Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Crypto from "effect/Crypto";
3import * as DateTime from "effect/DateTime";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Queue from "effect/Queue";
9import * as Ref from "effect/Ref";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12import {
13 DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,
14 AuthOrchestrationOperateScope,
15 AuthOrchestrationReadScope,
16 AuthReviewWriteScope,
17 AuthTerminalOperateScope,
18 AuthAccessReadScope,
19 AuthAccessStreamError,
20 type AuthAccessStreamEvent,
21 type AuthEnvironmentScope,
22 AuthSessionId,
23 CommandId,
24 EventId,
25 type OrchestrationCommand,
26 type GitActionProgressEvent,
27 type GitManagerServiceError,
28 OrchestrationDispatchCommandError,
29 type OrchestrationEvent,
30 type OrchestrationShellStreamEvent,
31 OrchestrationGetFullThreadDiffError,
32 OrchestrationGetSnapshotError,
33 OrchestrationGetTurnDiffError,
34 ORCHESTRATION_WS_METHODS,
35 ProjectSearchEntriesError,
36 ProjectWriteFileError,
37 OrchestrationReplayEventsError,
38 FilesystemBrowseError,
39 EnvironmentAuthorizationError,
40 ThreadId,
41 type TerminalAttachStreamEvent,
42 type TerminalError,
43 type TerminalEvent,
44 type TerminalMetadataStreamEvent,
45 WS_METHODS,
46 WsRpcGroup,
47} from "@t3tools/contracts";
48import { clamp } from "effect/Number";
49import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http";
50import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
51
52import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery.ts";
53import { ServerConfig } from "./config.ts";
54import { Keybindings } from "./keybindings.ts";
55import * as ExternalLauncher from "./process/externalLauncher.ts";
56import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
57import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
58import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
59import {
60 observeRpcEffect as instrumentRpcEffect,
61 observeRpcStream as instrumentRpcStream,
62 observeRpcStreamEffect as instrumentRpcStreamEffect,
63} from "./observability/RpcInstrumentation.ts";
64import { ProviderRegistry } from "./provider/Services/ProviderRegistry.ts";
65import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
66import { ServerLifecycleEvents } from "./serverLifecycleEvents.ts";
67import { ServerRuntimeStartup } from "./serverRuntimeStartup.ts";
68import { redactServerSettingsForClient, ServerSettingsService } from "./serverSettings.ts";
69import { TerminalManager } from "./terminal/Services/Manager.ts";
70import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts";
71import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts";
72import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths.ts";
73import { VcsStatusBroadcaster } from "./vcs/VcsStatusBroadcaster.ts";
74import { VcsProvisioningService } from "./vcs/VcsProvisioningService.ts";
75import { GitWorkflowService } from "./git/GitWorkflowService.ts";
76import { ReviewService } from "./review/ReviewService.ts";
77import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner.ts";
78import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";
79import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
80import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
81import type { AuthenticatedSession } from "./auth/EnvironmentAuth.ts";
82import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
83import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
84import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
85import * as SourceControlDiscoveryLayer from "./sourceControl/SourceControlDiscovery.ts";
86import { SourceControlRepositoryService } from "./sourceControl/SourceControlRepositoryService.ts";
87import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
88import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
89import * as GitHubCli from "./sourceControl/GitHubCli.ts";
90import * as GitLabCli from "./sourceControl/GitLabCli.ts";
91import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
92import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
93import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
94import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
95import * as VcsProcess from "./vcs/VcsProcess.ts";
96import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
97import * as SessionStore from "./auth/SessionStore.ts";
98import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
99const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
100const isWorkspacePathOutsideRootError = Schema.is(WorkspacePathOutsideRootError);
101
102const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
103
104function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
105 OrchestrationEvent,
106 {
107 type:
108 | "thread.message-sent"
109 | "thread.proposed-plan-upserted"
110 | "thread.activity-appended"
111 | "thread.turn-diff-completed"
112 | "thread.reverted"
113 | "thread.session-set";
114 }
115> {
116 return (
117 event.type === "thread.message-sent" ||
118 event.type === "thread.proposed-plan-upserted" ||
119 event.type === "thread.activity-appended" ||
120 event.type === "thread.turn-diff-completed" ||
121 event.type === "thread.reverted" ||
122 event.type === "thread.session-set"
123 );
124}
125
126const PROVIDER_STATUS_DEBOUNCE_MS = 200;
127
128const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
129 [ORCHESTRATION_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope],
130 [ORCHESTRATION_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope],
131 [ORCHESTRATION_WS_METHODS.getFullThreadDiff, AuthOrchestrationReadScope],
132 [ORCHESTRATION_WS_METHODS.replayEvents, AuthOrchestrationReadScope],
133 [ORCHESTRATION_WS_METHODS.subscribeShell, AuthOrchestrationReadScope],
134 [ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot, AuthOrchestrationReadScope],
135 [ORCHESTRATION_WS_METHODS.subscribeThread, AuthOrchestrationReadScope],
136 [WS_METHODS.serverGetConfig, AuthOrchestrationReadScope],
137 [WS_METHODS.serverRefreshProviders, AuthOrchestrationOperateScope],
138 [WS_METHODS.serverUpdateProvider, AuthOrchestrationOperateScope],
139 [WS_METHODS.serverUpsertKeybinding, AuthOrchestrationOperateScope],
140 [WS_METHODS.serverRemoveKeybinding, AuthOrchestrationOperateScope],
141 [WS_METHODS.serverGetSettings, AuthOrchestrationReadScope],
142 [WS_METHODS.serverUpdateSettings, AuthOrchestrationOperateScope],
143 [WS_METHODS.serverDiscoverSourceControl, AuthOrchestrationReadScope],
144 [WS_METHODS.serverGetTraceDiagnostics, AuthOrchestrationReadScope],
145 [WS_METHODS.serverGetProcessDiagnostics, AuthOrchestrationReadScope],
146 [WS_METHODS.serverGetProcessResourceHistory, AuthOrchestrationReadScope],
147 [WS_METHODS.serverSignalProcess, AuthOrchestrationOperateScope],
148 [WS_METHODS.sourceControlLookupRepository, AuthOrchestrationReadScope],
149 [WS_METHODS.sourceControlCloneRepository, AuthOrchestrationOperateScope],
150 [WS_METHODS.sourceControlPublishRepository, AuthOrchestrationOperateScope],
151 [WS_METHODS.projectsSearchEntries, AuthOrchestrationReadScope],
152 [WS_METHODS.projectsWriteFile, AuthOrchestrationOperateScope],
153 [WS_METHODS.shellOpenInEditor, AuthOrchestrationOperateScope],
154 [WS_METHODS.filesystemBrowse, AuthOrchestrationReadScope],
155 [WS_METHODS.subscribeVcsStatus, AuthOrchestrationReadScope],
156 [WS_METHODS.vcsRefreshStatus, AuthOrchestrationReadScope],
157 [WS_METHODS.vcsPull, AuthOrchestrationOperateScope],
158 [WS_METHODS.gitRunStackedAction, AuthOrchestrationOperateScope],
159 [WS_METHODS.gitResolvePullRequest, AuthOrchestrationOperateScope],
160 [WS_METHODS.gitPreparePullRequestThread, AuthOrchestrationOperateScope],
161 [WS_METHODS.vcsListRefs, AuthOrchestrationReadScope],
162 [WS_METHODS.vcsCreateWorktree, AuthOrchestrationOperateScope],
163 [WS_METHODS.vcsRemoveWorktree, AuthOrchestrationOperateScope],
164 [WS_METHODS.vcsCreateRef, AuthOrchestrationOperateScope],
165 [WS_METHODS.vcsSwitchRef, AuthOrchestrationOperateScope],
166 [WS_METHODS.vcsInit, AuthOrchestrationOperateScope],
167 [WS_METHODS.reviewGetDiffPreview, AuthReviewWriteScope],
168 [WS_METHODS.terminalOpen, AuthTerminalOperateScope],
169 [WS_METHODS.terminalAttach, AuthTerminalOperateScope],
170 [WS_METHODS.terminalWrite, AuthTerminalOperateScope],
171 [WS_METHODS.terminalResize, AuthTerminalOperateScope],
172 [WS_METHODS.terminalClear, AuthTerminalOperateScope],
173 [WS_METHODS.terminalRestart, AuthTerminalOperateScope],
174 [WS_METHODS.terminalClose, AuthTerminalOperateScope],
175 [WS_METHODS.subscribeTerminalEvents, AuthTerminalOperateScope],
176 [WS_METHODS.subscribeTerminalMetadata, AuthTerminalOperateScope],
177 [WS_METHODS.subscribeServerConfig, AuthOrchestrationReadScope],
178 [WS_METHODS.subscribeServerLifecycle, AuthOrchestrationReadScope],
179 [WS_METHODS.subscribeAuthAccess, AuthAccessReadScope],
180]);
181
182function toAuthAccessStreamEvent(
183 change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,
184 revision: number,
185 currentSessionId: AuthSessionId,
186): AuthAccessStreamEvent {
187 switch (change.type) {
188 case "pairingLinkUpserted":
189 return {
190 version: 1,
191 revision,
192 type: "pairingLinkUpserted",
193 payload: change.pairingLink,
194 };
195 case "pairingLinkRemoved":
196 return {
197 version: 1,
198 revision,
199 type: "pairingLinkRemoved",
200 payload: { id: change.id },
201 };
202 case "clientUpserted":
203 return {
204 version: 1,
205 revision,
206 type: "clientUpserted",
207 payload: {
208 ...change.clientSession,
209 current: change.clientSession.sessionId === currentSessionId,
210 },
211 };
212 case "clientRemoved":
213 return {
214 version: 1,
215 revision,
216 type: "clientRemoved",
217 payload: { sessionId: change.sessionId },
218 };
219 }
220}
221
222const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
223 WsRpcGroup.toLayer(
224 Effect.gen(function* () {
225 const currentSessionId = currentSession.sessionId;
226 const crypto = yield* Crypto.Crypto;
227 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
228 const orchestrationEngine = yield* OrchestrationEngineService;
229 const checkpointDiffQuery = yield* CheckpointDiffQuery;
230 const keybindings = yield* Keybindings;
231 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
232 const gitWorkflow = yield* GitWorkflowService;
233 const review = yield* ReviewService;
234 const vcsProvisioning = yield* VcsProvisioningService;
235 const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
236 const terminalManager = yield* TerminalManager;
237 const providerRegistry = yield* ProviderRegistry;
238 const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
239 const config = yield* ServerConfig;
240 const lifecycleEvents = yield* ServerLifecycleEvents;
241 const serverSettings = yield* ServerSettingsService;
242 const startup = yield* ServerRuntimeStartup;
243 const workspaceEntries = yield* WorkspaceEntries;
244 const workspaceFileSystem = yield* WorkspaceFileSystem;
245 const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
246 const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
247 const serverEnvironment = yield* ServerEnvironment;
248 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
249 const sourceControlDiscovery = yield* SourceControlDiscoveryLayer.SourceControlDiscovery;
250 const automaticGitFetchInterval = serverSettings.getSettings.pipe(
251 Effect.map((settings) => settings.automaticGitFetchInterval),
252 Effect.catch((cause) =>
253 Effect.logWarning("Failed to read automatic Git fetch interval setting", {
254 detail: cause.message,
255 }).pipe(Effect.as(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
256 ),
257 );
258 const sourceControlRepositories = yield* SourceControlRepositoryService;
259 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
260 const sessions = yield* SessionStore.SessionStore;
261 const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
262 const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor;
263 const authorizationError = (requiredScope: AuthEnvironmentScope) =>
264 new EnvironmentAuthorizationError({
265 message: `The authenticated token is missing required scope: ${requiredScope}.`,
266 requiredScope,
267 });
268 const authorizeEffect = <A, E, R>(
269 requiredScope: AuthEnvironmentScope,
270 effect: Effect.Effect<A, E, R>,
271 ): Effect.Effect<A, E | EnvironmentAuthorizationError, R> =>
272 currentSession.scopes.includes(requiredScope)
273 ? effect
274 : Effect.fail(authorizationError(requiredScope));
275 const authorizeStream = <A, E, R>(
276 requiredScope: AuthEnvironmentScope,
277 stream: Stream.Stream<A, E, R>,
278 ): Stream.Stream<A, E | EnvironmentAuthorizationError, R> =>
279 currentSession.scopes.includes(requiredScope)
280 ? stream
281 : Stream.fail(authorizationError(requiredScope));
282 const requiredScopeForMethod = (method: string): AuthEnvironmentScope => {
283 const requiredScope = RPC_REQUIRED_SCOPE.get(method);
284 if (requiredScope === undefined) {
285 throw new Error(`RPC method ${method} has no declared authorization scope.`);
286 }
287 return requiredScope;
288 };
289 const observeRpcEffect = <A, E, R>(
290 method: string,
291 effect: Effect.Effect<A, E, R>,
292 traceAttributes?: Readonly<Record<string, unknown>>,
293 ) =>
294 instrumentRpcEffect(
295 method,
296 authorizeEffect(requiredScopeForMethod(method), effect),
297 traceAttributes,
298 );
299 const observeRpcStream = <A, E, R>(
300 method: string,
301 stream: Stream.Stream<A, E, R>,
302 traceAttributes?: Readonly<Record<string, unknown>>,
303 ) =>
304 instrumentRpcStream(
305 method,
306 authorizeStream(requiredScopeForMethod(method), stream),
307 traceAttributes,
308 );
309 const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(
310 method: string,
311 effect: Effect.Effect<
312 Stream.Stream<A, StreamError, StreamContext>,
313 EffectError,
314 EffectContext
315 >,
316 traceAttributes?: Readonly<Record<string, unknown>>,
317 ) =>
318 instrumentRpcStreamEffect(
319 method,
320 authorizeEffect(requiredScopeForMethod(method), effect),
321 traceAttributes,
322 );
323 const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>
324 isOrchestrationDispatchCommandError(cause)
325 ? cause
326 : new OrchestrationDispatchCommandError({
327 message: cause instanceof Error ? cause.message : fallbackMessage,
328 cause,
329 });
330 const randomUUID = crypto.randomUUIDv4.pipe(
331 Effect.mapError((cause) =>
332 toDispatchCommandError(cause, "Failed to generate orchestration command identifier."),
333 ),
334 );
335 const serverEventId = randomUUID.pipe(Effect.map(EventId.make));
336 const serverCommandId = (tag: string) =>
337 randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
338
339 const loadAuthAccessSnapshot = () =>
340 Effect.all({
341 pairingLinks: serverAuth.listPairingLinks(),
342 clientSessions: serverAuth.listClientSessions(currentSessionId),
343 }).pipe(
344 Effect.mapError(
345 (error) =>
346 new AuthAccessStreamError({
347 message: error.message,
348 }),
349 ),
350 );
351
352 const appendSetupScriptActivity = (input: {
353 readonly threadId: ThreadId;
354 readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed";
355 readonly summary: string;
356 readonly createdAt: string;
357 readonly payload: Record<string, unknown>;
358 readonly tone: "info" | "error";
359 }) =>
360 Effect.all({
361 commandId: serverCommandId("setup-script-activity"),
362 activityId: serverEventId,
363 }).pipe(
364 Effect.flatMap(({ commandId, activityId }) =>
365 orchestrationEngine.dispatch({
366 type: "thread.activity.append",
367 commandId,
368 threadId: input.threadId,
369 activity: {
370 id: activityId,
371 tone: input.tone,
372 kind: input.kind,
373 summary: input.summary,
374 payload: input.payload,
375 turnId: null,
376 createdAt: input.createdAt,
377 },
378 createdAt: input.createdAt,
379 }),
380 ),
381 );
382
383 const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {
384 const error = Cause.squash(cause);
385 return isOrchestrationDispatchCommandError(error)
386 ? error
387 : new OrchestrationDispatchCommandError({
388 message:
389 error instanceof Error ? error.message : "Failed to bootstrap thread turn start.",
390 cause,
391 });
392 };
393
394 const enrichProjectEvent = (
395 event: OrchestrationEvent,
396 ): Effect.Effect<OrchestrationEvent, never, never> => {
397 switch (event.type) {
398 case "project.created":
399 return repositoryIdentityResolver.resolve(event.payload.workspaceRoot).pipe(
400 Effect.map((repositoryIdentity) => ({
401 ...event,
402 payload: {
403 ...event.payload,
404 repositoryIdentity,
405 },
406 })),
407 );
408 case "project.meta-updated":
409 return Effect.gen(function* () {
410 const workspaceRoot =
411 event.payload.workspaceRoot ??
412 Option.match(
413 yield* projectionSnapshotQuery.getProjectShellById(event.payload.projectId),
414 {
415 onNone: () => null,
416 onSome: (project) => project.workspaceRoot,
417 },
418 ) ??
419 null;
420 if (workspaceRoot === null) {
421 return event;
422 }
423
424 const repositoryIdentity = yield* repositoryIdentityResolver.resolve(workspaceRoot);
425 return {
426 ...event,
427 payload: {
428 ...event.payload,
429 repositoryIdentity,
430 },
431 } satisfies OrchestrationEvent;
432 }).pipe(Effect.catch(() => Effect.succeed(event)));
433 default:
434 return Effect.succeed(event);
435 }
436 };
437
438 const enrichOrchestrationEvents = (events: ReadonlyArray<OrchestrationEvent>) =>
439 Effect.forEach(events, enrichProjectEvent, { concurrency: 4 });
440
441 const toShellStreamEvent = (
442 event: OrchestrationEvent,
443 ): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> => {
444 switch (event.type) {
445 case "project.created":
446 case "project.meta-updated":
447 return projectionSnapshotQuery.getProjectShellById(event.payload.projectId).pipe(
448 Effect.map((project) =>
449 Option.map(project, (nextProject) => ({
450 kind: "project-upserted" as const,
451 sequence: event.sequence,
452 project: nextProject,
453 })),
454 ),
455 Effect.catch(() => Effect.succeed(Option.none())),
456 );
457 case "project.deleted":
458 return Effect.succeed(
459 Option.some({
460 kind: "project-removed" as const,
461 sequence: event.sequence,
462 projectId: event.payload.projectId,
463 }),
464 );
465 case "thread.deleted":
466 case "thread.archived":
467 return Effect.succeed(
468 Option.some({
469 kind: "thread-removed" as const,
470 sequence: event.sequence,
471 threadId: event.payload.threadId,
472 }),
473 );
474 case "thread.unarchived":
475 return projectionSnapshotQuery.getThreadShellById(event.payload.threadId).pipe(
476 Effect.map((thread) =>
477 Option.map(thread, (nextThread) => ({
478 kind: "thread-upserted" as const,
479 sequence: event.sequence,
480 thread: nextThread,
481 })),
482 ),
483 Effect.catch(() => Effect.succeed(Option.none())),
484 );
485 default:
486 if (event.aggregateKind !== "thread") {
487 return Effect.succeed(Option.none());
488 }
489 return projectionSnapshotQuery
490 .getThreadShellById(ThreadId.make(event.aggregateId))
491 .pipe(
492 Effect.map((thread) =>
493 Option.map(thread, (nextThread) => ({
494 kind: "thread-upserted" as const,
495 sequence: event.sequence,
496 thread: nextThread,
497 })),
498 ),
499 Effect.catch(() => Effect.succeed(Option.none())),
500 );
501 }
502 };
503
504 const dispatchBootstrapTurnStart = (
505 command: Extract<OrchestrationCommand, { type: "thread.turn.start" }>,
506 ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>
507 Effect.gen(function* () {
508 const bootstrap = command.bootstrap;
509 const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command;
510 let createdThread = false;
511 let targetProjectId = bootstrap?.createThread?.projectId;
512 let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd;
513 let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null;
514
515 const cleanupCreatedThread = () =>
516 createdThread
517 ? serverCommandId("bootstrap-thread-delete").pipe(
518 Effect.flatMap((commandId) =>
519 orchestrationEngine.dispatch({
520 type: "thread.delete",
521 commandId,
522 threadId: command.threadId,
523 }),
524 ),
525 Effect.ignoreCause({ log: true }),
526 )
527 : Effect.void;
528
529 const recordSetupScriptLaunchFailure = (input: {
530 readonly error: unknown;
531 readonly requestedAt: string;
532 readonly worktreePath: string;
533 }) => {
534 const detail =
535 input.error instanceof Error ? input.error.message : "Unknown setup failure.";
536 return appendSetupScriptActivity({
537 threadId: command.threadId,
538 kind: "setup-script.failed",
539 summary: "Setup script failed to start",
540 createdAt: input.requestedAt,
541 payload: {
542 detail,
543 worktreePath: input.worktreePath,
544 },
545 tone: "error",
546 }).pipe(
547 Effect.ignoreCause({ log: false }),
548 Effect.flatMap(() =>
549 Effect.logWarning("bootstrap turn start failed to launch setup script", {
550 threadId: command.threadId,
551 worktreePath: input.worktreePath,
552 detail,
553 }),
554 ),
555 );
556 };
557
558 const recordSetupScriptStarted = (input: {
559 readonly requestedAt: string;
560 readonly worktreePath: string;
561 readonly scriptId: string;
562 readonly scriptName: string;
563 readonly terminalId: string;
564 }) =>
565 Effect.gen(function* () {
566 const startedAt = yield* nowIso;
567 const payload = {
568 scriptId: input.scriptId,
569 scriptName: input.scriptName,
570 terminalId: input.terminalId,
571 worktreePath: input.worktreePath,
572 };
573 yield* Effect.all([
574 appendSetupScriptActivity({
575 threadId: command.threadId,
576 kind: "setup-script.requested",
577 summary: "Starting setup script",
578 createdAt: input.requestedAt,
579 payload,
580 tone: "info",
581 }),
582 appendSetupScriptActivity({
583 threadId: command.threadId,
584 kind: "setup-script.started",
585 summary: "Setup script started",
586 createdAt: startedAt,
587 payload,
588 tone: "info",
589 }),
590 ]).pipe(
591 Effect.asVoid,
592 Effect.catch((error) =>
593 Effect.logWarning(
594 "bootstrap turn start launched setup script but failed to record setup activity",
595 {
596 threadId: command.threadId,
597 worktreePath: input.worktreePath,
598 scriptId: input.scriptId,
599 terminalId: input.terminalId,
600 detail: error.message,
601 },
602 ),
603 ),
604 );
605 });
606
607 const runSetupProgram = () =>
608 Effect.gen(function* () {
609 if (!bootstrap?.runSetupScript || !targetWorktreePath) {
610 return;
611 }
612 const worktreePath = targetWorktreePath;
613 const requestedAt = yield* nowIso;
614 yield* projectSetupScriptRunner
615 .runForThread({
616 threadId: command.threadId,
617 ...(targetProjectId ? { projectId: targetProjectId } : {}),
618 ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),
619 worktreePath,
620 })
621 .pipe(
622 Effect.matchEffect({
623 onFailure: (error) =>
624 recordSetupScriptLaunchFailure({
625 error,
626 requestedAt,
627 worktreePath,
628 }),
629 onSuccess: (setupResult) => {
630 if (setupResult.status !== "started") {
631 return Effect.void;
632 }
633 return recordSetupScriptStarted({
634 requestedAt,
635 worktreePath,
636 scriptId: setupResult.scriptId,
637 scriptName: setupResult.scriptName,
638 terminalId: setupResult.terminalId,
639 });
640 },
641 }),
642 );
643 });
644
645 const bootstrapProgram = Effect.gen(function* () {
646 if (bootstrap?.createThread) {
647 yield* orchestrationEngine.dispatch({
648 type: "thread.create",
649 commandId: yield* serverCommandId("bootstrap-thread-create"),
650 threadId: command.threadId,
651 projectId: bootstrap.createThread.projectId,
652 title: bootstrap.createThread.title,
653 modelSelection: bootstrap.createThread.modelSelection,
654 runtimeMode: bootstrap.createThread.runtimeMode,
655 interactionMode: bootstrap.createThread.interactionMode,
656 branch: bootstrap.createThread.branch,
657 worktreePath: bootstrap.createThread.worktreePath,
658 createdAt: bootstrap.createThread.createdAt,
659 });
660 createdThread = true;
661 }
662
663 if (bootstrap?.prepareWorktree) {
664 const worktree = yield* gitWorkflow.createWorktree({
665 cwd: bootstrap.prepareWorktree.projectCwd,
666 refName: bootstrap.prepareWorktree.baseBranch,
667 newRefName: bootstrap.prepareWorktree.branch,
668 path: null,
669 });
670 targetWorktreePath = worktree.worktree.path;
671 yield* orchestrationEngine.dispatch({
672 type: "thread.meta.update",
673 commandId: yield* serverCommandId("bootstrap-thread-meta-update"),
674 threadId: command.threadId,
675 branch: worktree.worktree.refName,
676 worktreePath: targetWorktreePath,
677 });
678 yield* refreshGitStatus(targetWorktreePath);
679 }
680
681 yield* runSetupProgram();
682
683 return yield* orchestrationEngine.dispatch(finalTurnStartCommand);
684 });
685
686 return yield* bootstrapProgram.pipe(
687 Effect.catchCause((cause) => {
688 const dispatchError = toBootstrapDispatchCommandCauseError(cause);
689 if (Cause.hasInterruptsOnly(cause)) {
690 return Effect.fail(dispatchError);
691 }
692 return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError)));
693 }),
694 );
695 });
696
697 const dispatchNormalizedCommand = (
698 normalizedCommand: OrchestrationCommand,
699 ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => {
700 const dispatchEffect =
701 normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap
702 ? dispatchBootstrapTurnStart(normalizedCommand)
703 : orchestrationEngine
704 .dispatch(normalizedCommand)
705 .pipe(
706 Effect.mapError((cause) =>
707 toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
708 ),
709 );
710
711 return startup
712 .enqueueCommand(dispatchEffect)
713 .pipe(
714 Effect.mapError((cause) =>
715 toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
716 ),
717 );
718 };
719
720 const loadServerConfig = Effect.gen(function* () {
721 const keybindingsConfig = yield* keybindings.loadConfigState;
722 const providers = yield* providerRegistry.getProviders;
723 const settings = redactServerSettingsForClient(yield* serverSettings.getSettings);
724 const environment = yield* serverEnvironment.getDescriptor;
725 const auth = yield* serverAuth.getDescriptor();
726
727 return {
728 environment,
729 auth,
730 cwd: config.cwd,
731 keybindingsConfigPath: config.keybindingsConfigPath,
732 keybindings: keybindingsConfig.keybindings,
733 issues: keybindingsConfig.issues,
734 providers,
735 availableEditors: ExternalLauncher.resolveAvailableEditors(),
736 observability: {
737 logsDirectoryPath: config.logsDir,
738 localTracingEnabled: true,
739 ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),
740 otlpTracesEnabled: config.otlpTracesUrl !== undefined,
741 ...(config.otlpMetricsUrl !== undefined
742 ? { otlpMetricsUrl: config.otlpMetricsUrl }
743 : {}),
744 otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,
745 },
746 settings,
747 };
748 });
749
750 const refreshGitStatus = (cwd: string) =>
751 vcsStatusBroadcaster
752 .refreshStatus(cwd)
753 .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
754
755 return WsRpcGroup.of({
756 [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
757 observeRpcEffect(
758 ORCHESTRATION_WS_METHODS.dispatchCommand,
759 Effect.gen(function* () {
760 const normalizedCommand = yield* normalizeDispatchCommand(command);
761 const shouldStopSessionAfterArchive =
762 normalizedCommand.type === "thread.archive"
763 ? yield* projectionSnapshotQuery
764 .getThreadShellById(normalizedCommand.threadId)
765 .pipe(
766 Effect.map(
767 Option.match({
768 onNone: () => false,
769 onSome: (thread) =>
770 thread.session !== null && thread.session.status !== "stopped",
771 }),
772 ),
773 Effect.catch(() => Effect.succeed(false)),
774 )
775 : false;
776 const result = yield* dispatchNormalizedCommand(normalizedCommand);
777 if (normalizedCommand.type === "thread.archive") {
778 if (shouldStopSessionAfterArchive) {
779 yield* Effect.gen(function* () {
780 const stopCommand = yield* normalizeDispatchCommand({
781 type: "thread.session.stop",
782 commandId: CommandId.make(
783 `session-stop-for-archive:${normalizedCommand.commandId}`,
784 ),
785 threadId: normalizedCommand.threadId,
786 createdAt: yield* nowIso,
787 });
788
789 yield* dispatchNormalizedCommand(stopCommand);
790 }).pipe(
791 Effect.catchCause((cause) =>
792 Effect.logWarning("failed to stop provider session during archive", {
793 threadId: normalizedCommand.threadId,
794 cause,
795 }),
796 ),
797 );
798 }
799
800 yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
801 Effect.catch((error) =>
802 Effect.logWarning("failed to close thread terminals after archive", {
803 threadId: normalizedCommand.threadId,
804 error: error.message,
805 }),
806 ),
807 );
808 }
809 return result;
810 }).pipe(
811 Effect.mapError((cause) =>
812 isOrchestrationDispatchCommandError(cause)
813 ? cause
814 : new OrchestrationDispatchCommandError({
815 message: "Failed to dispatch orchestration command",
816 cause,
817 }),
818 ),
819 ),
820 { "rpc.aggregate": "orchestration" },
821 ),
822 [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>
823 observeRpcEffect(
824 ORCHESTRATION_WS_METHODS.getTurnDiff,
825 checkpointDiffQuery.getTurnDiff(input).pipe(
826 Effect.mapError(
827 (cause) =>
828 new OrchestrationGetTurnDiffError({
829 message: "Failed to load turn diff",
830 cause,
831 }),
832 ),
833 ),
834 { "rpc.aggregate": "orchestration" },
835 ),
836 [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
837 observeRpcEffect(
838 ORCHESTRATION_WS_METHODS.getFullThreadDiff,
839 checkpointDiffQuery.getFullThreadDiff(input).pipe(
840 Effect.mapError(
841 (cause) =>
842 new OrchestrationGetFullThreadDiffError({
843 message: "Failed to load full thread diff",
844 cause,
845 }),
846 ),
847 ),
848 { "rpc.aggregate": "orchestration" },
849 ),
850 [ORCHESTRATION_WS_METHODS.replayEvents]: (input) =>
851 observeRpcEffect(
852 ORCHESTRATION_WS_METHODS.replayEvents,
853 Stream.runCollect(
854 orchestrationEngine.readEvents(
855 clamp(input.fromSequenceExclusive, {
856 maximum: Number.MAX_SAFE_INTEGER,
857 minimum: 0,
858 }),
859 ),
860 ).pipe(
861 Effect.map((events) => Array.from(events)),
862 Effect.flatMap(enrichOrchestrationEvents),
863 Effect.mapError(
864 (cause) =>
865 new OrchestrationReplayEventsError({
866 message: "Failed to replay orchestration events",
867 cause,
868 }),
869 ),
870 ),
871 { "rpc.aggregate": "orchestration" },
872 ),
873 [ORCHESTRATION_WS_METHODS.subscribeShell]: (_input) =>
874 observeRpcStreamEffect(
875 ORCHESTRATION_WS_METHODS.subscribeShell,
876 Effect.gen(function* () {
877 const snapshot = yield* projectionSnapshotQuery.getShellSnapshot().pipe(
878 Effect.tapError((cause) =>
879 Effect.logError("orchestration shell snapshot load failed", { cause }),
880 ),
881 Effect.mapError(
882 (cause) =>
883 new OrchestrationGetSnapshotError({
884 message: "Failed to load orchestration shell snapshot",
885 cause,
886 }),
887 ),
888 );
889
890 const liveStream = orchestrationEngine.streamDomainEvents.pipe(
891 Stream.mapEffect(toShellStreamEvent),
892 Stream.flatMap((event) =>
893 Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,
894 ),
895 );
896
897 return Stream.concat(
898 Stream.make({
899 kind: "snapshot" as const,
900 snapshot,
901 }),
902 liveStream,
903 );
904 }),
905 { "rpc.aggregate": "orchestration" },
906 ),
907 [ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: (_input) =>
908 observeRpcEffect(
909 ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,
910 projectionSnapshotQuery.getArchivedShellSnapshot().pipe(
911 Effect.tapError((cause) =>
912 Effect.logError("orchestration archived shell snapshot load failed", { cause }),
913 ),
914 Effect.mapError(
915 (cause) =>
916 new OrchestrationGetSnapshotError({
917 message: "Failed to load archived orchestration shell snapshot",
918 cause,
919 }),
920 ),
921 ),
922 { "rpc.aggregate": "orchestration" },
923 ),
924 [ORCHESTRATION_WS_METHODS.subscribeThread]: (input) =>
925 observeRpcStreamEffect(
926 ORCHESTRATION_WS_METHODS.subscribeThread,
927 Effect.gen(function* () {
928 const [threadDetail, snapshotSequence] = yield* Effect.all([
929 projectionSnapshotQuery.getThreadDetailById(input.threadId).pipe(
930 Effect.mapError(
931 (cause) =>
932 new OrchestrationGetSnapshotError({
933 message: `Failed to load thread ${input.threadId}`,
934 cause,
935 }),
936 ),
937 ),
938 projectionSnapshotQuery.getSnapshotSequence().pipe(
939 Effect.map(({ snapshotSequence }) => snapshotSequence),
940 Effect.mapError(
941 (cause) =>
942 new OrchestrationGetSnapshotError({
943 message: "Failed to load orchestration snapshot sequence",
944 cause,
945 }),
946 ),
947 ),
948 ]);
949
950 if (Option.isNone(threadDetail)) {
951 return yield* new OrchestrationGetSnapshotError({
952 message: `Thread ${input.threadId} was not found`,
953 cause: input.threadId,
954 });
955 }
956
957 const liveStream = orchestrationEngine.streamDomainEvents.pipe(
958 Stream.filter(
959 (event) =>
960 event.aggregateKind === "thread" &&
961 event.aggregateId === input.threadId &&
962 isThreadDetailEvent(event),
963 ),
964 Stream.map((event) => ({
965 kind: "event" as const,
966 event,
967 })),
968 );
969
970 return Stream.concat(
971 Stream.make({
972 kind: "snapshot" as const,
973 snapshot: {
974 snapshotSequence,
975 thread: threadDetail.value,
976 },
977 }),
978 liveStream,
979 );
980 }),
981 { "rpc.aggregate": "orchestration" },
982 ),
983 [WS_METHODS.serverGetConfig]: (_input) =>
984 observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {
985 "rpc.aggregate": "server",
986 }),
987 [WS_METHODS.serverRefreshProviders]: (input) =>
988 observeRpcEffect(
989 WS_METHODS.serverRefreshProviders,
990 (input.instanceId !== undefined
991 ? providerRegistry.refreshInstance(input.instanceId)
992 : providerRegistry.refresh()
993 ).pipe(Effect.map((providers) => ({ providers }))),
994 { "rpc.aggregate": "server" },
995 ),
996 [WS_METHODS.serverUpdateProvider]: (input) =>
997 observeRpcEffect(
998 WS_METHODS.serverUpdateProvider,
999 providerMaintenanceRunner.updateProvider(input),
1000 {
1001 "rpc.aggregate": "server",
1002 },
1003 ),
1004 [WS_METHODS.serverUpsertKeybinding]: (rule) =>
1005 observeRpcEffect(
1006 WS_METHODS.serverUpsertKeybinding,
1007 Effect.gen(function* () {
1008 const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
1009 return { keybindings: keybindingsConfig, issues: [] };
1010 }),
1011 { "rpc.aggregate": "server" },
1012 ),
1013 [WS_METHODS.serverRemoveKeybinding]: (rule) =>
1014 observeRpcEffect(
1015 WS_METHODS.serverRemoveKeybinding,
1016 Effect.gen(function* () {
1017 const keybindingsConfig = yield* keybindings.removeKeybindingRule(rule);
1018 return { keybindings: keybindingsConfig, issues: [] };
1019 }),
1020 { "rpc.aggregate": "server" },
1021 ),
1022 [WS_METHODS.serverGetSettings]: (_input) =>
1023 observeRpcEffect(
1024 WS_METHODS.serverGetSettings,
1025 serverSettings.getSettings.pipe(Effect.map(redactServerSettingsForClient)),
1026 {
1027 "rpc.aggregate": "server",
1028 },
1029 ),
1030 [WS_METHODS.serverUpdateSettings]: ({ patch }) =>
1031 observeRpcEffect(
1032 WS_METHODS.serverUpdateSettings,
1033 serverSettings.updateSettings(patch).pipe(Effect.map(redactServerSettingsForClient)),
1034 {
1035 "rpc.aggregate": "server",
1036 },
1037 ),
1038 [WS_METHODS.serverDiscoverSourceControl]: (_input) =>
1039 observeRpcEffect(
1040 WS_METHODS.serverDiscoverSourceControl,
1041 sourceControlDiscovery.discover,
1042 {
1043 "rpc.aggregate": "server",
1044 },
1045 ),
1046 [WS_METHODS.serverGetTraceDiagnostics]: (_input) =>
1047 observeRpcEffect(
1048 WS_METHODS.serverGetTraceDiagnostics,
1049 TraceDiagnostics.readTraceDiagnostics({
1050 traceFilePath: config.serverTracePath,
1051 maxFiles: config.traceMaxFiles,
1052 }),
1053 {
1054 "rpc.aggregate": "server",
1055 },
1056 ),
1057 [WS_METHODS.serverGetProcessDiagnostics]: (_input) =>
1058 observeRpcEffect(WS_METHODS.serverGetProcessDiagnostics, processDiagnostics.read, {
1059 "rpc.aggregate": "server",
1060 }),
1061 [WS_METHODS.serverGetProcessResourceHistory]: (input) =>
1062 observeRpcEffect(
1063 WS_METHODS.serverGetProcessResourceHistory,
1064 processResourceMonitor.readHistory(input),
1065 {
1066 "rpc.aggregate": "server",
1067 },
1068 ),
1069 [WS_METHODS.serverSignalProcess]: (input) =>
1070 observeRpcEffect(WS_METHODS.serverSignalProcess, processDiagnostics.signal(input), {
1071 "rpc.aggregate": "server",
1072 }),
1073 [WS_METHODS.sourceControlLookupRepository]: (input) =>
1074 observeRpcEffect(
1075 WS_METHODS.sourceControlLookupRepository,
1076 sourceControlRepositories.lookupRepository(input),
1077 {
1078 "rpc.aggregate": "source-control",
1079 },
1080 ),
1081 [WS_METHODS.sourceControlCloneRepository]: (input) =>
1082 observeRpcEffect(
1083 WS_METHODS.sourceControlCloneRepository,
1084 sourceControlRepositories.cloneRepository(input),
1085 {
1086 "rpc.aggregate": "source-control",
1087 },
1088 ),
1089 [WS_METHODS.sourceControlPublishRepository]: (input) =>
1090 observeRpcEffect(
1091 WS_METHODS.sourceControlPublishRepository,
1092 sourceControlRepositories
1093 .publishRepository(input)
1094 .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
1095 {
1096 "rpc.aggregate": "source-control",
1097 },
1098 ),
1099 [WS_METHODS.projectsSearchEntries]: (input) =>
1100 observeRpcEffect(
1101 WS_METHODS.projectsSearchEntries,
1102 workspaceEntries.search(input).pipe(
1103 Effect.mapError(
1104 (cause) =>
1105 new ProjectSearchEntriesError({
1106 message: `Failed to search workspace entries: ${cause.detail}`,
1107 cause,
1108 }),
1109 ),
1110 ),
1111 { "rpc.aggregate": "workspace" },
1112 ),
1113 [WS_METHODS.projectsWriteFile]: (input) =>
1114 observeRpcEffect(
1115 WS_METHODS.projectsWriteFile,
1116 workspaceFileSystem.writeFile(input).pipe(
1117 Effect.mapError((cause) => {
1118 const message = isWorkspacePathOutsideRootError(cause)
1119 ? "Workspace file path must stay within the project root."
1120 : "Failed to write workspace file";
1121 return new ProjectWriteFileError({
1122 message,
1123 cause,
1124 });
1125 }),
1126 ),
1127 { "rpc.aggregate": "workspace" },
1128 ),
1129 [WS_METHODS.shellOpenInEditor]: (input) =>
1130 observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), {
1131 "rpc.aggregate": "workspace",
1132 }),
1133 [WS_METHODS.filesystemBrowse]: (input) =>
1134 observeRpcEffect(
1135 WS_METHODS.filesystemBrowse,
1136 workspaceEntries.browse(input).pipe(
1137 Effect.mapError(
1138 (cause) =>
1139 new FilesystemBrowseError({
1140 message: cause.detail,
1141 cause,
1142 }),
1143 ),
1144 ),
1145 { "rpc.aggregate": "workspace" },
1146 ),
1147 [WS_METHODS.subscribeVcsStatus]: (input) =>
1148 observeRpcStream(
1149 WS_METHODS.subscribeVcsStatus,
1150 vcsStatusBroadcaster.streamStatus(input, {
1151 automaticRemoteRefreshInterval: automaticGitFetchInterval,
1152 }),
1153 {
1154 "rpc.aggregate": "vcs",
1155 },
1156 ),
1157 [WS_METHODS.vcsRefreshStatus]: (input) =>
1158 observeRpcEffect(
1159 WS_METHODS.vcsRefreshStatus,
1160 vcsStatusBroadcaster.refreshStatus(input.cwd),
1161 {
1162 "rpc.aggregate": "vcs",
1163 },
1164 ),
1165 [WS_METHODS.vcsPull]: (input) =>
1166 observeRpcEffect(
1167 WS_METHODS.vcsPull,
1168 gitWorkflow.pullCurrentBranch(input.cwd).pipe(
1169 Effect.matchCauseEffect({
1170 onFailure: (cause) => Effect.failCause(cause),
1171 onSuccess: (result) =>
1172 refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)),
1173 }),
1174 ),
1175 { "rpc.aggregate": "git" },
1176 ),
1177 [WS_METHODS.gitRunStackedAction]: (input) =>
1178 observeRpcStream(
1179 WS_METHODS.gitRunStackedAction,
1180 Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
1181 gitWorkflow
1182 .runStackedAction(input, {
1183 actionId: input.actionId,
1184 progressReporter: {
1185 publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),
1186 },
1187 })
1188 .pipe(
1189 Effect.matchCauseEffect({
1190 onFailure: (cause) => Queue.failCause(queue, cause),
1191 onSuccess: () =>
1192 refreshGitStatus(input.cwd).pipe(
1193 Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)),
1194 ),
1195 }),
1196 ),
1197 ),
1198 { "rpc.aggregate": "vcs" },
1199 ),
1200 [WS_METHODS.gitResolvePullRequest]: (input) =>
1201 observeRpcEffect(
1202 WS_METHODS.gitResolvePullRequest,
1203 gitWorkflow.resolvePullRequest(input),
1204 {
1205 "rpc.aggregate": "git",
1206 },
1207 ),
1208 [WS_METHODS.gitPreparePullRequestThread]: (input) =>
1209 observeRpcEffect(
1210 WS_METHODS.gitPreparePullRequestThread,
1211 gitWorkflow
1212 .preparePullRequestThread(input)
1213 .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
1214 { "rpc.aggregate": "git" },
1215 ),
1216 [WS_METHODS.vcsListRefs]: (input) =>
1217 observeRpcEffect(WS_METHODS.vcsListRefs, gitWorkflow.listRefs(input), {
1218 "rpc.aggregate": "vcs",
1219 }),
1220 [WS_METHODS.vcsCreateWorktree]: (input) =>
1221 observeRpcEffect(
1222 WS_METHODS.vcsCreateWorktree,
1223 gitWorkflow.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
1224 { "rpc.aggregate": "vcs" },
1225 ),
1226 [WS_METHODS.vcsRemoveWorktree]: (input) =>
1227 observeRpcEffect(
1228 WS_METHODS.vcsRemoveWorktree,
1229 gitWorkflow.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
1230 { "rpc.aggregate": "vcs" },
1231 ),
1232 [WS_METHODS.vcsCreateRef]: (input) =>
1233 observeRpcEffect(
1234 WS_METHODS.vcsCreateRef,
1235 gitWorkflow.createRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
1236 { "rpc.aggregate": "vcs" },
1237 ),
1238 [WS_METHODS.vcsSwitchRef]: (input) =>
1239 observeRpcEffect(
1240 WS_METHODS.vcsSwitchRef,
1241 gitWorkflow.switchRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
1242 { "rpc.aggregate": "vcs" },
1243 ),
1244 [WS_METHODS.vcsInit]: (input) =>
1245 observeRpcEffect(
1246 WS_METHODS.vcsInit,
1247 vcsProvisioning
1248 .initRepository(input)
1249 .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
1250 { "rpc.aggregate": "vcs" },
1251 ),
1252 [WS_METHODS.reviewGetDiffPreview]: (input) =>
1253 observeRpcEffect(WS_METHODS.reviewGetDiffPreview, review.getDiffPreview(input), {
1254 "rpc.aggregate": "review",
1255 }),
1256 [WS_METHODS.terminalOpen]: (input) =>
1257 observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
1258 "rpc.aggregate": "terminal",
1259 }),
1260 [WS_METHODS.terminalAttach]: (input) =>
1261 observeRpcStream(
1262 WS_METHODS.terminalAttach,
1263 Stream.callback<TerminalAttachStreamEvent, TerminalError>((queue) =>
1264 Effect.acquireRelease(
1265 terminalManager.attachStream(input, (event) => Queue.offer(queue, event)),
1266 (unsubscribe) => Effect.sync(unsubscribe),
1267 ),
1268 ),
1269 { "rpc.aggregate": "terminal" },
1270 ),
1271 [WS_METHODS.terminalWrite]: (input) =>
1272 observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), {
1273 "rpc.aggregate": "terminal",
1274 }),
1275 [WS_METHODS.terminalResize]: (input) =>
1276 observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), {
1277 "rpc.aggregate": "terminal",
1278 }),
1279 [WS_METHODS.terminalClear]: (input) =>
1280 observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), {
1281 "rpc.aggregate": "terminal",
1282 }),
1283 [WS_METHODS.terminalRestart]: (input) =>
1284 observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), {
1285 "rpc.aggregate": "terminal",
1286 }),
1287 [WS_METHODS.terminalClose]: (input) =>
1288 observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), {
1289 "rpc.aggregate": "terminal",
1290 }),
1291 [WS_METHODS.subscribeTerminalEvents]: (_input) =>
1292 observeRpcStream(
1293 WS_METHODS.subscribeTerminalEvents,
1294 Stream.callback<TerminalEvent>((queue) =>
1295 Effect.acquireRelease(
1296 terminalManager.subscribe((event) => Queue.offer(queue, event)),
1297 (unsubscribe) => Effect.sync(unsubscribe),
1298 ),
1299 ),
1300 { "rpc.aggregate": "terminal" },
1301 ),
1302 [WS_METHODS.subscribeTerminalMetadata]: (_input) =>
1303 observeRpcStream(
1304 WS_METHODS.subscribeTerminalMetadata,
1305 Stream.callback<TerminalMetadataStreamEvent>((queue) =>
1306 Effect.acquireRelease(
1307 terminalManager.subscribeMetadata((event) => Queue.offer(queue, event)),
1308 (unsubscribe) => Effect.sync(unsubscribe),
1309 ),
1310 ),
1311 { "rpc.aggregate": "terminal" },
1312 ),
1313 [WS_METHODS.subscribeServerConfig]: (_input) =>
1314 observeRpcStreamEffect(
1315 WS_METHODS.subscribeServerConfig,
1316 Effect.gen(function* () {
1317 const keybindingsUpdates = keybindings.streamChanges.pipe(
1318 Stream.map((event) => ({
1319 version: 1 as const,
1320 type: "keybindingsUpdated" as const,
1321 payload: {
1322 keybindings: event.keybindings,
1323 issues: event.issues,
1324 },
1325 })),
1326 );
1327 const providerStatuses = providerRegistry.streamChanges.pipe(
1328 Stream.map((providers) => ({
1329 version: 1 as const,
1330 type: "providerStatuses" as const,
1331 payload: { providers },
1332 })),
1333 Stream.debounce(Duration.millis(PROVIDER_STATUS_DEBOUNCE_MS)),
1334 );
1335 const settingsUpdates = serverSettings.streamChanges.pipe(
1336 Stream.map((settings) => redactServerSettingsForClient(settings)),
1337 Stream.map((settings) => ({
1338 version: 1 as const,
1339 type: "settingsUpdated" as const,
1340 payload: { settings },
1341 })),
1342 );
1343
1344 yield* providerRegistry
1345 .refresh()
1346 .pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);
1347
1348 const liveUpdates = Stream.merge(
1349 keybindingsUpdates,
1350 Stream.merge(providerStatuses, settingsUpdates),
1351 );
1352
1353 return Stream.concat(
1354 Stream.make({
1355 version: 1 as const,
1356 type: "snapshot" as const,
1357 config: yield* loadServerConfig,
1358 }),
1359 liveUpdates,
1360 );
1361 }),
1362 { "rpc.aggregate": "server" },
1363 ),
1364 [WS_METHODS.subscribeServerLifecycle]: (_input) =>
1365 observeRpcStreamEffect(
1366 WS_METHODS.subscribeServerLifecycle,
1367 Effect.gen(function* () {
1368 const snapshot = yield* lifecycleEvents.snapshot;
1369 const snapshotEvents = Array.from(snapshot.events).toSorted(
1370 (left, right) => left.sequence - right.sequence,
1371 );
1372 const liveEvents = lifecycleEvents.stream.pipe(
1373 Stream.filter((event) => event.sequence > snapshot.sequence),
1374 );
1375 return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);
1376 }),
1377 { "rpc.aggregate": "server" },
1378 ),
1379 [WS_METHODS.subscribeAuthAccess]: (_input) =>
1380 observeRpcStreamEffect(
1381 WS_METHODS.subscribeAuthAccess,
1382 Effect.gen(function* () {
1383 const initialSnapshot = yield* loadAuthAccessSnapshot();
1384 const revisionRef = yield* Ref.make(1);
1385 const accessChanges: Stream.Stream<
1386 PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange
1387 > = Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges);
1388
1389 const liveEvents: Stream.Stream<AuthAccessStreamEvent> = accessChanges.pipe(
1390 Stream.mapEffect((change) =>
1391 Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe(
1392 Effect.map((revision) =>
1393 toAuthAccessStreamEvent(change, revision, currentSessionId),
1394 ),
1395 ),
1396 ),
1397 );
1398
1399 return Stream.concat(
1400 Stream.make({
1401 version: 1 as const,
1402 revision: 1,
1403 type: "snapshot" as const,
1404 payload: initialSnapshot,
1405 }),
1406 liveEvents,
1407 );
1408 }),
1409 { "rpc.aggregate": "auth" },
1410 ),
1411 });
1412 }),
1413 );
1414
1415export const websocketRpcRouteLayer = Layer.unwrap(
1416 Effect.succeed(
1417 HttpRouter.add(
1418 "GET",
1419 "/ws",
1420 Effect.gen(function* () {
1421 const request = yield* HttpServerRequest.HttpServerRequest;
1422 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
1423 const sessions = yield* SessionStore.SessionStore;
1424 const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(
1425 Effect.catchTags({
1426 ServerAuthInvalidCredentialError: (error) => failEnvironmentAuthInvalid(error.reason),
1427 ServerAuthInternalError: (error) => failEnvironmentInternal("internal_error", error),
1428 }),
1429 );
1430 const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
1431 disableTracing: true,
1432 }).pipe(
1433 Effect.provide(
1434 makeWsRpcLayer(session).pipe(
1435 Layer.provideMerge(RpcSerialization.layerJson),
1436 Layer.provide(ProviderMaintenanceRunner.layer),
1437 Layer.provide(
1438 SourceControlDiscoveryLayer.layer.pipe(
1439 Layer.provide(
1440 SourceControlProviderRegistry.layer.pipe(
1441 Layer.provide(
1442 Layer.mergeAll(
1443 AzureDevOpsCli.layer,
1444 BitbucketApi.layer,
1445 GitHubCli.layer,
1446 GitLabCli.layer,
1447 ),
1448 ),
1449 Layer.provideMerge(GitVcsDriver.layer),
1450 Layer.provide(
1451 VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer)),
1452 ),
1453 ),
1454 ),
1455 Layer.provide(VcsProcess.layer),
1456 ),
1457 ),
1458 ),
1459 ),
1460 );
1461 return yield* Effect.acquireUseRelease(
1462 sessions.markConnected(session.sessionId),
1463 () => rpcWebSocketHttpEffect,
1464 () => sessions.markDisconnected(session.sessionId),
1465 );
1466 }).pipe(
1467 Effect.catchTags({
1468 EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
1469 EnvironmentInternalError: HttpServerRespondable.toResponse,
1470 }),
1471 ),
1472 ),
1473 ),
1474);