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