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