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

serverRuntimeStartup.ts

1,137 lines41.7 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.catchCause((cause) =>
268 Cause.hasInterrupts(cause)
269 ? Effect.failCause(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 yield* Effect.succeed(serverConfig.mode === "desktop" ? baseTarget : undefined).pipe(
316 Effect.flatMap((target) =>
317 target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget),
318 ),
319 );
320});
321​
322const maybeOpenBrowser = (target: string) =>
323 Effect.gen(function* () {
324 const serverConfig = yield* ServerConfig.ServerConfig;
325 if (serverConfig.noBrowser) {
326 return;
327 }
328 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
329​
330 yield* externalLauncher.launchBrowser(target).pipe(
331 Effect.catch(() =>
332 Effect.logInfo("browser auto-open unavailable", {
333 hint: `Open ${target} in your browser.`,
334 }),
335 ),
336 );
337 });
338​
339const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
340 effect.pipe(
341 Effect.annotateSpans({ "startup.phase": phase }),
342 Effect.withSpan(`server.startup.${phase}`),
343 );
344​
345const ORPHANED_PROVIDER_SESSION_ERROR =
346 "Provider session did not survive a server restart. Send a new message to continue.";
347const SERVER_UPDATE_CONTINUATION_KEY = "continueAfterServerUpdate";
348const SERVER_UPDATE_CONTINUATION_PROMPT = "Continue where you left off.";
349​
350class ProviderSessionContinuationError extends Schema.TaggedError<ProviderSessionContinuationError>()(
351 "ProviderSessionContinuationError",
352 {
353 threadId: ThreadId,
354 },
355) {
356 override get message(): string {
357 return `Could not continue thread '${this.threadId}': the provider instance is missing.`;
358 }
360​
361export class ServerUpdateThreadContinuationError extends Schema.TaggedError<ServerUpdateThreadContinuationError>()(
362 "ServerUpdateThreadContinuationError",
363 {
364 cause: Schema.Defect(),
365 },
366) {
367 override get message(): string {
368 return "Could not prepare running threads to continue after the update.";
369 }
371​
372function hasServerUpdateContinuationMarker(
373 runtimePayload: unknown,
374): runtimePayload is Record<string, unknown> {
375 return (
376 runtimePayload !== null &&
377 typeof runtimePayload === "object" &&
378 !Array.isArray(runtimePayload) &&
379 SERVER_UPDATE_CONTINUATION_KEY in runtimePayload
380 );
382​
383function readRuntimePayload(runtimePayload: unknown): Record<string, unknown> {
384 return runtimePayload !== null &&
385 typeof runtimePayload === "object" &&
386 !Array.isArray(runtimePayload)
387 ? (runtimePayload as Record<string, unknown>)
388 : {};
390​
391const isServerUpdateThreadContinuationError = Schema.is(ServerUpdateThreadContinuationError);
392​
393function readServerUpdateContinuationTurnId(runtimePayload: unknown): TurnId | null {
394 if (!hasServerUpdateContinuationMarker(runtimePayload)) {
395 return null;
396 }
397 const value = runtimePayload[SERVER_UPDATE_CONTINUATION_KEY];
398 return typeof value === "string" && value.length > 0 ? TurnId.make(value) : null;
400​
401const toServerUpdateThreadContinuationError = (cause: unknown) =>
402 isServerUpdateThreadContinuationError(cause)
403 ? cause
404 : new ServerUpdateThreadContinuationError({ cause });
405​
406export const markRunningProviderSessionsForContinuation = Effect.gen(function* () {
407 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
408 const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
409 const { threads } = yield* query.getCommandReadModel();
410 const running = threads.filter(
411 (thread) =>
412 thread.archivedAt === null &&
413 thread.deletedAt === null &&
414 thread.session?.status === "running" &&
415 thread.session.activeTurnId !== null,
416 );
417​
418 const marked: ThreadId[] = [];
419 return yield* Effect.gen(function* () {
420 for (const thread of running) {
421 const activeTurnId = thread.session?.activeTurnId;
422 if (activeTurnId === null || activeTurnId === undefined) {
423 continue;
424 }
425 const binding = yield* directory.getBinding(thread.id);
426 if (Option.isNone(binding)) {
427 continue;
428 }
429 if (binding.value.resumeCursor === null || binding.value.resumeCursor === undefined) {
430 continue;
431 }
432 yield* directory.upsert({
433 ...binding.value,
434 runtimePayload: {
435 ...readRuntimePayload(binding.value.runtimePayload),
436 [SERVER_UPDATE_CONTINUATION_KEY]: activeTurnId,
437 continueAfterServerUpdatePrepared: null,
438 },
439 });
440 marked.push(thread.id);
441 }
442 return marked;
443 }).pipe(
444 Effect.catchCause((cause) =>
445 clearProviderSessionContinuationMarkers(marked).pipe(Effect.andThen(Effect.failCause(cause))),
446 ),
447 );
448}).pipe(Effect.mapError(toServerUpdateThreadContinuationError));
449​
450const clearContinuationMarkers = (
451 directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"],
452 threadIds: ReadonlyArray<ThreadId>,
453) =>
454 Effect.forEach(
455 threadIds,
456 (threadId) =>
457 directory.getBinding(threadId).pipe(
458 Effect.flatMap(
459 Option.match({
460 onNone: () => Effect.void,
461 onSome: (binding) =>
462 directory.upsert({
463 ...binding,
464 runtimePayload: {
465 ...readRuntimePayload(binding.runtimePayload),
466 [SERVER_UPDATE_CONTINUATION_KEY]: null,
467 continueAfterServerUpdatePrepared: null,
468 },
469 }),
470 }),
471 ),
472 ),
473 { concurrency: "unbounded", discard: true },
474 );
475​
476const clearProviderSessionContinuationMarkers = (threadIds: ReadonlyArray<ThreadId>) =>
477 Effect.gen(function* () {
478 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
479 yield* clearContinuationMarkers(directory, threadIds);
480 }).pipe(Effect.mapError(toServerUpdateThreadContinuationError));
481​
482export const reconcileProviderSessions = Effect.gen(function* () {
483 const crypto = yield* Crypto.Crypto;
484 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
485 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
486 const providerService = yield* ProviderService.ProviderService;
487 const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
488 const settings = yield* ServerSettings.ServerSettingsService;
489 const restartSettings = yield* settings.getSettings.pipe(
490 Effect.map(Option.some),
491 Effect.catch((cause) =>
492 Effect.logWarning("could not read restart continuation preference", { cause }).pipe(
493 Effect.as(Option.none()),
494 ),
495 ),
496 );
497 const continueAfterRestartFor = (projectId: ProjectId) =>
498 Option.isSome(restartSettings)
499 ? resolveProjectSettings(restartSettings.value, projectId).settings
500 .continueThreadsAfterServerUpdate
501 : false;
502​
503 const liveThreadIds = new Set(
504 (yield* providerService.listSessions()).map((session) => session.threadId),
505 );
506 const { threads } = yield* query.getCommandReadModel();
507 // Provider startup can report ready before the continuation is submitted.
508 // Find those markers in one read rather than querying every idle thread.
509 const preparedThreadIds = new Set(
510 (yield* directory.listBindings().pipe(
511 Effect.catch((cause) =>
512 Effect.logWarning("failed to read prepared provider continuations", { cause }).pipe(
513 Effect.andThen(
514 Effect.forEach(
515 threads.filter(
516 (thread) => thread.session?.status === "ready" && !liveThreadIds.has(thread.id),
517 ),
518 (thread) =>
519 directory.getBinding(thread.id).pipe(Effect.orElseSucceed(() => Option.none())),
520 ),
521 ),
522 Effect.map((bindings) =>
523 bindings.flatMap((binding) => (Option.isSome(binding) ? [binding.value] : [])),
524 ),
525 ),
526 ),
527 ))
528 .filter(
529 (binding) =>
530 readServerUpdateContinuationTurnId(binding.runtimePayload) !== null &&
531 readRuntimePayload(binding.runtimePayload).activeTurnId === null &&
532 readRuntimePayload(binding.runtimePayload).continueAfterServerUpdatePrepared === true,
533 )
534 .map((binding) => binding.threadId),
535 );
536 const orphanedThreads = threads.filter(
537 (thread) =>
538 thread.session !== null &&
539 (thread.session.status === "starting" ||
540 thread.session.status === "running" ||
541 thread.session.activeTurnId !== null ||
542 (thread.session.status === "ready" && preparedThreadIds.has(thread.id))) &&
543 !liveThreadIds.has(thread.id),
544 );
545​
546 for (const thread of orphanedThreads) {
547 const session = thread.session;
548 if (session === null) {
549 continue;
550 }
551 const binding = yield* directory.getBinding(thread.id).pipe(
552 Effect.catchCause((cause) =>
553 Cause.hasInterrupts(cause)
554 ? Effect.failCause(cause)
555 : Effect.logWarning("failed to read orphaned provider session directory binding", {
556 threadId: thread.id,
557 cause,
558 }).pipe(Effect.as(Option.none())),
559 ),
560 );
561 const continuationMarkerPresent =
562 Option.isSome(binding) && hasServerUpdateContinuationMarker(binding.value.runtimePayload);
563 const continuationTurnId = Option.isSome(binding)
564 ? readServerUpdateContinuationTurnId(binding.value.runtimePayload)
565 : null;
566 const continuationMarked =
567 continuationTurnId !== null &&
568 (session.activeTurnId === null || continuationTurnId === session.activeTurnId) &&
569 Option.isSome(binding) &&
570 (session.activeTurnId !== null ||
571 readRuntimePayload(binding.value.runtimePayload).activeTurnId == null ||
572 readRuntimePayload(binding.value.runtimePayload).activeTurnId === continuationTurnId);
573 const preparedWhileReady =
574 session.status === "ready" &&
575 session.activeTurnId === null &&
576 continuationMarked &&
577 Option.isSome(binding) &&
578 readRuntimePayload(binding.value.runtimePayload).activeTurnId === null &&
579 readRuntimePayload(binding.value.runtimePayload).continueAfterServerUpdatePrepared === true;
580 // Runtime events advance the projection's turn, but not the directory's
581 // last admitted turn. Use the projection to identify interrupted work.
582 const interruptedByRestart =
583 continueAfterRestartFor(thread.projectId) &&
584 session.status === "running" &&
585 session.activeTurnId !== null &&
586 Option.isSome(binding) &&
587 binding.value.status === "running" &&
588 binding.value.resumeCursor != null;
589 const settleAsError = (lastError: string) =>
590 Effect.gen(function* () {
591 yield* Effect.gen(function* () {
592 if (Option.isSome(binding)) {
593 yield* directory.upsert({
594 ...binding.value,
595 status: "stopped",
596 runtimePayload: {
597 ...readRuntimePayload(binding.value.runtimePayload),
598 activeTurnId: null,
599 ...(continuationMarkerPresent || interruptedByRestart
600 ? {
601 [SERVER_UPDATE_CONTINUATION_KEY]: null,
602 continueAfterServerUpdatePrepared: null,
603 }
604 : {}),
605 },
606 });
607 }
608 }).pipe(
609 Effect.catchCause((cause) =>
610 Cause.hasInterrupts(cause)
611 ? Effect.failCause(cause)
612 : Effect.logWarning(
613 "failed to reconcile orphaned provider session directory binding",
614 { threadId: thread.id, cause },
615 ),
616 ),
617 );
618​
619 yield* Effect.gen(function* () {
620 const reconciledAt = DateTime.formatIso(yield* DateTime.now);
621 yield* orchestrationEngine.dispatch({
622 type: "thread.session.set",
623 commandId: CommandId.make(yield* crypto.randomUUIDv4),
624 threadId: thread.id,
625 session: {
626 ...session,
627 status: "error",
628 activeTurnId: null,
629 lastError,
630 updatedAt: reconciledAt,
631 },
632 createdAt: reconciledAt,
633 });
634 }).pipe(
635 Effect.retry({ times: 1 }),
636 Effect.catchCause((cause) =>
637 Cause.hasInterrupts(cause)
638 ? Effect.failCause(cause)
639 : Effect.logWarning("failed to settle orphaned provider session projection", {
640 threadId: thread.id,
641 cause,
642 }),
643 ),
644 );
645 });
646​
647 if (
648 Option.isSome(binding) &&
649 (continuationMarked || interruptedByRestart) &&
650 (session.status === "running" || session.status === "starting" || preparedWhileReady) &&
651 binding.value.resumeCursor != null &&
652 thread.archivedAt === null &&
653 thread.deletedAt === null
654 ) {
655 const prepared = yield* Effect.gen(function* () {
656 yield* directory.upsert({
657 ...binding.value,
658 status: "starting",
659 runtimePayload: {
660 ...readRuntimePayload(binding.value.runtimePayload),
661 // Keep recovery durable if this process also exits before sending.
662 [SERVER_UPDATE_CONTINUATION_KEY]: session.activeTurnId ?? continuationTurnId,
663 continueAfterServerUpdatePrepared: true,
664 activeTurnId: null,
665 },
666 });
667 const resumedAt = DateTime.formatIso(yield* DateTime.now);
668 yield* orchestrationEngine.dispatch({
669 type: "thread.session.set",
670 commandId: CommandId.make(yield* crypto.randomUUIDv4),
671 threadId: thread.id,
672 session: {
673 ...session,
674 status: "starting",
675 activeTurnId: null,
676 lastError: null,
677 updatedAt: resumedAt,
678 },
679 createdAt: resumedAt,
680 });
681 }).pipe(Effect.retry({ times: 1 }), Effect.exit);
682 if (Exit.isFailure(prepared)) {
683 if (Cause.hasInterrupts(prepared.cause)) {
684 return yield* Effect.failCause(prepared.cause);
685 }
686 yield* Effect.logWarning("failed to prepare provider session continuation", {
687 threadId: thread.id,
688 cause: prepared.cause,
689 });
690 yield* settleAsError(ORPHANED_PROVIDER_SESSION_ERROR);
691 continue;
692 }
693​
694 yield* forkParked(
695 Effect.gen(function* () {
696 const continuation = Effect.gen(function* () {
697 const providerInstanceId = binding.value.providerInstanceId;
698 if (providerInstanceId === undefined) {
699 return yield* new ProviderSessionContinuationError({
700 threadId: thread.id,
701 });
702 }
703 const capabilities = yield* providerService.getCapabilities(providerInstanceId);
704 yield* providerService.sendTurn({
705 threadId: thread.id,
706 ...(capabilities.promptlessTurnContinuation === true
707 ? { continuation: true }
708 : { input: SERVER_UPDATE_CONTINUATION_PROMPT }),
709 interactionMode: thread.interactionMode,
710 });
711 });
712 const continuationExit = yield* Effect.exit(continuation);
713 if (Exit.isSuccess(continuationExit) || Cause.hasInterrupts(continuationExit.cause)) {
714 if (Exit.isSuccess(continuationExit)) {
715 yield* clearContinuationMarkers(directory, [thread.id]).pipe(
716 Effect.uninterruptible,
717 Effect.catchCause((cause) =>
718 Effect.logWarning("failed to clear completed provider session continuation", {
719 threadId: thread.id,
720 cause,
721 }),
722 ),
723 );
724 }
725 return;
726 }
727 yield* Effect.logWarning("failed to continue provider session after server restart", {
728 threadId: thread.id,
729 cause: continuationExit.cause,
730 });
731 yield* settleAsError(
732 "Could not continue this thread after the server restart. Send a new message to continue.",
733 ).pipe(Effect.ignoreCause);
734 }),
735 );
736 continue;
737 }
738​
739 yield* settleAsError(ORPHANED_PROVIDER_SESSION_ERROR);
740 }
741}).pipe(
742 Effect.catchCause((cause) =>
743 Cause.hasInterrupts(cause)
744 ? Effect.failCause(cause)
745 : Effect.logWarning("provider session startup reconciliation failed", { cause }),
746 ),
747);
748​
749const decodeWorktreeSetupSnapshot = Schema.decodeUnknownOption(WorktreeSetupSnapshot);
750​
751/**
752 * A worktree bootstrap records its setup snapshot on the thread while it runs
753 * and settles it when it finishes. The bootstrap itself lives only in memory,
754 * so a process exit mid-setup leaves a `running` record with nobody to finish
755 * it. Before the turn started that also strands the persisted user message, so
756 * the setup is marked failed and the user is told to send again. After the
757 * handoff only an async setup script was still running; its stage is marked
758 * failed and the setup settles as done, like any other script failure.
759 */
760export const reconcileWorktreeSetups = Effect.gen(function* () {
761 const crypto = yield* Crypto.Crypto;
762 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
763 const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
764 // The command read model carries no activity bodies; read the setup
765 // records directly, live threads only.
766 const recordedSetups = yield* query.listActivitiesByKind(WORKTREE_SETUP_ACTIVITY_KIND);
767 const interruptedAt = DateTime.formatIso(yield* DateTime.now);
768​
769 for (const recorded of recordedSetups) {
770 const snapshot = decodeWorktreeSetupSnapshot(recorded.payload);
771 if (Option.isNone(snapshot) || snapshot.value.phase !== "running") continue;
772 if (recorded.id !== worktreeSetupActivityId(snapshot.value.threadId)) continue;
773 const threadId = snapshot.value.threadId;
774​
775 const turnStarted = snapshot.value.stages.some(
776 (stage) => stage.id === "agent" && stage.status === "done",
777 );
778 const interrupted: WorktreeSetupSnapshot = {
779 ...snapshot.value,
780 phase: turnStarted ? "done" : "failed",
781 endedAt: interruptedAt,
782 error: turnStarted
783 ? null
784 : "The server restarted before the worktree setup finished. Send the message again.",
785 stages: snapshot.value.stages.map((stage) =>
786 stage.status === "running" || stage.status === "pending"
787 ? {
788 ...stage,
789 status: "failed",
790 endedAt: interruptedAt,
791 detail: "interrupted by a server restart",
792 }
793 : stage,
794 ),
795 sequence: snapshot.value.sequence + 1,
796 };
797 yield* orchestrationEngine
798 .dispatch({
799 type: "thread.activity.append",
800 commandId: CommandId.make(yield* crypto.randomUUIDv4),
801 threadId,
802 activity: {
803 id: EventId.make(worktreeSetupActivityId(threadId)),
804 tone: "error",
805 kind: WORKTREE_SETUP_ACTIVITY_KIND,
806 summary: turnStarted
807 ? "Setup script interrupted by a server restart"
808 : "Worktree setup interrupted by a server restart",
809 payload: interrupted,
810 turnId: null,
811 createdAt: snapshot.value.startedAt,
812 },
813 createdAt: interruptedAt,
814 })
815 .pipe(
816 Effect.catchCause((cause) =>
817 Cause.hasInterrupts(cause)
818 ? Effect.failCause(cause)
819 : Effect.logWarning("failed to settle interrupted worktree setup", {
820 threadId,
821 cause,
822 }),
823 ),
824 );
825 }
826}).pipe(
827 Effect.catchCause((cause) =>
828 Cause.hasInterrupts(cause)
829 ? Effect.failCause(cause)
830 : Effect.logWarning("worktree setup startup reconciliation failed", { cause }),
831 ),
832);
833​
834interface StartupOptions {
835 readonly activate?: Effect.Effect<void>;
836 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
837 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
839​
840export const autoPullProjects = Effect.fn("autoPullProjects")(function* (
841 projects: ReadonlyArray<OrchestrationProjectShell>,
842 settings: ServerSettingsValue = DEFAULT_SERVER_SETTINGS,
843) {
844 const git = yield* GitVcsDriver.GitVcsDriver;
845 const workspaceRoots = [
846 ...new Set(
847 projects
848 .filter((project) => resolveProjectSettings(settings, project.id).settings.defaultAutoPull)
849 .map((project) => project.workspaceRoot),
850 ),
851 ];
852​
853 yield* Effect.forEach(
854 workspaceRoots,
855 (cwd) =>
856 Effect.gen(function* () {
857 const status = yield* git.statusDetails(cwd);
858 if (
859 !status.isRepo ||
860 !status.isDefaultBranch ||
861 !status.hasUpstream ||
862 status.hasWorkingTreeChanges ||
863 status.aheadCount > 0
864 ) {
865 yield* Effect.logDebug("Skipped automatic project pull", {
866 cwd,
867 reason: !status.isRepo
868 ? "not-a-repository"
869 : !status.isDefaultBranch
870 ? "not-on-default-branch"
871 : !status.hasUpstream
872 ? "no-upstream"
873 : status.hasWorkingTreeChanges
874 ? "working-tree-changes"
875 : "local-commits",
876 });
877 return;
878 }
879​
880 if (status.behindCount <= 0) return;
881​
882 const result = yield* git.pullCurrentBranch(cwd);
883 yield* Effect.logDebug("Automatic project pull completed", {
884 cwd,
885 status: result.status,
886 refName: result.refName,
887 });
888 }).pipe(
889 Effect.catch((cause) =>
890 Effect.logWarning("Automatic project pull failed", {
891 cwd,
892 cause,
893 }),
894 ),
895 ),
896 { concurrency: 4, discard: true },
897 );
898});
899​
900/** @public Service construction is part of the canonical Effect module API. */
901export const make = (options?: StartupOptions) =>
902 Effect.gen(function* () {
903 const serverConfig = yield* ServerConfig.ServerConfig;
904 const keybindings = yield* Keybindings.Keybindings;
905 const orchestrationReactor = yield* OrchestrationReactor.OrchestrationReactor;
906 const providerSessionReaper = yield* ProviderSessionReaper.ProviderSessionReaper;
907 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
908 const serverSettings = yield* ServerSettings.ServerSettingsService;
909 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
910 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
911 const providerSessionDirectory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
912 const crypto = yield* Crypto.Crypto;
913 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
914​
915 const commandGate = yield* makeCommandGate;
916 const httpListening = yield* Deferred.make<void>();
917 const reactorScope = yield* Scope.make("sequential");
918​
919 const syncAutoPullProjects = projectionSnapshotQuery.getShellSnapshot().pipe(
920 Effect.flatMap((snapshot) =>
921 serverSettings.getSettings.pipe(
922 Effect.flatMap((settings) => autoPullProjects(snapshot.projects, settings)),
923 ),
924 ),
925 Effect.catch((cause) =>
926 Effect.logWarning("Failed to load projects for automatic pull", { cause }),
927 ),
928 );
929​
930 yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
931​
932 const startup = Effect.gen(function* () {
933 yield* Effect.logDebug("startup phase: starting keybindings runtime");
934 yield* runStartupPhase(
935 "keybindings.start",
936 keybindings.start.pipe(
937 Effect.catch((error) =>
938 Effect.logWarning("failed to start keybindings runtime", {
939 path: error.configPath,
940 detail: error.detail,
941 cause: error.cause,
942 }),
943 ),
944 ),
945 );
946​
947 yield* Effect.logDebug("startup phase: starting server settings runtime");
948 yield* runStartupPhase(
949 "settings.start",
950 serverSettings.start.pipe(
951 Effect.catch((error) =>
952 Effect.logWarning("failed to start server settings runtime", {
953 path: error.settingsPath,
954 operation: error.operation,
955 providerInstanceId: error.providerInstanceId,
956 environmentVariable: error.environmentVariable,
957 cause: error.cause,
958 }),
959 ),
960 ),
961 );
962​
963 yield* Effect.logDebug("startup phase: parking orchestration roots at activation");
964 yield* runStartupPhase(
965 "reactors.start",
966 Effect.gen(function* () {
967 yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
968 yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));
969 }),
970 );
971​
972 yield* runStartupPhase("provider-sessions.reconcile", reconcileProviderSessions);
973 yield* runStartupPhase("worktree-setups.reconcile", reconcileWorktreeSetups);
974​
975 yield* Effect.logDebug("startup phase: syncing clean projects");
976 yield* runStartupPhase("projects.auto-pull", syncAutoPullProjects);
977​
978 const welcomeBase = yield* resolveWelcomeBase;
979 const environment = yield* serverEnvironment.getDescriptor;
980 yield* Effect.logDebug("startup phase: preparing welcome payload");
981​
982 if (serverConfig.autoBootstrapProjectFromCwd) {
983 yield* forkParked(
984 runStartupPhase(
985 "welcome.autobootstrap",
986 Effect.gen(function* () {
987 const bootstrapCompletion = yield* completeAutoBootstrapWelcome(
988 resolveAutoBootstrapWelcomeTargets.pipe(
989 Effect.provideService(Crypto.Crypto, crypto),
990 ),
991 );
992​
993 yield* Effect.logDebug(
994 "startup phase: publishing completed bootstrap welcome event",
995 {
996 environmentId: environment.environmentId,
997 cwd: welcomeBase.cwd,
998 projectName: welcomeBase.projectName,
999 ...bootstrapCompletion,
1000 },
1001 );
1002 yield* lifecycleEvents.publish({
1003 version: 1,
1004 type: "welcome",
1005 payload: {
1006 environment,
1007 ...welcomeBase,
1008 ...bootstrapCompletion,
1009 },
1010 });
1011 }).pipe(Effect.ignoreCause({ log: true })),
1012 ),
1013 );
1015​
1016 yield* forkParked(
1017 Effect.gen(function* () {
1018 yield* Effect.logDebug("startup phase: recording startup heartbeat");
1019 yield* recordStartupHeartbeat.pipe(
1020 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
1021 Effect.withSpan("server.startup.heartbeat.record"),
1022 Effect.ignoreCause({ log: true }),
1023 );
1024 if (serverConfig.startupPresentation === "headless") {
1025 const accessInfo = yield* issueHeadlessServeAccessInfo();
1026 yield* runStartupPhase(
1027 "headless.output",
1028 Console.log(formatHeadlessServeOutput(accessInfo)),
1029 );
1030 } else {
1031 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
1032 if (serverConfig.mode !== "desktop") {
1033 yield* Effect.logInfo(
1034 "Authentication required. Open T3 Code using the pairing URL.",
1035 ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
1037 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
1039 }),
1040 );
1041​
1042 yield* Effect.logDebug("startup phase: waiting for http listener");
1043 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
1044 yield* runStartupPhase(
1045 "auxiliary-roots.parked",
1046 options?.awaitAuxiliaryParked ?? Effect.void,
1047 );
1048​
1049 // This is the prepared boundary. Every dependency has been acquired and
1050 // every runtime root has confirmed that it is parked before this request.
1051 const updateOutcome = yield* launcher.prepareTrial;
1052 yield* runStartupPhase(
1053 "welcome.publish",
1054 lifecycleEvents.publish({
1055 version: 1,
1056 type: "welcome",
1057 payload: {
1058 environment,
1059 ...welcomeBase,
1060 bootstrapStatus: serverConfig.autoBootstrapProjectFromCwd ? "pending" : "complete",
1061 },
1062 }),
1063 );
1064 yield* options?.activate ?? Effect.void;
1065​
1066 yield* Effect.logDebug("Accepting commands");
1067 yield* commandGate.signalCommandReady;
1068 yield* runStartupPhase(
1069 "ready.publish",
1070 lifecycleEvents.publish({
1071 version: 1,
1072 type: "ready",
1073 payload: {
1074 at: DateTime.formatIso(yield* DateTime.now),
1075 environment,
1076 ...(updateOutcome === undefined ? {} : { updateOutcome }),
1077 },
1078 }),
1079 );
1080 yield* Effect.logDebug("startup phase: complete");
1081 }).pipe(
1082 Effect.annotateSpans({
1083 "server.mode": serverConfig.mode,
1084 "server.port": serverConfig.port,
1085 "server.host": serverConfig.host ?? "default",
1086 }),
1087 Effect.withSpan("server.startup", { kind: "server", root: true }),
1088 );
1089​
1090 yield* Effect.forkScoped(
1091 Effect.exit(startup).pipe(
1092 Effect.flatMap((startupExit) => {
1093 if (Exit.isSuccess(startupExit)) return Effect.void;
1094 const error = new ServerRuntimeStartupError({
1095 mode: serverConfig.mode,
1096 host: serverConfig.host ?? null,
1097 port: serverConfig.port,
1098 cause: startupExit.cause,
1099 });
1100 return Effect.logError("server runtime startup failed", {
1101 cause: startupExit.cause,
1102 }).pipe(
1103 Effect.andThen(commandGate.failCommandReady(error)),
1104 Effect.andThen(options?.abort?.(error) ?? Effect.void),
1105 );
1106 }),
1107 ),
1108 );
1109​
1110 return {
1111 awaitCommandReady: commandGate.awaitCommandReady,
1112 markHttpListening: Deferred.succeed(httpListening, undefined),
1113 markRunningProviderSessionsForContinuation: markRunningProviderSessionsForContinuation.pipe(
1114 Effect.provideService(
1115 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
1116 projectionSnapshotQuery,
1117 ),
1118 Effect.provideService(
1119 ProviderSessionDirectory.ProviderSessionDirectory,
1120 providerSessionDirectory,
1121 ),
1122 ),
1123 clearProviderSessionContinuationMarkers: (threadIds) =>
1124 clearProviderSessionContinuationMarkers(threadIds).pipe(
1125 Effect.provideService(
1126 ProviderSessionDirectory.ProviderSessionDirectory,
1127 providerSessionDirectory,
1128 ),
1129 ),
1130 enqueueCommand: commandGate.enqueueCommand,
1131 } satisfies ServerRuntimeStartup["Service"];
1132 });
1133​
1134export const layerWithOptions = (options?: StartupOptions) =>
1135 Layer.effect(ServerRuntimeStartup, make(options));
1136​
1137export const layer = layerWithOptions();