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

serverRuntimeStartup.ts

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