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

serverRuntimeStartup.ts

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