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