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