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