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

serverRuntimeStartup.ts

1,046 lines38.1 KB

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