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