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