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