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

serverRuntimeStartup.ts

1,042 lines37.9 KB

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