Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ws.ts

1,291 lines50.7 KB

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