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