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

ws.ts

1,090 lines42.0 KB

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";
31import { ServerConfig } from "./config";
32import { GitCore } from "./git/Services/GitCore";
33import { GitManager } from "./git/Services/GitManager";
34import { GitStatusBroadcaster } from "./git/Services/GitStatusBroadcaster";
35import { Keybindings } from "./keybindings";
36import { Open, resolveAvailableEditors } from "./open";
37import { normalizeDispatchCommand } from "./orchestration/Normalizer";
38import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
39import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
40import {
41 observeRpcEffect,
42 observeRpcStream,
43 observeRpcStreamEffect,
44} from "./observability/RpcInstrumentation";
45import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
46import { ServerLifecycleEvents } from "./serverLifecycleEvents";
47import { ServerRuntimeStartup } from "./serverRuntimeStartup";
48import { ServerSettingsService } from "./serverSettings";
49import { TerminalManager } from "./terminal/Services/Manager";
50import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries";
51import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem";
52import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths";
53import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner";
54import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver";
55import { ServerEnvironment } from "./environment/Services/ServerEnvironment";
56import { ServerAuth } from "./auth/Services/ServerAuth";
57import {
58 BootstrapCredentialService,
59 type BootstrapCredentialChange,
60} from "./auth/Services/BootstrapCredentialService";
61import {
62 SessionCredentialService,
63 type SessionCredentialChange,
64} from "./auth/Services/SessionCredentialService";
65import { respondToAuthError } from "./auth/http";
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 );
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 }
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 = 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 providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))),
756 { "rpc.aggregate": "server" },
757 ),
758 [WS_METHODS.serverUpsertKeybinding]: (rule) =>
759 observeRpcEffect(
760 WS_METHODS.serverUpsertKeybinding,
761 Effect.gen(function* () {
762 const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
763 return { keybindings: keybindingsConfig, issues: [] };
764 }),
765 { "rpc.aggregate": "server" },
766 ),
767 [WS_METHODS.serverGetSettings]: (_input) =>
768 observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, {
769 "rpc.aggregate": "server",
770 }),
771 [WS_METHODS.serverUpdateSettings]: ({ patch }) =>
772 observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), {
773 "rpc.aggregate": "server",
774 }),
775 [WS_METHODS.projectsSearchEntries]: (input) =>
776 observeRpcEffect(
777 WS_METHODS.projectsSearchEntries,
778 workspaceEntries.search(input).pipe(
779 Effect.mapError(
780 (cause) =>
781 new ProjectSearchEntriesError({
782 message: `Failed to search workspace entries: ${cause.detail}`,
783 cause,
784 }),
785 ),
786 ),
787 { "rpc.aggregate": "workspace" },
788 ),
789 [WS_METHODS.projectsWriteFile]: (input) =>
790 observeRpcEffect(
791 WS_METHODS.projectsWriteFile,
792 workspaceFileSystem.writeFile(input).pipe(
793 Effect.mapError((cause) => {
794 const message = Schema.is(WorkspacePathOutsideRootError)(cause)
795 ? "Workspace file path must stay within the project root."
796 : "Failed to write workspace file";
797 return new ProjectWriteFileError({
798 message,
799 cause,
800 });
801 }),
802 ),
803 { "rpc.aggregate": "workspace" },
804 ),
805 [WS_METHODS.shellOpenInEditor]: (input) =>
806 observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
807 "rpc.aggregate": "workspace",
808 }),
809 [WS_METHODS.filesystemBrowse]: (input) =>
810 observeRpcEffect(
811 WS_METHODS.filesystemBrowse,
812 workspaceEntries.browse(input).pipe(
813 Effect.mapError(
814 (cause) =>
815 new FilesystemBrowseError({
816 message: cause.detail,
817 cause,
818 }),
819 ),
820 ),
821 { "rpc.aggregate": "workspace" },
822 ),
823 [WS_METHODS.subscribeGitStatus]: (input) =>
824 observeRpcStream(
825 WS_METHODS.subscribeGitStatus,
826 gitStatusBroadcaster.streamStatus(input),
827 {
828 "rpc.aggregate": "git",
829 },
830 ),
831 [WS_METHODS.gitRefreshStatus]: (input) =>
832 observeRpcEffect(
833 WS_METHODS.gitRefreshStatus,
834 gitStatusBroadcaster.refreshStatus(input.cwd),
835 {
836 "rpc.aggregate": "git",
837 },
838 ),
839 [WS_METHODS.gitPull]: (input) =>
840 observeRpcEffect(
841 WS_METHODS.gitPull,
842 git.pullCurrentBranch(input.cwd).pipe(
843 Effect.matchCauseEffect({
844 onFailure: (cause) => Effect.failCause(cause),
845 onSuccess: (result) =>
846 refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)),
847 }),
848 ),
849 { "rpc.aggregate": "git" },
850 ),
851 [WS_METHODS.gitRunStackedAction]: (input) =>
852 observeRpcStream(
853 WS_METHODS.gitRunStackedAction,
854 Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
855 gitManager
856 .runStackedAction(input, {
857 actionId: input.actionId,
858 progressReporter: {
859 publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),
860 },
861 })
862 .pipe(
863 Effect.matchCauseEffect({
864 onFailure: (cause) => Queue.failCause(queue, cause),
865 onSuccess: () =>
866 refreshGitStatus(input.cwd).pipe(
867 Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)),
868 ),
869 }),
870 ),
871 ),
872 { "rpc.aggregate": "git" },
873 ),
874 [WS_METHODS.gitResolvePullRequest]: (input) =>
875 observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), {
876 "rpc.aggregate": "git",
877 }),
878 [WS_METHODS.gitPreparePullRequestThread]: (input) =>
879 observeRpcEffect(
880 WS_METHODS.gitPreparePullRequestThread,
881 gitManager
882 .preparePullRequestThread(input)
883 .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
884 { "rpc.aggregate": "git" },
885 ),
886 [WS_METHODS.gitListBranches]: (input) =>
887 observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), {
888 "rpc.aggregate": "git",
889 }),
890 [WS_METHODS.gitCreateWorktree]: (input) =>
891 observeRpcEffect(
892 WS_METHODS.gitCreateWorktree,
893 git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
894 { "rpc.aggregate": "git" },
895 ),
896 [WS_METHODS.gitRemoveWorktree]: (input) =>
897 observeRpcEffect(
898 WS_METHODS.gitRemoveWorktree,
899 git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
900 { "rpc.aggregate": "git" },
901 ),
902 [WS_METHODS.gitCreateBranch]: (input) =>
903 observeRpcEffect(
904 WS_METHODS.gitCreateBranch,
905 git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
906 { "rpc.aggregate": "git" },
907 ),
908 [WS_METHODS.gitCheckout]: (input) =>
909 observeRpcEffect(
910 WS_METHODS.gitCheckout,
911 Effect.scoped(git.checkoutBranch(input)).pipe(
912 Effect.tap(() => refreshGitStatus(input.cwd)),
913 ),
914 { "rpc.aggregate": "git" },
915 ),
916 [WS_METHODS.gitInit]: (input) =>
917 observeRpcEffect(
918 WS_METHODS.gitInit,
919 git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
920 { "rpc.aggregate": "git" },
921 ),
922 [WS_METHODS.terminalOpen]: (input) =>
923 observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
924 "rpc.aggregate": "terminal",
925 }),
926 [WS_METHODS.terminalWrite]: (input) =>
927 observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), {
928 "rpc.aggregate": "terminal",
929 }),
930 [WS_METHODS.terminalResize]: (input) =>
931 observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), {
932 "rpc.aggregate": "terminal",
933 }),
934 [WS_METHODS.terminalClear]: (input) =>
935 observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), {
936 "rpc.aggregate": "terminal",
937 }),
938 [WS_METHODS.terminalRestart]: (input) =>
939 observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), {
940 "rpc.aggregate": "terminal",
941 }),
942 [WS_METHODS.terminalClose]: (input) =>
943 observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), {
944 "rpc.aggregate": "terminal",
945 }),
946 [WS_METHODS.subscribeTerminalEvents]: (_input) =>
947 observeRpcStream(
948 WS_METHODS.subscribeTerminalEvents,
949 Stream.callback<TerminalEvent>((queue) =>
950 Effect.acquireRelease(
951 terminalManager.subscribe((event) => Queue.offer(queue, event)),
952 (unsubscribe) => Effect.sync(unsubscribe),
953 ),
954 ),
955 { "rpc.aggregate": "terminal" },
956 ),
957 [WS_METHODS.subscribeServerConfig]: (_input) =>
958 observeRpcStreamEffect(
959 WS_METHODS.subscribeServerConfig,
960 Effect.gen(function* () {
961 const keybindingsUpdates = keybindings.streamChanges.pipe(
962 Stream.map((event) => ({
963 version: 1 as const,
964 type: "keybindingsUpdated" as const,
965 payload: {
966 issues: event.issues,
967 },
968 })),
969 );
970 const providerStatuses = providerRegistry.streamChanges.pipe(
971 Stream.map((providers) => ({
972 version: 1 as const,
973 type: "providerStatuses" as const,
974 payload: { providers },
975 })),
976 Stream.debounce(Duration.millis(PROVIDER_STATUS_DEBOUNCE_MS)),
977 );
978 const settingsUpdates = serverSettings.streamChanges.pipe(
979 Stream.map((settings) => ({
980 version: 1 as const,
981 type: "settingsUpdated" as const,
982 payload: { settings },
983 })),
984 );
985​
986 yield* Effect.all(
987 [providerRegistry.refresh("codex"), providerRegistry.refresh("claudeAgent")],
988 {
989 concurrency: "unbounded",
990 discard: true,
991 },
992 ).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);
993​
994 const liveUpdates = Stream.merge(
995 keybindingsUpdates,
996 Stream.merge(providerStatuses, settingsUpdates),
997 );
998​
999 return Stream.concat(
1000 Stream.make({
1001 version: 1 as const,
1002 type: "snapshot" as const,
1003 config: yield* loadServerConfig,
1004 }),
1005 liveUpdates,
1006 );
1007 }),
1008 { "rpc.aggregate": "server" },
1009 ),
1010 [WS_METHODS.subscribeServerLifecycle]: (_input) =>
1011 observeRpcStreamEffect(
1012 WS_METHODS.subscribeServerLifecycle,
1013 Effect.gen(function* () {
1014 const snapshot = yield* lifecycleEvents.snapshot;
1015 const snapshotEvents = Array.from(snapshot.events).toSorted(
1016 (left, right) => left.sequence - right.sequence,
1017 );
1018 const liveEvents = lifecycleEvents.stream.pipe(
1019 Stream.filter((event) => event.sequence > snapshot.sequence),
1020 );
1021 return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);
1022 }),
1023 { "rpc.aggregate": "server" },
1024 ),
1025 [WS_METHODS.subscribeAuthAccess]: (_input) =>
1026 observeRpcStreamEffect(
1027 WS_METHODS.subscribeAuthAccess,
1028 Effect.gen(function* () {
1029 const initialSnapshot = yield* loadAuthAccessSnapshot();
1030 const revisionRef = yield* Ref.make(1);
1031 const accessChanges: Stream.Stream<
1032 BootstrapCredentialChange | SessionCredentialChange
1033 > = Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges);
1034​
1035 const liveEvents: Stream.Stream<AuthAccessStreamEvent> = accessChanges.pipe(
1036 Stream.mapEffect((change) =>
1037 Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe(
1038 Effect.map((revision) =>
1039 toAuthAccessStreamEvent(change, revision, currentSessionId),
1040 ),
1041 ),
1042 ),
1043 );
1044​
1045 return Stream.concat(
1046 Stream.make({
1047 version: 1 as const,
1048 revision: 1,
1049 type: "snapshot" as const,
1050 payload: initialSnapshot,
1051 }),
1052 liveEvents,
1053 );
1054 }),
1055 { "rpc.aggregate": "auth" },
1056 ),
1057 });
1058 }),
1059 );
1060​
1061export const websocketRpcRouteLayer = Layer.unwrap(
1062 Effect.succeed(
1063 HttpRouter.add(
1064 "GET",
1065 "/ws",
1066 Effect.gen(function* () {
1067 const request = yield* HttpServerRequest.HttpServerRequest;
1068 const serverAuth = yield* ServerAuth;
1069 const sessions = yield* SessionCredentialService;
1070 const session = yield* serverAuth.authenticateWebSocketUpgrade(request);
1071 const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
1072 spanPrefix: "ws.rpc",
1073 spanAttributes: {
1074 "rpc.transport": "websocket",
1075 "rpc.system": "effect-rpc",
1076 },
1077 }).pipe(
1078 Effect.provide(
1079 makeWsRpcLayer(session.sessionId).pipe(Layer.provideMerge(RpcSerialization.layerJson)),
1080 ),
1081 );
1082 return yield* Effect.acquireUseRelease(
1083 sessions.markConnected(session.sessionId),
1084 () => rpcWebSocketHttpEffect,
1085 () => sessions.markDisconnected(session.sessionId),
1086 );
1087 }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
1088 ),
1089 ),