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.make(`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.make(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: error.message,
317 },
318 ),
319 ),
320 );
321 };
322
323 const runSetupProgram = () =>
324 bootstrap?.runSetupScript && targetWorktreePath
325 ? (() => {
326 const worktreePath = targetWorktreePath;
327 const requestedAt = new Date().toISOString();
328 return projectSetupScriptRunner
329 .runForThread({
330 threadId: command.threadId,
331 ...(targetProjectId ? { projectId: targetProjectId } : {}),
332 ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),
333 worktreePath,
334 })
335 .pipe(
336 Effect.matchEffect({
337 onFailure: (error) =>
338 recordSetupScriptLaunchFailure({
339 error,
340 requestedAt,
341 worktreePath,
342 }),
343 onSuccess: (setupResult) => {
344 if (setupResult.status !== "started") {
345 return Effect.void;
346 }
347 return recordSetupScriptStarted({
348 requestedAt,
349 worktreePath,
350 scriptId: setupResult.scriptId,
351 scriptName: setupResult.scriptName,
352 terminalId: setupResult.terminalId,
353 });
354 },
355 }),
356 );
357 })()
358 : Effect.void;
359
360 const bootstrapProgram = Effect.gen(function* () {
361 if (bootstrap?.createThread) {
362 yield* orchestrationEngine.dispatch({
363 type: "thread.create",
364 commandId: serverCommandId("bootstrap-thread-create"),
365 threadId: command.threadId,
366 projectId: bootstrap.createThread.projectId,
367 title: bootstrap.createThread.title,
368 modelSelection: bootstrap.createThread.modelSelection,
369 runtimeMode: bootstrap.createThread.runtimeMode,
370 interactionMode: bootstrap.createThread.interactionMode,
371 branch: bootstrap.createThread.branch,
372 worktreePath: bootstrap.createThread.worktreePath,
373 createdAt: bootstrap.createThread.createdAt,
374 });
375 createdThread = true;
376 }
377
378 if (bootstrap?.prepareWorktree) {
379 const worktree = yield* git.createWorktree({
380 cwd: bootstrap.prepareWorktree.projectCwd,
381 branch: bootstrap.prepareWorktree.baseBranch,
382 newBranch: bootstrap.prepareWorktree.branch,
383 path: null,
384 });
385 targetWorktreePath = worktree.worktree.path;
386 yield* orchestrationEngine.dispatch({
387 type: "thread.meta.update",
388 commandId: serverCommandId("bootstrap-thread-meta-update"),
389 threadId: command.threadId,
390 branch: worktree.worktree.branch,
391 worktreePath: targetWorktreePath,
392 });
393 }
394
395 yield* runSetupProgram();
396
397 return yield* orchestrationEngine.dispatch(finalTurnStartCommand);
398 });
399
400 return yield* bootstrapProgram.pipe(
401 Effect.catchCause((cause) => {
402 const dispatchError = toBootstrapDispatchCommandCauseError(cause);
403 if (Cause.hasInterruptsOnly(cause)) {
404 return Effect.fail(dispatchError);
405 }
406 return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError)));
407 }),
408 );
409 });
410
411 const dispatchNormalizedCommand = (
412 normalizedCommand: OrchestrationCommand,
413 ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => {
414 const dispatchEffect =
415 normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap
416 ? dispatchBootstrapTurnStart(normalizedCommand)
417 : orchestrationEngine
418 .dispatch(normalizedCommand)
419 .pipe(
420 Effect.mapError((cause) =>
421 toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
422 ),
423 );
424
425 return startup
426 .enqueueCommand(dispatchEffect)
427 .pipe(
428 Effect.mapError((cause) =>
429 toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
430 ),
431 );
432 };
433
434 const loadServerConfig = Effect.gen(function* () {
435 const keybindingsConfig = yield* keybindings.loadConfigState;
436 const providers = yield* providerRegistry.getProviders;
437 const settings = yield* serverSettings.getSettings;
438 const environment = yield* serverEnvironment.getDescriptor;
439 const auth = yield* serverAuth.getDescriptor();
440
441 return {
442 environment,
443 auth,
444 cwd: config.cwd,
445 keybindingsConfigPath: config.keybindingsConfigPath,
446 keybindings: keybindingsConfig.keybindings,
447 issues: keybindingsConfig.issues,
448 providers,
449 availableEditors: resolveAvailableEditors(),
450 observability: {
451 logsDirectoryPath: config.logsDir,
452 localTracingEnabled: true,
453 ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),
454 otlpTracesEnabled: config.otlpTracesUrl !== undefined,
455 ...(config.otlpMetricsUrl !== undefined
456 ? { otlpMetricsUrl: config.otlpMetricsUrl }
457 : {}),
458 otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,
459 },
460 settings,
461 };
462 });
463
464 const refreshGitStatus = (cwd: string) =>
465 gitStatusBroadcaster
466 .refreshStatus(cwd)
467 .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
468
469 return WsRpcGroup.of({
470 [ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
471 observeRpcEffect(
472 ORCHESTRATION_WS_METHODS.getSnapshot,
473 projectionSnapshotQuery.getSnapshot().pipe(
474 Effect.mapError(
475 (cause) =>
476 new OrchestrationGetSnapshotError({
477 message: "Failed to load orchestration snapshot",
478 cause,
479 }),
480 ),
481 ),
482 { "rpc.aggregate": "orchestration" },
483 ),
484 [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
485 observeRpcEffect(
486 ORCHESTRATION_WS_METHODS.dispatchCommand,
487 Effect.gen(function* () {
488 const normalizedCommand = yield* normalizeDispatchCommand(command);
489 const result = yield* dispatchNormalizedCommand(normalizedCommand);
490 if (normalizedCommand.type === "thread.archive") {
491 yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
492 Effect.catch((error) =>
493 Effect.logWarning("failed to close thread terminals after archive", {
494 threadId: normalizedCommand.threadId,
495 error: error.message,
496 }),
497 ),
498 );
499 }
500 return result;
501 }).pipe(
502 Effect.mapError((cause) =>
503 Schema.is(OrchestrationDispatchCommandError)(cause)
504 ? cause
505 : new OrchestrationDispatchCommandError({
506 message: "Failed to dispatch orchestration command",
507 cause,
508 }),
509 ),
510 ),
511 { "rpc.aggregate": "orchestration" },
512 ),
513 [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>
514 observeRpcEffect(
515 ORCHESTRATION_WS_METHODS.getTurnDiff,
516 checkpointDiffQuery.getTurnDiff(input).pipe(
517 Effect.mapError(
518 (cause) =>
519 new OrchestrationGetTurnDiffError({
520 message: "Failed to load turn diff",
521 cause,
522 }),
523 ),
524 ),
525 { "rpc.aggregate": "orchestration" },
526 ),
527 [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
528 observeRpcEffect(
529 ORCHESTRATION_WS_METHODS.getFullThreadDiff,
530 checkpointDiffQuery.getFullThreadDiff(input).pipe(
531 Effect.mapError(
532 (cause) =>
533 new OrchestrationGetFullThreadDiffError({
534 message: "Failed to load full thread diff",
535 cause,
536 }),
537 ),
538 ),
539 { "rpc.aggregate": "orchestration" },
540 ),
541 [ORCHESTRATION_WS_METHODS.replayEvents]: (input) =>
542 observeRpcEffect(
543 ORCHESTRATION_WS_METHODS.replayEvents,
544 Stream.runCollect(
545 orchestrationEngine.readEvents(
546 clamp(input.fromSequenceExclusive, {
547 maximum: Number.MAX_SAFE_INTEGER,
548 minimum: 0,
549 }),
550 ),
551 ).pipe(
552 Effect.map((events) => Array.from(events)),
553 Effect.flatMap(enrichOrchestrationEvents),
554 Effect.mapError(
555 (cause) =>
556 new OrchestrationReplayEventsError({
557 message: "Failed to replay orchestration events",
558 cause,
559 }),
560 ),
561 ),
562 { "rpc.aggregate": "orchestration" },
563 ),
564 [WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) =>
565 observeRpcStreamEffect(
566 WS_METHODS.subscribeOrchestrationDomainEvents,
567 Effect.gen(function* () {
568 const snapshot = yield* orchestrationEngine.getReadModel();
569 const fromSequenceExclusive = snapshot.snapshotSequence;
570 const replayEvents: Array<OrchestrationEvent> = yield* Stream.runCollect(
571 orchestrationEngine.readEvents(fromSequenceExclusive),
572 ).pipe(
573 Effect.map((events) => Array.from(events)),
574 Effect.flatMap(enrichOrchestrationEvents),
575 Effect.catch(() => Effect.succeed([] as Array<OrchestrationEvent>)),
576 );
577 const replayStream = Stream.fromIterable(replayEvents);
578 const liveStream = orchestrationEngine.streamDomainEvents.pipe(
579 Stream.mapEffect(enrichProjectEvent),
580 );
581 const source = Stream.merge(replayStream, liveStream);
582 type SequenceState = {
583 readonly nextSequence: number;
584 readonly pendingBySequence: Map<number, OrchestrationEvent>;
585 };
586 const state = yield* Ref.make<SequenceState>({
587 nextSequence: fromSequenceExclusive + 1,
588 pendingBySequence: new Map<number, OrchestrationEvent>(),
589 });
590
591 return source.pipe(
592 Stream.mapEffect((event) =>
593 Ref.modify(
594 state,
595 ({
596 nextSequence,
597 pendingBySequence,
598 }): [Array<OrchestrationEvent>, SequenceState] => {
599 if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) {
600 return [[], { nextSequence, pendingBySequence }];
601 }
602
603 const updatedPending = new Map(pendingBySequence);
604 updatedPending.set(event.sequence, event);
605
606 const emit: Array<OrchestrationEvent> = [];
607 let expected = nextSequence;
608 for (;;) {
609 const expectedEvent = updatedPending.get(expected);
610 if (!expectedEvent) {
611 break;
612 }
613 emit.push(expectedEvent);
614 updatedPending.delete(expected);
615 expected += 1;
616 }
617
618 return [emit, { nextSequence: expected, pendingBySequence: updatedPending }];
619 },
620 ),
621 ),
622 Stream.flatMap((events) => Stream.fromIterable(events)),
623 );
624 }),
625 { "rpc.aggregate": "orchestration" },
626 ),
627 [WS_METHODS.serverGetConfig]: (_input) =>
628 observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {
629 "rpc.aggregate": "server",
630 }),
631 [WS_METHODS.serverRefreshProviders]: (_input) =>
632 observeRpcEffect(
633 WS_METHODS.serverRefreshProviders,
634 providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))),
635 { "rpc.aggregate": "server" },
636 ),
637 [WS_METHODS.serverUpsertKeybinding]: (rule) =>
638 observeRpcEffect(
639 WS_METHODS.serverUpsertKeybinding,
640 Effect.gen(function* () {
641 const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
642 return { keybindings: keybindingsConfig, issues: [] };
643 }),
644 { "rpc.aggregate": "server" },
645 ),
646 [WS_METHODS.serverGetSettings]: (_input) =>
647 observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, {
648 "rpc.aggregate": "server",
649 }),
650 [WS_METHODS.serverUpdateSettings]: ({ patch }) =>
651 observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), {
652 "rpc.aggregate": "server",
653 }),
654 [WS_METHODS.projectsSearchEntries]: (input) =>
655 observeRpcEffect(
656 WS_METHODS.projectsSearchEntries,
657 workspaceEntries.search(input).pipe(
658 Effect.mapError(
659 (cause) =>
660 new ProjectSearchEntriesError({
661 message: `Failed to search workspace entries: ${cause.detail}`,
662 cause,
663 }),
664 ),
665 ),
666 { "rpc.aggregate": "workspace" },
667 ),
668 [WS_METHODS.projectsWriteFile]: (input) =>
669 observeRpcEffect(
670 WS_METHODS.projectsWriteFile,
671 workspaceFileSystem.writeFile(input).pipe(
672 Effect.mapError((cause) => {
673 const message = Schema.is(WorkspacePathOutsideRootError)(cause)
674 ? "Workspace file path must stay within the project root."
675 : "Failed to write workspace file";
676 return new ProjectWriteFileError({
677 message,
678 cause,
679 });
680 }),
681 ),
682 { "rpc.aggregate": "workspace" },
683 ),
684 [WS_METHODS.shellOpenInEditor]: (input) =>
685 observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
686 "rpc.aggregate": "workspace",
687 }),
688 [WS_METHODS.subscribeGitStatus]: (input) =>
689 observeRpcStream(
690 WS_METHODS.subscribeGitStatus,
691 gitStatusBroadcaster.streamStatus(input),
692 {
693 "rpc.aggregate": "git",
694 },
695 ),
696 [WS_METHODS.gitRefreshStatus]: (input) =>
697 observeRpcEffect(
698 WS_METHODS.gitRefreshStatus,
699 gitStatusBroadcaster.refreshStatus(input.cwd),
700 {
701 "rpc.aggregate": "git",
702 },
703 ),
704 [WS_METHODS.gitPull]: (input) =>
705 observeRpcEffect(
706 WS_METHODS.gitPull,
707 git.pullCurrentBranch(input.cwd).pipe(
708 Effect.matchCauseEffect({
709 onFailure: (cause) => Effect.failCause(cause),
710 onSuccess: (result) =>
711 refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)),
712 }),
713 ),
714 { "rpc.aggregate": "git" },
715 ),
716 [WS_METHODS.gitRunStackedAction]: (input) =>
717 observeRpcStream(
718 WS_METHODS.gitRunStackedAction,
719 Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
720 gitManager
721 .runStackedAction(input, {
722 actionId: input.actionId,
723 progressReporter: {
724 publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),
725 },
726 })
727 .pipe(
728 Effect.matchCauseEffect({
729 onFailure: (cause) => Queue.failCause(queue, cause),
730 onSuccess: () =>
731 refreshGitStatus(input.cwd).pipe(
732 Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)),
733 ),
734 }),
735 ),
736 ),
737 { "rpc.aggregate": "git" },
738 ),
739 [WS_METHODS.gitResolvePullRequest]: (input) =>
740 observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), {
741 "rpc.aggregate": "git",
742 }),
743 [WS_METHODS.gitPreparePullRequestThread]: (input) =>
744 observeRpcEffect(
745 WS_METHODS.gitPreparePullRequestThread,
746 gitManager
747 .preparePullRequestThread(input)
748 .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
749 { "rpc.aggregate": "git" },
750 ),
751 [WS_METHODS.gitListBranches]: (input) =>
752 observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), {
753 "rpc.aggregate": "git",
754 }),
755 [WS_METHODS.gitCreateWorktree]: (input) =>
756 observeRpcEffect(
757 WS_METHODS.gitCreateWorktree,
758 git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
759 { "rpc.aggregate": "git" },
760 ),
761 [WS_METHODS.gitRemoveWorktree]: (input) =>
762 observeRpcEffect(
763 WS_METHODS.gitRemoveWorktree,
764 git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
765 { "rpc.aggregate": "git" },
766 ),
767 [WS_METHODS.gitCreateBranch]: (input) =>
768 observeRpcEffect(
769 WS_METHODS.gitCreateBranch,
770 git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
771 { "rpc.aggregate": "git" },
772 ),
773 [WS_METHODS.gitCheckout]: (input) =>
774 observeRpcEffect(
775 WS_METHODS.gitCheckout,
776 Effect.scoped(git.checkoutBranch(input)).pipe(
777 Effect.tap(() => refreshGitStatus(input.cwd)),
778 ),
779 { "rpc.aggregate": "git" },
780 ),
781 [WS_METHODS.gitInit]: (input) =>
782 observeRpcEffect(
783 WS_METHODS.gitInit,
784 git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
785 { "rpc.aggregate": "git" },
786 ),
787 [WS_METHODS.terminalOpen]: (input) =>
788 observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
789 "rpc.aggregate": "terminal",
790 }),
791 [WS_METHODS.terminalWrite]: (input) =>
792 observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), {
793 "rpc.aggregate": "terminal",
794 }),
795 [WS_METHODS.terminalResize]: (input) =>
796 observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), {
797 "rpc.aggregate": "terminal",
798 }),
799 [WS_METHODS.terminalClear]: (input) =>
800 observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), {
801 "rpc.aggregate": "terminal",
802 }),
803 [WS_METHODS.terminalRestart]: (input) =>
804 observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), {
805 "rpc.aggregate": "terminal",
806 }),
807 [WS_METHODS.terminalClose]: (input) =>
808 observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), {
809 "rpc.aggregate": "terminal",
810 }),
811 [WS_METHODS.subscribeTerminalEvents]: (_input) =>
812 observeRpcStream(
813 WS_METHODS.subscribeTerminalEvents,
814 Stream.callback<TerminalEvent>((queue) =>
815 Effect.acquireRelease(
816 terminalManager.subscribe((event) => Queue.offer(queue, event)),
817 (unsubscribe) => Effect.sync(unsubscribe),
818 ),
819 ),
820 { "rpc.aggregate": "terminal" },
821 ),
822 [WS_METHODS.subscribeServerConfig]: (_input) =>
823 observeRpcStreamEffect(
824 WS_METHODS.subscribeServerConfig,
825 Effect.gen(function* () {
826 const keybindingsUpdates = keybindings.streamChanges.pipe(
827 Stream.map((event) => ({
828 version: 1 as const,
829 type: "keybindingsUpdated" as const,
830 payload: {
831 issues: event.issues,
832 },
833 })),
834 );
835 const providerStatuses = providerRegistry.streamChanges.pipe(
836 Stream.map((providers) => ({
837 version: 1 as const,
838 type: "providerStatuses" as const,
839 payload: { providers },
840 })),
841 );
842 const settingsUpdates = serverSettings.streamChanges.pipe(
843 Stream.map((settings) => ({
844 version: 1 as const,
845 type: "settingsUpdated" as const,
846 payload: { settings },
847 })),
848 );
849
850 return Stream.concat(
851 Stream.make({
852 version: 1 as const,
853 type: "snapshot" as const,
854 config: yield* loadServerConfig,
855 }),
856 Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)),
857 );
858 }),
859 { "rpc.aggregate": "server" },
860 ),
861 [WS_METHODS.subscribeServerLifecycle]: (_input) =>
862 observeRpcStreamEffect(
863 WS_METHODS.subscribeServerLifecycle,
864 Effect.gen(function* () {
865 const snapshot = yield* lifecycleEvents.snapshot;
866 const snapshotEvents = Array.from(snapshot.events).toSorted(
867 (left, right) => left.sequence - right.sequence,
868 );
869 const liveEvents = lifecycleEvents.stream.pipe(
870 Stream.filter((event) => event.sequence > snapshot.sequence),
871 );
872 return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);
873 }),
874 { "rpc.aggregate": "server" },
875 ),
876 [WS_METHODS.subscribeAuthAccess]: (_input) =>
877 observeRpcStreamEffect(
878 WS_METHODS.subscribeAuthAccess,
879 Effect.gen(function* () {
880 const initialSnapshot = yield* loadAuthAccessSnapshot();
881 const revisionRef = yield* Ref.make(1);
882 const accessChanges: Stream.Stream<
883 BootstrapCredentialChange | SessionCredentialChange
884 > = Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges);
885
886 const liveEvents: Stream.Stream<AuthAccessStreamEvent> = accessChanges.pipe(
887 Stream.mapEffect((change) =>
888 Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe(
889 Effect.map((revision) =>
890 toAuthAccessStreamEvent(change, revision, currentSessionId),
891 ),
892 ),
893 ),
894 );
895
896 return Stream.concat(
897 Stream.make({
898 version: 1 as const,
899 revision: 1,
900 type: "snapshot" as const,
901 payload: initialSnapshot,
902 }),
903 liveEvents,
904 );
905 }),
906 { "rpc.aggregate": "auth" },
907 ),
908 });
909 }),
910 );
911
912export const websocketRpcRouteLayer = Layer.unwrap(
913 Effect.succeed(
914 HttpRouter.add(
915 "GET",
916 "/ws",
917 Effect.gen(function* () {
918 const request = yield* HttpServerRequest.HttpServerRequest;
919 const serverAuth = yield* ServerAuth;
920 const sessions = yield* SessionCredentialService;
921 const session = yield* serverAuth.authenticateWebSocketUpgrade(request);
922 const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
923 spanPrefix: "ws.rpc",
924 spanAttributes: {
925 "rpc.transport": "websocket",
926 "rpc.system": "effect-rpc",
927 },
928 }).pipe(
929 Effect.provide(
930 makeWsRpcLayer(session.sessionId).pipe(Layer.provideMerge(RpcSerialization.layerJson)),
931 ),
932 );
933 return yield* Effect.acquireUseRelease(
934 sessions.markConnected(session.sessionId),
935 () => rpcWebSocketHttpEffect,
936 () => sessions.markDisconnected(session.sessionId),
937 );
938 }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
939 ),
940 ),
941);