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

serverRuntimeStartup.ts

993 lines36.3 KB

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