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

serverRuntimeStartup.ts

1,133 lines41.5 KB

1import {
2 CommandId,
3 EventId,
4 DEFAULT_MODEL,
5 DEFAULT_PROVIDER_INTERACTION_MODE,
6 DEFAULT_SERVER_SETTINGS,
7 type ServerSettings as ServerSettingsValue,
8 type ModelSelection,
9 type OrchestrationProjectShell,
10 ProjectId,
11 ProviderInstanceId,
12 ThreadId,
13 TurnId,
14 WORKTREE_SETUP_ACTIVITY_KIND,
15 WorktreeSetupSnapshot,
16 worktreeSetupActivityId,
17} from "@t3tools/contracts";
18import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
19import * as Cause from "effect/Cause";
20import * as Console from "effect/Console";
21import * as Context from "effect/Context";
22import * as Crypto from "effect/Crypto";
23import * as DateTime from "effect/DateTime";
24import * as Deferred from "effect/Deferred";
25import * as Effect from "effect/Effect";
26import * as Exit from "effect/Exit";
27import * as Layer from "effect/Layer";
28import * as Option from "effect/Option";
29import * as Path from "effect/Path";
30import * as Queue from "effect/Queue";
31import * as Ref from "effect/Ref";
32import * as Schema from "effect/Schema";
33import * as Scope from "effect/Scope";
34​
35import * as ServerConfig from "./config.ts";
36import * as Keybindings from "./keybindings.ts";
37import * as ExternalLauncher from "./process/externalLauncher.ts";
38import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
39import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
40import * as OrchestrationReactor from "./orchestration/Services/OrchestrationReactor.ts";
41import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
42import * as ServerSettings from "./serverSettings.ts";
43import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
44import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
45import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
46import * as ProviderService from "./provider/Services/ProviderService.ts";
47import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
48import * as ProviderSessionReaper from "./provider/Services/ProviderSessionReaper.ts";
49import { forkParked } from "./serverActivation.ts";
50import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
51import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
52import {
53 formatHeadlessServeOutput,
54 formatHostForUrl,
55 isWildcardHost,
56 issueHeadlessServeAccessInfo,
57} from "./startupAccess.ts";
58​
59export class ServerRuntimeStartupError extends Schema.TaggedError<ServerRuntimeStartupError>()(
60 "ServerRuntimeStartupError",
61 {
62 mode: ServerConfig.RuntimeMode,
63 host: Schema.NullOr(Schema.String),
64 port: Schema.Number,
65 cause: Schema.Defect(),
66 },
67) {
68 override get message(): string {
69 return "Server runtime startup failed before command readiness.";
70 }
72​
73export class ServerRuntimeStartup extends Context.Service<
74 ServerRuntimeStartup,
75 {
76 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
77 readonly markHttpListening: Effect.Effect<void>;
78 readonly markRunningProviderSessionsForContinuation: Effect.Effect<
79 ReadonlyArray<ThreadId>,
80 ServerUpdateThreadContinuationError
81 >;
82 readonly clearProviderSessionContinuationMarkers: (
83 threadIds: ReadonlyArray<ThreadId>,
84 ) => Effect.Effect<void, ServerUpdateThreadContinuationError>;
85 readonly enqueueCommand: <A, E>(
86 effect: Effect.Effect<A, E>,
87 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
88 }
89>()("t3/serverRuntimeStartup") {}
90​
91interface QueuedCommand {
92 readonly run: Effect.Effect<void, never>;
94​
95type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError;
96​
97interface CommandGate {
98 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
99 readonly signalCommandReady: Effect.Effect<void>;
100 readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
101 readonly enqueueCommand: <A, E>(
102 effect: Effect.Effect<A, E>,
103 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
105​
106const settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>
107 Exit.isSuccess(exit)
108 ? Deferred.succeed(deferred, exit.value)
109 : Deferred.failCause(deferred, exit.cause);
110​
111export const makeCommandGate = Effect.gen(function* () {
112 const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
113 const commandQueue = yield* Queue.unbounded<QueuedCommand>();
114 const commandReadinessState = yield* Ref.make<CommandReadinessState>("pending");
115​
116 const commandWorker = Effect.forever(
117 Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),
118 );
119 yield* Effect.forkScoped(commandWorker);
120​
121 return {
122 awaitCommandReady: Deferred.await(commandReady),
123 signalCommandReady: Effect.gen(function* () {
124 yield* Ref.set(commandReadinessState, "ready");
125 yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
126 }),
127 failCommandReady: (error) =>
128 Effect.gen(function* () {
129 yield* Ref.set(commandReadinessState, error);
130 yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
131 }),
132 enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>
133 Effect.gen(function* () {
134 const readinessState = yield* Ref.get(commandReadinessState);
135 if (readinessState === "ready") {
136 return yield* effect;
137 }
138 if (readinessState !== "pending") {
139 return yield* readinessState;
140 }
141​
142 const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
143 yield* Queue.offer(commandQueue, {
144 run: Deferred.await(commandReady).pipe(
145 Effect.flatMap(() => effect),
146 Effect.exit,
147 Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
148 ),
149 });
150 return yield* Deferred.await(result);
151 }),
152 } satisfies CommandGate;
153});
154​
155const recordStartupHeartbeat = Effect.gen(function* () {
156 const analytics = yield* AnalyticsService.AnalyticsService;
157 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
158​
159 const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe(
160 Effect.catch((cause) =>
161 Effect.logWarning("failed to gather startup projection counts for telemetry", {
162 cause,
163 }).pipe(
164 Effect.as({
165 threadCount: 0,
166 projectCount: 0,
167 }),
168 ),
169 ),
170 );
171​
172 yield* analytics.record("server.boot.heartbeat", {
173 threadCount,
174 projectCount,
175 });
176});
177​
178const getAutoBootstrapThreadModelSelection = (): ModelSelection => ({
179 instanceId: ProviderInstanceId.make("codex"),
180 model: DEFAULT_MODEL,
181});
182​
183export const resolveWelcomeBase = Effect.gen(function* () {
184 const serverConfig = yield* ServerConfig.ServerConfig;
185 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
186 const projectName = segments[segments.length - 1] ?? "project";
187​
188 return {
189 cwd: serverConfig.cwd,
190 projectName,
191 } as const;
192});
193​
194export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
195 const crypto = yield* Crypto.Crypto;
196 const randomUUID = crypto.randomUUIDv4;
197 const serverConfig = yield* ServerConfig.ServerConfig;
198 const projectionReadModelQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
199 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
200 const path = yield* Path.Path;
201​
202 let bootstrapProjectId: ProjectId | undefined;
203 let bootstrapThreadId: ThreadId | undefined;
204 let bootstrapProjectCreated = false;
205 let bootstrapThreadCreated = false;
206​
207 if (serverConfig.autoBootstrapProjectFromCwd) {
208 const settings = yield* (yield* ServerSettings.ServerSettingsService).getSettings;
209 const defaultModelSelection =
210 settings.defaultModelSelection ?? getAutoBootstrapThreadModelSelection();
211 yield* Effect.gen(function* () {
212 const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot(
213 serverConfig.cwd,
214 );
215 let nextProjectId: ProjectId;
216 let nextThreadModelSelection: ModelSelection;
217​
218 if (Option.isNone(existingProject)) {
219 const createdAt = DateTime.formatIso(yield* DateTime.now);
220 nextProjectId = ProjectId.make(yield* randomUUID);
221 const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
222 nextThreadModelSelection = defaultModelSelection;
223 yield* orchestrationEngine.dispatch({
224 type: "project.create",
225 commandId: CommandId.make(yield* randomUUID),
226 projectId: nextProjectId,
227 title: bootstrapProjectTitle,
228 workspaceRoot: serverConfig.cwd,
229 createdAt,
230 });
231 bootstrapProjectId = nextProjectId;
232 bootstrapProjectCreated = true;
233 } else {
234 nextProjectId = existingProject.value.id;
235 bootstrapProjectId = nextProjectId;
236 nextThreadModelSelection =
237 resolveProjectSettings(settings, nextProjectId, existingProject.value).settings
238 .defaultModelSelection ?? defaultModelSelection;
239 }
240​
241 yield* Effect.gen(function* () {
242 const existingThreadId =
243 yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
244 if (Option.isNone(existingThreadId)) {
245 const createdAt = DateTime.formatIso(yield* DateTime.now);
246 const createdThreadId = ThreadId.make(yield* randomUUID);
247 yield* orchestrationEngine.dispatch({
248 type: "thread.create",
249 commandId: CommandId.make(yield* randomUUID),
250 threadId: createdThreadId,
251 projectId: nextProjectId,
252 title: "New thread",
253 modelSelection: nextThreadModelSelection,
254 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
255 runtimeMode: resolveProjectSettings(settings, nextProjectId).settings
256 .defaultRuntimeMode,
257 branch: null,
258 worktreePath: null,
259 createdAt,
260 });
261 bootstrapThreadId = createdThreadId;
262 bootstrapThreadCreated = true;
263 } else {
264 bootstrapThreadId = existingThreadId.value;
265 }
266 }).pipe(
267 Effect.catchCauseIf(
268 (cause) => !Cause.hasInterrupts(cause),
269 (cause) =>
270 Effect.logWarning("startup thread auto-bootstrap failed", {
271 bootstrapProjectId: nextProjectId,
272 cause,
273 }),
274 ),
275 );
276 });
277 }
278​
279 return {
280 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
281 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
282 ...(bootstrapProjectId ? { bootstrapProjectCreated } : {}),
283 ...(bootstrapThreadId ? { bootstrapThreadCreated } : {}),
284 } as const;
285});
286​
287export const completeAutoBootstrapWelcome = <A extends object, E, R>(
288 bootstrap: Effect.Effect<A, E, R>,
289) =>
290 bootstrap.pipe(
291 Effect.matchCauseEffect({
292 onFailure: (cause) =>
293 Cause.hasInterrupts(cause)
294 ? Effect.failCause(cause)
295 : Effect.logWarning("startup auto-bootstrap failed", { cause }).pipe(
296 Effect.as({ bootstrapStatus: "complete" as const }),
297 ),
298 onSuccess: (targets) =>
299 Effect.succeed({
300 ...targets,
301 bootstrapStatus: "complete" as const,
302 }),
303 }),
304 );
305​
306const resolveStartupBrowserTarget = Effect.gen(function* () {
307 const serverConfig = yield* ServerConfig.ServerConfig;
308 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
309 const localUrl = `http://localhost:${serverConfig.port}`;
310 const bindUrl =
311 serverConfig.host && !isWildcardHost(serverConfig.host)
312 ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
313 : localUrl;
314 const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
315 return serverConfig.mode === "desktop"
316 ? baseTarget
317 : yield* serverAuth.issueStartupPairingUrl(baseTarget);
318});
319​
320const maybeOpenBrowser = (target: string) =>
321 Effect.gen(function* () {
322 const serverConfig = yield* ServerConfig.ServerConfig;
323 if (serverConfig.noBrowser) {
324 return;
325 }
326 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
327​
328 yield* externalLauncher.launchBrowser(target).pipe(
329 Effect.catch(() =>
330 Effect.logInfo("browser auto-open unavailable", {
331 hint: `Open ${target} in your browser.`,
332 }),
333 ),
334 );
335 });
336​
337const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
338 effect.pipe(
339 Effect.annotateSpans({ "startup.phase": phase }),
340 Effect.withSpan(`server.startup.${phase}`),
341 );
342​
343const ORPHANED_PROVIDER_SESSION_ERROR =
344 "Provider session did not survive a server restart. Send a new message to continue.";
345const SERVER_UPDATE_CONTINUATION_KEY = "continueAfterServerUpdate";
346const SERVER_UPDATE_CONTINUATION_PROMPT = "Continue where you left off.";
347​
348class ProviderSessionContinuationError extends Schema.TaggedError<ProviderSessionContinuationError>()(
349 "ProviderSessionContinuationError",
350 {
351 threadId: ThreadId,
352 },
353) {
354 override get message(): string {
355 return `Could not continue thread '${this.threadId}': the provider instance is missing.`;
356 }
358​
359export class ServerUpdateThreadContinuationError extends Schema.TaggedError<ServerUpdateThreadContinuationError>()(
360 "ServerUpdateThreadContinuationError",
361 {
362 cause: Schema.Defect(),
363 },
364) {
365 override get message(): string {
366 return "Could not prepare running threads to continue after the update.";
367 }
369​
370function hasServerUpdateContinuationMarker(
371 runtimePayload: unknown,
372): runtimePayload is Record<string, unknown> {
373 return (
374 runtimePayload !== null &&
375 typeof runtimePayload === "object" &&
376 !Array.isArray(runtimePayload) &&
377 SERVER_UPDATE_CONTINUATION_KEY in runtimePayload
378 );
380​
381function readRuntimePayload(runtimePayload: unknown): Record<string, unknown> {
382 return runtimePayload !== null &&
383 typeof runtimePayload === "object" &&
384 !Array.isArray(runtimePayload)
385 ? (runtimePayload as Record<string, unknown>)
386 : {};
388​
389const isServerUpdateThreadContinuationError = Schema.is(ServerUpdateThreadContinuationError);
390​
391function readServerUpdateContinuationTurnId(runtimePayload: unknown): TurnId | null {
392 if (!hasServerUpdateContinuationMarker(runtimePayload)) {
393 return null;
394 }
395 const value = runtimePayload[SERVER_UPDATE_CONTINUATION_KEY];
396 return typeof value === "string" && value.length > 0 ? TurnId.make(value) : null;
398​
399const toServerUpdateThreadContinuationError = (cause: unknown) =>
400 isServerUpdateThreadContinuationError(cause)
401 ? cause
402 : new ServerUpdateThreadContinuationError({ cause });
403​
404export const markRunningProviderSessionsForContinuation = Effect.gen(function* () {
405 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
406 const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
407 const { threads } = yield* query.getCommandReadModel();
408 const running = threads.filter(
409 (thread) =>
410 thread.archivedAt === null &&
411 thread.deletedAt === null &&
412 thread.session?.status === "running" &&
413 thread.session.activeTurnId !== null,
414 );
415​
416 const marked: ThreadId[] = [];
417 return yield* Effect.gen(function* () {
418 for (const thread of running) {
419 const activeTurnId = thread.session?.activeTurnId;
420 if (activeTurnId === null || activeTurnId === undefined) {
421 continue;
422 }
423 const binding = yield* directory.getBinding(thread.id);
424 if (Option.isNone(binding)) {
425 continue;
426 }
427 if (binding.value.resumeCursor === null || binding.value.resumeCursor === undefined) {
428 continue;
429 }
430 yield* directory.upsert({
431 ...binding.value,
432 runtimePayload: {
433 ...readRuntimePayload(binding.value.runtimePayload),
434 [SERVER_UPDATE_CONTINUATION_KEY]: activeTurnId,
435 continueAfterServerUpdatePrepared: null,
436 },
437 });
438 marked.push(thread.id);
439 }
440 return marked;
441 }).pipe(
442 Effect.catchCause((cause) =>
443 clearProviderSessionContinuationMarkers(marked).pipe(Effect.andThen(Effect.failCause(cause))),
444 ),
445 );
446}).pipe(Effect.mapError(toServerUpdateThreadContinuationError));
447​
448const clearContinuationMarkers = (
449 directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"],
450 threadIds: ReadonlyArray<ThreadId>,
451) =>
452 Effect.forEach(
453 threadIds,
454 (threadId) =>
455 directory.getBinding(threadId).pipe(
456 Effect.flatMap(
457 Option.match({
458 onNone: () => Effect.void,
459 onSome: (binding) =>
460 directory.upsert({
461 ...binding,
462 runtimePayload: {
463 ...readRuntimePayload(binding.runtimePayload),
464 [SERVER_UPDATE_CONTINUATION_KEY]: null,
465 continueAfterServerUpdatePrepared: null,
466 },
467 }),
468 }),
469 ),
470 ),
471 { concurrency: "unbounded", discard: true },
472 );
473​
474const clearProviderSessionContinuationMarkers = (threadIds: ReadonlyArray<ThreadId>) =>
475 Effect.gen(function* () {
476 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
477 yield* clearContinuationMarkers(directory, threadIds);
478 }).pipe(Effect.mapError(toServerUpdateThreadContinuationError));
479​
480export const reconcileProviderSessions = Effect.gen(function* () {
481 const crypto = yield* Crypto.Crypto;
482 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
483 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
484 const providerService = yield* ProviderService.ProviderService;
485 const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
486 const settings = yield* ServerSettings.ServerSettingsService;
487 const restartSettings = yield* settings.getSettings.pipe(
488 Effect.asSome,
489 Effect.catch((cause) =>
490 Effect.logWarning("could not read restart continuation preference", { cause }).pipe(
491 Effect.as(Option.none()),
492 ),
493 ),
494 );
495 const continueAfterRestartFor = (projectId: ProjectId) =>
496 Option.isSome(restartSettings)
497 ? resolveProjectSettings(restartSettings.value, projectId).settings
498 .continueThreadsAfterServerUpdate
499 : false;
500​
501 const liveThreadIds = new Set(
502 (yield* providerService.listSessions()).map((session) => session.threadId),
503 );
504 const { threads } = yield* query.getCommandReadModel();
505 // Provider startup can report ready before the continuation is submitted.
506 // Find those markers in one read rather than querying every idle thread.
507 const preparedThreadIds = new Set(
508 (yield* directory.listBindings().pipe(
509 Effect.catch((cause) =>
510 Effect.logWarning("failed to read prepared provider continuations", { cause }).pipe(
511 Effect.andThen(
512 Effect.forEach(
513 threads.filter(
514 (thread) => thread.session?.status === "ready" && !liveThreadIds.has(thread.id),
515 ),
516 (thread) =>
517 directory.getBinding(thread.id).pipe(Effect.orElseSucceed(() => Option.none())),
518 ),
519 ),
520 Effect.map((bindings) =>
521 bindings.flatMap((binding) => (Option.isSome(binding) ? [binding.value] : [])),
522 ),
523 ),
524 ),
525 ))
526 .filter(
527 (binding) =>
528 readServerUpdateContinuationTurnId(binding.runtimePayload) !== null &&
529 readRuntimePayload(binding.runtimePayload).activeTurnId === null &&
530 readRuntimePayload(binding.runtimePayload).continueAfterServerUpdatePrepared === true,
531 )
532 .map((binding) => binding.threadId),
533 );
534 const orphanedThreads = threads.filter(
535 (thread) =>
536 thread.session !== null &&
537 (thread.session.status === "starting" ||
538 thread.session.status === "running" ||
539 thread.session.activeTurnId !== null ||
540 (thread.session.status === "ready" && preparedThreadIds.has(thread.id))) &&
541 !liveThreadIds.has(thread.id),
542 );
543​
544 for (const thread of orphanedThreads) {
545 const session = thread.session;
546 if (session === null) {
547 continue;
548 }
549 const binding = yield* directory.getBinding(thread.id).pipe(
550 Effect.catchCauseIf(
551 (cause) => !Cause.hasInterrupts(cause),
552 (cause) =>
553 Effect.logWarning("failed to read orphaned provider session directory binding", {
554 threadId: thread.id,
555 cause,
556 }).pipe(Effect.as(Option.none())),
557 ),
558 );
559 const continuationMarkerPresent =
560 Option.isSome(binding) && hasServerUpdateContinuationMarker(binding.value.runtimePayload);
561 const continuationTurnId = Option.isSome(binding)
562 ? readServerUpdateContinuationTurnId(binding.value.runtimePayload)
563 : null;
564 const continuationMarked =
565 continuationTurnId !== null &&
566 (session.activeTurnId === null || continuationTurnId === session.activeTurnId) &&
567 Option.isSome(binding) &&
568 (session.activeTurnId !== null ||
569 readRuntimePayload(binding.value.runtimePayload).activeTurnId == null ||
570 readRuntimePayload(binding.value.runtimePayload).activeTurnId === continuationTurnId);
571 const preparedWhileReady =
572 session.status === "ready" &&
573 session.activeTurnId === null &&
574 continuationMarked &&
575 Option.isSome(binding) &&
576 readRuntimePayload(binding.value.runtimePayload).activeTurnId === null &&
577 readRuntimePayload(binding.value.runtimePayload).continueAfterServerUpdatePrepared === true;
578 // Runtime events advance the projection's turn, but not the directory's
579 // last admitted turn. Use the projection to identify interrupted work.
580 const interruptedByRestart =
581 continueAfterRestartFor(thread.projectId) &&
582 session.status === "running" &&
583 session.activeTurnId !== null &&
584 Option.isSome(binding) &&
585 binding.value.status === "running" &&
586 binding.value.resumeCursor != null;
587 const settleAsError = (lastError: string) =>
588 Effect.gen(function* () {
589 yield* Effect.gen(function* () {
590 if (Option.isSome(binding)) {
591 yield* directory.upsert({
592 ...binding.value,
593 status: "stopped",
594 runtimePayload: {
595 ...readRuntimePayload(binding.value.runtimePayload),
596 activeTurnId: null,
597 ...(continuationMarkerPresent || interruptedByRestart
598 ? {
599 [SERVER_UPDATE_CONTINUATION_KEY]: null,
600 continueAfterServerUpdatePrepared: null,
601 }
602 : {}),
603 },
604 });
605 }
606 }).pipe(
607 Effect.catchCauseIf(
608 (cause) => !Cause.hasInterrupts(cause),
609 (cause) =>
610 Effect.logWarning("failed to reconcile orphaned provider session directory binding", {
611 threadId: thread.id,
612 cause,
613 }),
614 ),
615 );
616​
617 yield* Effect.gen(function* () {
618 const reconciledAt = DateTime.formatIso(yield* DateTime.now);
619 yield* orchestrationEngine.dispatch({
620 type: "thread.session.set",
621 commandId: CommandId.make(yield* crypto.randomUUIDv4),
622 threadId: thread.id,
623 session: {
624 ...session,
625 status: "error",
626 activeTurnId: null,
627 lastError,
628 updatedAt: reconciledAt,
629 },
630 createdAt: reconciledAt,
631 });
632 }).pipe(
633 Effect.retry({ times: 1 }),
634 Effect.catchCauseIf(
635 (cause) => !Cause.hasInterrupts(cause),
636 (cause) =>
637 Effect.logWarning("failed to settle orphaned provider session projection", {
638 threadId: thread.id,
639 cause,
640 }),
641 ),
642 );
643 });
644​
645 if (
646 Option.isSome(binding) &&
647 (continuationMarked || interruptedByRestart) &&
648 (session.status === "running" || session.status === "starting" || preparedWhileReady) &&
649 binding.value.resumeCursor != null &&
650 thread.archivedAt === null &&
651 thread.deletedAt === null
652 ) {
653 const prepared = yield* Effect.gen(function* () {
654 yield* directory.upsert({
655 ...binding.value,
656 status: "starting",
657 runtimePayload: {
658 ...readRuntimePayload(binding.value.runtimePayload),
659 // Keep recovery durable if this process also exits before sending.
660 [SERVER_UPDATE_CONTINUATION_KEY]: session.activeTurnId ?? continuationTurnId,
661 continueAfterServerUpdatePrepared: true,
662 activeTurnId: null,
663 },
664 });
665 const resumedAt = DateTime.formatIso(yield* DateTime.now);
666 yield* orchestrationEngine.dispatch({
667 type: "thread.session.set",
668 commandId: CommandId.make(yield* crypto.randomUUIDv4),
669 threadId: thread.id,
670 session: {
671 ...session,
672 status: "starting",
673 activeTurnId: null,
674 lastError: null,
675 updatedAt: resumedAt,
676 },
677 createdAt: resumedAt,
678 });
679 }).pipe(Effect.retry({ times: 1 }), Effect.exit);
680 if (Exit.isFailure(prepared)) {
681 if (Cause.hasInterrupts(prepared.cause)) {
682 return yield* Effect.failCause(prepared.cause);
683 }
684 yield* Effect.logWarning("failed to prepare provider session continuation", {
685 threadId: thread.id,
686 cause: prepared.cause,
687 });
688 yield* settleAsError(ORPHANED_PROVIDER_SESSION_ERROR);
689 continue;
690 }
691​
692 yield* forkParked(
693 Effect.gen(function* () {
694 const continuation = Effect.gen(function* () {
695 const providerInstanceId = binding.value.providerInstanceId;
696 if (providerInstanceId === undefined) {
697 return yield* new ProviderSessionContinuationError({
698 threadId: thread.id,
699 });
700 }
701 const capabilities = yield* providerService.getCapabilities(providerInstanceId);
702 yield* providerService.sendTurn({
703 threadId: thread.id,
704 ...(capabilities.promptlessTurnContinuation === true
705 ? { continuation: true }
706 : { input: SERVER_UPDATE_CONTINUATION_PROMPT }),
707 interactionMode: thread.interactionMode,
708 });
709 });
710 const continuationExit = yield* Effect.exit(continuation);
711 if (Exit.isSuccess(continuationExit) || Cause.hasInterrupts(continuationExit.cause)) {
712 if (Exit.isSuccess(continuationExit)) {
713 yield* clearContinuationMarkers(directory, [thread.id]).pipe(
714 Effect.uninterruptible,
715 Effect.catchCause((cause) =>
716 Effect.logWarning("failed to clear completed provider session continuation", {
717 threadId: thread.id,
718 cause,
719 }),
720 ),
721 );
722 }
723 return;
724 }
725 yield* Effect.logWarning("failed to continue provider session after server restart", {
726 threadId: thread.id,
727 cause: continuationExit.cause,
728 });
729 yield* settleAsError(
730 "Could not continue this thread after the server restart. Send a new message to continue.",
731 ).pipe(Effect.ignoreCause);
732 }),
733 );
734 continue;
735 }
736​
737 yield* settleAsError(ORPHANED_PROVIDER_SESSION_ERROR);
738 }
739}).pipe(
740 Effect.catchCauseIf(
741 (cause) => !Cause.hasInterrupts(cause),
742 (cause) => Effect.logWarning("provider session startup reconciliation failed", { cause }),
743 ),
744);
745​
746const decodeWorktreeSetupSnapshot = Schema.decodeUnknownOption(WorktreeSetupSnapshot);
747​
748/**
749 * A worktree bootstrap records its setup snapshot on the thread while it runs
750 * and settles it when it finishes. The bootstrap itself lives only in memory,
751 * so a process exit mid-setup leaves a `running` record with nobody to finish
752 * it. Before the turn started that also strands the persisted user message, so
753 * the setup is marked failed and the user is told to send again. After the
754 * handoff only an async setup script was still running; its stage is marked
755 * failed and the setup settles as done, like any other script failure.
756 */
757export const reconcileWorktreeSetups = Effect.gen(function* () {
758 const crypto = yield* Crypto.Crypto;
759 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
760 const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
761 // The command read model carries no activity bodies; read the setup
762 // records directly, live threads only.
763 const recordedSetups = yield* query.listActivitiesByKind(WORKTREE_SETUP_ACTIVITY_KIND);
764 const interruptedAt = DateTime.formatIso(yield* DateTime.now);
765​
766 for (const recorded of recordedSetups) {
767 const snapshot = decodeWorktreeSetupSnapshot(recorded.payload);
768 if (Option.isNone(snapshot) || snapshot.value.phase !== "running") continue;
769 if (recorded.id !== worktreeSetupActivityId(snapshot.value.threadId)) continue;
770 const threadId = snapshot.value.threadId;
771​
772 const turnStarted = snapshot.value.stages.some(
773 (stage) => stage.id === "agent" && stage.status === "done",
774 );
775 const interrupted: WorktreeSetupSnapshot = {
776 ...snapshot.value,
777 phase: turnStarted ? "done" : "failed",
778 endedAt: interruptedAt,
779 error: turnStarted
780 ? null
781 : "The server restarted before the worktree setup finished. Send the message again.",
782 stages: snapshot.value.stages.map((stage) =>
783 stage.status === "running" || stage.status === "pending"
784 ? {
785 ...stage,
786 status: "failed",
787 endedAt: interruptedAt,
788 detail: "interrupted by a server restart",
789 }
790 : stage,
791 ),
792 sequence: snapshot.value.sequence + 1,
793 };
794 yield* orchestrationEngine
795 .dispatch({
796 type: "thread.activity.append",
797 commandId: CommandId.make(yield* crypto.randomUUIDv4),
798 threadId,
799 activity: {
800 id: EventId.make(worktreeSetupActivityId(threadId)),
801 tone: "error",
802 kind: WORKTREE_SETUP_ACTIVITY_KIND,
803 summary: turnStarted
804 ? "Setup script interrupted by a server restart"
805 : "Worktree setup interrupted by a server restart",
806 payload: interrupted,
807 turnId: null,
808 createdAt: snapshot.value.startedAt,
809 },
810 createdAt: interruptedAt,
811 })
812 .pipe(
813 Effect.catchCauseIf(
814 (cause) => !Cause.hasInterrupts(cause),
815 (cause) =>
816 Effect.logWarning("failed to settle interrupted worktree setup", {
817 threadId,
818 cause,
819 }),
820 ),
821 );
822 }
823}).pipe(
824 Effect.catchCauseIf(
825 (cause) => !Cause.hasInterrupts(cause),
826 (cause) => Effect.logWarning("worktree setup startup reconciliation failed", { cause }),
827 ),
828);
829​
830interface StartupOptions {
831 readonly activate?: Effect.Effect<void>;
832 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
833 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
835​
836export const autoPullProjects = Effect.fn("autoPullProjects")(function* (
837 projects: ReadonlyArray<OrchestrationProjectShell>,
838 settings: ServerSettingsValue = DEFAULT_SERVER_SETTINGS,
839) {
840 const git = yield* GitVcsDriver.GitVcsDriver;
841 const workspaceRoots = [
842 ...new Set(
843 projects
844 .filter((project) => resolveProjectSettings(settings, project.id).settings.defaultAutoPull)
845 .map((project) => project.workspaceRoot),
846 ),
847 ];
848​
849 yield* Effect.forEach(
850 workspaceRoots,
851 (cwd) =>
852 Effect.gen(function* () {
853 const status = yield* git.statusDetails(cwd);
854 if (
855 !status.isRepo ||
856 !status.isDefaultBranch ||
857 !status.hasUpstream ||
858 status.hasWorkingTreeChanges ||
859 status.aheadCount > 0
860 ) {
861 yield* Effect.logDebug("Skipped automatic project pull", {
862 cwd,
863 reason: !status.isRepo
864 ? "not-a-repository"
865 : !status.isDefaultBranch
866 ? "not-on-default-branch"
867 : !status.hasUpstream
868 ? "no-upstream"
869 : status.hasWorkingTreeChanges
870 ? "working-tree-changes"
871 : "local-commits",
872 });
873 return;
874 }
875​
876 if (status.behindCount <= 0) return;
877​
878 const result = yield* git.pullCurrentBranch(cwd);
879 yield* Effect.logDebug("Automatic project pull completed", {
880 cwd,
881 status: result.status,
882 refName: result.refName,
883 });
884 }).pipe(
885 Effect.catch((cause) =>
886 Effect.logWarning("Automatic project pull failed", {
887 cwd,
888 cause,
889 }),
890 ),
891 ),
892 { concurrency: 4, discard: true },
893 );
894});
895​
896/** @public Service construction is part of the canonical Effect module API. */
897export const make = (options?: StartupOptions) =>
898 Effect.gen(function* () {
899 const serverConfig = yield* ServerConfig.ServerConfig;
900 const keybindings = yield* Keybindings.Keybindings;
901 const orchestrationReactor = yield* OrchestrationReactor.OrchestrationReactor;
902 const providerSessionReaper = yield* ProviderSessionReaper.ProviderSessionReaper;
903 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
904 const serverSettings = yield* ServerSettings.ServerSettingsService;
905 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
906 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
907 const providerSessionDirectory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
908 const crypto = yield* Crypto.Crypto;
909 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
910​
911 const commandGate = yield* makeCommandGate;
912 const httpListening = yield* Deferred.make<void>();
913 const reactorScope = yield* Scope.make("sequential");
914​
915 const syncAutoPullProjects = projectionSnapshotQuery.getShellSnapshot().pipe(
916 Effect.flatMap((snapshot) =>
917 serverSettings.getSettings.pipe(
918 Effect.flatMap((settings) => autoPullProjects(snapshot.projects, settings)),
919 ),
920 ),
921 Effect.catch((cause) =>
922 Effect.logWarning("Failed to load projects for automatic pull", { cause }),
923 ),
924 );
925​
926 yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
927​
928 const startup = Effect.gen(function* () {
929 yield* Effect.logDebug("startup phase: starting keybindings runtime");
930 yield* runStartupPhase(
931 "keybindings.start",
932 keybindings.start.pipe(
933 Effect.catch((error) =>
934 Effect.logWarning("failed to start keybindings runtime", {
935 path: error.configPath,
936 detail: error.detail,
937 cause: error.cause,
938 }),
939 ),
940 ),
941 );
942​
943 yield* Effect.logDebug("startup phase: starting server settings runtime");
944 yield* runStartupPhase(
945 "settings.start",
946 serverSettings.start.pipe(
947 Effect.catch((error) =>
948 Effect.logWarning("failed to start server settings runtime", {
949 path: error.settingsPath,
950 operation: error.operation,
951 providerInstanceId: error.providerInstanceId,
952 environmentVariable: error.environmentVariable,
953 cause: error.cause,
954 }),
955 ),
956 ),
957 );
958​
959 yield* Effect.logDebug("startup phase: parking orchestration roots at activation");
960 yield* runStartupPhase(
961 "reactors.start",
962 Effect.gen(function* () {
963 yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
964 yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));
965 }),
966 );
967​
968 yield* runStartupPhase("provider-sessions.reconcile", reconcileProviderSessions);
969 yield* runStartupPhase("worktree-setups.reconcile", reconcileWorktreeSetups);
970​
971 yield* Effect.logDebug("startup phase: syncing clean projects");
972 yield* runStartupPhase("projects.auto-pull", syncAutoPullProjects);
973​
974 const welcomeBase = yield* resolveWelcomeBase;
975 const environment = yield* serverEnvironment.getDescriptor;
976 yield* Effect.logDebug("startup phase: preparing welcome payload");
977​
978 if (serverConfig.autoBootstrapProjectFromCwd) {
979 yield* forkParked(
980 runStartupPhase(
981 "welcome.autobootstrap",
982 Effect.gen(function* () {
983 const bootstrapCompletion = yield* completeAutoBootstrapWelcome(
984 resolveAutoBootstrapWelcomeTargets.pipe(
985 Effect.provideService(Crypto.Crypto, crypto),
986 ),
987 );
988​
989 yield* Effect.logDebug(
990 "startup phase: publishing completed bootstrap welcome event",
991 {
992 environmentId: environment.environmentId,
993 cwd: welcomeBase.cwd,
994 projectName: welcomeBase.projectName,
995 ...bootstrapCompletion,
996 },
997 );
998 yield* lifecycleEvents.publish({
999 version: 1,
1000 type: "welcome",
1001 payload: {
1002 environment,
1003 ...welcomeBase,
1004 ...bootstrapCompletion,
1005 },
1006 });
1007 }).pipe(Effect.ignoreCause({ log: true })),
1008 ),
1009 );
1011​
1012 yield* forkParked(
1013 Effect.gen(function* () {
1014 yield* Effect.logDebug("startup phase: recording startup heartbeat");
1015 yield* recordStartupHeartbeat.pipe(
1016 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
1017 Effect.withSpan("server.startup.heartbeat.record"),
1018 Effect.ignoreCause({ log: true }),
1019 );
1020 if (serverConfig.startupPresentation === "headless") {
1021 const accessInfo = yield* issueHeadlessServeAccessInfo();
1022 yield* runStartupPhase(
1023 "headless.output",
1024 Console.log(formatHeadlessServeOutput(accessInfo)),
1025 );
1026 } else {
1027 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
1028 if (serverConfig.mode !== "desktop") {
1029 yield* Effect.logInfo(
1030 "Authentication required. Open T3 Code using the pairing URL.",
1031 ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
1033 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
1035 }),
1036 );
1037​
1038 yield* Effect.logDebug("startup phase: waiting for http listener");
1039 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
1040 yield* runStartupPhase(
1041 "auxiliary-roots.parked",
1042 options?.awaitAuxiliaryParked ?? Effect.void,
1043 );
1044​
1045 // This is the prepared boundary. Every dependency has been acquired and
1046 // every runtime root has confirmed that it is parked before this request.
1047 const updateOutcome = yield* launcher.prepareTrial;
1048 yield* runStartupPhase(
1049 "welcome.publish",
1050 lifecycleEvents.publish({
1051 version: 1,
1052 type: "welcome",
1053 payload: {
1054 environment,
1055 ...welcomeBase,
1056 bootstrapStatus: serverConfig.autoBootstrapProjectFromCwd ? "pending" : "complete",
1057 },
1058 }),
1059 );
1060 yield* options?.activate ?? Effect.void;
1061​
1062 yield* Effect.logDebug("Accepting commands");
1063 yield* commandGate.signalCommandReady;
1064 yield* runStartupPhase(
1065 "ready.publish",
1066 lifecycleEvents.publish({
1067 version: 1,
1068 type: "ready",
1069 payload: {
1070 at: DateTime.formatIso(yield* DateTime.now),
1071 environment,
1072 ...(updateOutcome === undefined ? {} : { updateOutcome }),
1073 },
1074 }),
1075 );
1076 yield* Effect.logDebug("startup phase: complete");
1077 }).pipe(
1078 Effect.annotateSpans({
1079 "server.mode": serverConfig.mode,
1080 "server.port": serverConfig.port,
1081 "server.host": serverConfig.host ?? "default",
1082 }),
1083 Effect.withSpan("server.startup", { kind: "server", root: true }),
1084 );
1085​
1086 yield* Effect.forkScoped(
1087 Effect.exit(startup).pipe(
1088 Effect.flatMap((startupExit) => {
1089 if (Exit.isSuccess(startupExit)) return Effect.void;
1090 const error = new ServerRuntimeStartupError({
1091 mode: serverConfig.mode,
1092 host: serverConfig.host ?? null,
1093 port: serverConfig.port,
1094 cause: startupExit.cause,
1095 });
1096 return Effect.logError("server runtime startup failed", {
1097 cause: startupExit.cause,
1098 }).pipe(
1099 Effect.andThen(commandGate.failCommandReady(error)),
1100 Effect.andThen(options?.abort?.(error) ?? Effect.void),
1101 );
1102 }),
1103 ),
1104 );
1105​
1106 return {
1107 awaitCommandReady: commandGate.awaitCommandReady,
1108 markHttpListening: Deferred.succeed(httpListening, undefined),
1109 markRunningProviderSessionsForContinuation: markRunningProviderSessionsForContinuation.pipe(
1110 Effect.provideService(
1111 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
1112 projectionSnapshotQuery,
1113 ),
1114 Effect.provideService(
1115 ProviderSessionDirectory.ProviderSessionDirectory,
1116 providerSessionDirectory,
1117 ),
1118 ),
1119 clearProviderSessionContinuationMarkers: (threadIds) =>
1120 clearProviderSessionContinuationMarkers(threadIds).pipe(
1121 Effect.provideService(
1122 ProviderSessionDirectory.ProviderSessionDirectory,
1123 providerSessionDirectory,
1124 ),
1125 ),
1126 enqueueCommand: commandGate.enqueueCommand,
1127 } satisfies ServerRuntimeStartup["Service"];
1128 });
1129​
1130export const layerWithOptions = (options?: StartupOptions) =>
1131 Layer.effect(ServerRuntimeStartup, make(options));
1132​
1133export const layer = layerWithOptions();