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

ws.ts

1,225 lines47.9 KB

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