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