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

serverRuntimeStartup.ts

726 lines26.3 KB

1import {
2 CommandId,
3 DEFAULT_MODEL,
4 DEFAULT_PROVIDER_INTERACTION_MODE,
5 DEFAULT_SERVER_SETTINGS,
6 type ModelSelection,
7 type Project,
8 ProjectId,
9 ProviderInstanceId,
10 ThreadId,
11} from "@t3tools/contracts";
12import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
13import * as Cause from "effect/Cause";
14import * as Console from "effect/Console";
15import * as Context from "effect/Context";
16import * as Crypto from "effect/Crypto";
17import * as DateTime from "effect/DateTime";
18import * as Deferred from "effect/Deferred";
19import * as Effect from "effect/Effect";
20import * as Exit from "effect/Exit";
21import * as Fiber from "effect/Fiber";
22import * as Layer from "effect/Layer";
23import * as Path from "effect/Path";
24import * as Queue from "effect/Queue";
25import * as Ref from "effect/Ref";
26import * as Schema from "effect/Schema";
27​
28import * as ServerConfig from "./config.ts";
29import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
30import { flushCompileCache } from "./compileCache.ts";
31import * as Keybindings from "./keybindings.ts";
32import * as ExternalLauncher from "./process/externalLauncher.ts";
33import * as EffectWorker from "./orchestration-v2/EffectWorker.ts";
34import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
35import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
36import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts";
37import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
38import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts";
39import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
40import * as ProjectService from "./project/ProjectService.ts";
41import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
42import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
43import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
44import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
45import * as ServerSettings from "./serverSettings.ts";
46import { forkParked, forkParkedFiber } from "./serverActivation.ts";
47import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
48import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
49import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
50import {
51 formatHeadlessServeOutput,
52 formatHostForUrl,
53 isWildcardHost,
54 issueHeadlessServeAccessInfo,
55} from "./startupAccess.ts";
56​
57export class ServerRuntimeStartupError extends Schema.TaggedError<ServerRuntimeStartupError>()(
58 "ServerRuntimeStartupError",
59 {
60 mode: ServerConfig.RuntimeMode,
61 host: Schema.NullOr(Schema.String),
62 port: Schema.Number,
63 cause: Schema.Defect(),
64 },
65) {
66 override get message(): string {
67 return "Server runtime startup failed before command readiness.";
68 }
70​
71export class ServerRuntimeStartup extends Context.Service<
72 ServerRuntimeStartup,
73 {
74 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
75 readonly markHttpListening: Effect.Effect<void>;
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>;
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>;
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 const enqueueCommand = Effect.fn("serverRuntimeStartup.enqueueCommand")(function* <A, E>(
113 effect: Effect.Effect<A, E>,
114 ): Effect.fn.Return<A, E | ServerRuntimeStartupError> {
115 const readinessState = yield* Ref.get(commandReadinessState);
116 if (readinessState === "ready") {
117 return yield* effect;
118 }
119 if (readinessState !== "pending") {
120 return yield* readinessState;
121 }
122​
123 const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
124 yield* Queue.offer(commandQueue, {
125 run: Deferred.await(commandReady).pipe(
126 Effect.flatMap(() => effect),
127 Effect.exit,
128 Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
129 ),
130 });
131 return yield* Deferred.await(result);
132 });
133​
134 return {
135 awaitCommandReady: Deferred.await(commandReady),
136 signalCommandReady: Effect.gen(function* () {
137 yield* Ref.set(commandReadinessState, "ready");
138 yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
139 }),
140 failCommandReady: Effect.fn("serverRuntimeStartup.failCommandReady")(function* (error) {
141 yield* Ref.set(commandReadinessState, error);
142 yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
143 }),
144 enqueueCommand,
145 } satisfies CommandGate;
146});
147​
148const recordStartupHeartbeat = Effect.gen(function* () {
149 const analytics = yield* AnalyticsService.AnalyticsService;
150 const projects = yield* ProjectService.ProjectService;
151 const threads = yield* ThreadManagement.ThreadManagementService;
152​
153 const { threadCount, projectCount } = yield* Effect.all({
154 projects: projects.snapshot,
155 threads: threads.getShellSnapshot(),
156 }).pipe(
157 Effect.map(({ projects: projectSnapshot, threads: shellSnapshot }) => ({
158 projectCount: projectSnapshot.projects.length,
159 threadCount: shellSnapshot.threads.length + shellSnapshot.archivedThreads.length,
160 })),
161 Effect.catch((cause) =>
162 Effect.logWarning("failed to gather V2 startup counts for telemetry", {
163 cause,
164 }).pipe(
165 Effect.as({
166 threadCount: 0,
167 projectCount: 0,
168 }),
169 ),
170 ),
171 );
172​
173 yield* analytics.record("server.boot.heartbeat", {
174 threadCount,
175 projectCount,
176 });
177});
178​
179export const getAutoBootstrapThreadModelSelection = (): ModelSelection => ({
180 instanceId: ProviderInstanceId.make("codex"),
181 model: DEFAULT_MODEL,
182});
183​
184interface AutoBootstrapWelcomeTargets {
185 readonly bootstrapProjectId?: ProjectId;
186 readonly bootstrapThreadId?: ThreadId;
188​
189export const autoPullProjects = Effect.fn("autoPullProjects")(function* (
190 projects: ReadonlyArray<Pick<Project, "id" | "workspaceRoot" | "autoPull">>,
191 settings = DEFAULT_SERVER_SETTINGS,
192) {
193 const git = yield* GitVcsDriver.GitVcsDriver;
194 const workspaceRoots = [
195 ...new Set(
196 projects
197 .filter((project) => resolveProjectSettings(settings, project.id).settings.defaultAutoPull)
198 .map((project) => project.workspaceRoot),
199 ),
200 ];
201​
202 yield* Effect.forEach(
203 workspaceRoots,
204 (cwd) =>
205 Effect.gen(function* () {
206 const status = yield* git.statusDetails(cwd);
207 if (
208 !status.isRepo ||
209 !status.isDefaultBranch ||
210 !status.hasUpstream ||
211 status.hasWorkingTreeChanges ||
212 status.aheadCount > 0
213 ) {
214 yield* Effect.logDebug("Skipped automatic project pull", {
215 cwd,
216 reason: !status.isRepo
217 ? "not-a-repository"
218 : !status.isDefaultBranch
219 ? "not-on-default-branch"
220 : !status.hasUpstream
221 ? "no-upstream"
222 : status.hasWorkingTreeChanges
223 ? "working-tree-changes"
224 : "local-commits",
225 });
226 return;
227 }
228​
229 if (status.behindCount <= 0) return;
230​
231 const result = yield* git.pullCurrentBranch(cwd);
232 yield* Effect.logDebug("Automatic project pull completed", {
233 cwd,
234 status: result.status,
235 refName: result.refName,
236 });
237 }).pipe(
238 Effect.catch((cause) =>
239 Effect.logWarning("Automatic project pull failed", {
240 cwd,
241 cause,
242 }),
243 ),
244 ),
245 { concurrency: 4, discard: true },
246 );
247});
248​
249export const resolveWelcomeBase = Effect.gen(function* () {
250 const serverConfig = yield* ServerConfig.ServerConfig;
251 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
252 const projectName = segments[segments.length - 1] ?? "project";
253​
254 return {
255 cwd: serverConfig.cwd,
256 projectName,
257 } as const;
258});
259​
260const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
261 const crypto = yield* Crypto.Crypto;
262 const randomUUID = crypto.randomUUIDv4();
263 const serverConfig = yield* ServerConfig.ServerConfig;
264 const projects = yield* ProjectService.ProjectService;
265 const threads = yield* ThreadManagement.ThreadManagementService;
266 const threadLaunch = yield* ThreadLaunch.ThreadLaunchService;
267 const path = yield* Path.Path;
268​
269 let bootstrapProjectId: ProjectId | undefined;
270 let bootstrapThreadId: ThreadId | undefined;
271​
272 if (serverConfig.autoBootstrapProjectFromCwd) {
273 const threadModelSelection = getAutoBootstrapThreadModelSelection();
274 const { project } = yield* projects.bootstrap({
275 commandId: CommandId.make(yield* randomUUID),
276 projectId: ProjectId.make(yield* randomUUID),
277 title: path.basename(serverConfig.cwd) || "project",
278 workspaceRoot: serverConfig.cwd,
279 });
280 const shell = yield* threads.getShellSnapshot();
281 const existingThread = shell.threads.find(
282 (thread) =>
283 thread.projectId === project.id && thread.lineage.relationshipToParent !== "subagent",
284 );
285 if (existingThread === undefined) {
286 const serverSettings = yield* ServerSettings.ServerSettingsService;
287 const settings = yield* serverSettings.getSettings;
288 const launched = yield* threadLaunch
289 .launch({
290 commandId: CommandId.make(yield* randomUUID),
291 projectId: project.id,
292 title: "New thread",
293 modelSelection:
294 resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ??
295 threadModelSelection,
296 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
297 runtimeMode: resolveProjectSettings(settings, project.id, project).settings
298 .defaultRuntimeMode,
299 workspaceStrategy: { type: "root" },
300 createdBy: "system",
301 creationSource: "server",
302 })
303 .pipe(
304 // The bootstrap thread is optional; its launch must not prevent opening the app.
305 Effect.catchTags({
306 ThreadManagementProviderInstanceDisabledError: (error) =>
307 Effect.logInfo("Skipped bootstrap thread because its provider instance is disabled", {
308 projectId: project.id,
309 instanceId: error.instanceId,
310 }).pipe(Effect.as(undefined)),
311 ThreadLaunchError: (error) =>
312 Effect.logWarning("Failed to launch bootstrap thread", {
313 projectId: project.id,
314 operation: error.operation,
315 }).pipe(Effect.as(undefined)),
316 }),
317 );
318 bootstrapProjectId = project.id;
319 bootstrapThreadId = launched?.threadId;
320 } else {
321 bootstrapProjectId = project.id;
322 bootstrapThreadId = existingThread.id;
323 }
324 }
325​
326 return {
327 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
328 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
329 } satisfies AutoBootstrapWelcomeTargets;
330});
331​
332const resolveStartupBrowserTarget = Effect.gen(function* () {
333 const serverConfig = yield* ServerConfig.ServerConfig;
334 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
335 const localUrl = `http://localhost:${serverConfig.port}`;
336 const bindUrl =
337 serverConfig.host && !isWildcardHost(serverConfig.host)
338 ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
339 : localUrl;
340 const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
341 return serverConfig.mode === "desktop"
342 ? baseTarget
343 : yield* serverAuth.issueStartupPairingUrl(baseTarget);
344});
345​
346/**
347 * Prints the startup pairing URL to stdout, where `t3` users and the dev runner
348 * read it. The URL carries a one-time admin token, so it skips the logger: log
349 * records also land in the trace file and any configured OTLP collector.
350 */
351export const announceStartupPairingUrl = (pairingUrl: string) =>
352 Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe(
353 // Indented to match the annotation line the pretty logger printed before.
354 Effect.andThen(Console.log(` pairingUrl: ${pairingUrl}`)),
355 );
356​
357// No URL here: the browser target carries the pairing token, which
358// announceStartupPairingUrl has already printed to stdout.
359export const logBrowserAutoOpenUnavailable = Effect.logInfo("browser auto-open unavailable", {
360 hint: "Open the pairing URL above in your browser.",
361});
362​
363export const maybeOpenBrowser = Effect.fn("serverRuntimeStartup.maybeOpenBrowser")(function* (
364 target: string,
365) {
366 const serverConfig = yield* ServerConfig.ServerConfig;
367 if (serverConfig.noBrowser) {
368 return;
369 }
370 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
371​
372 yield* externalLauncher.launchBrowser(target).pipe(
373 // The target carries the pairing token, and a failed launch records its
374 // command line on the span, so this call stays out of traces.
375 Effect.withTracerEnabled(false),
376 Effect.catch(() => logBrowserAutoOpenUnavailable),
377 );
378});
379​
380const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
381 effect.pipe(
382 // Attributes on the span itself, not annotateSpans: an annotation follows
383 // every fiber forked inside the phase, such as the effect worker, for the
384 // life of the server.
385 Effect.withSpan(`server.startup.${phase}`, { attributes: { "startup.phase": phase } }),
386 );
387​
388interface StartupOptions {
389 readonly activate?: Effect.Effect<void>;
390 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
391 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
393​
394export const startEffectWorkerWithRelay = Effect.fn(
395 "ServerRuntimeStartup.startEffectWorkerWithRelay",
396)(function* <WorkerContext, RelayContext>(input: {
397 readonly runWorker: Effect.Effect<void, never, WorkerContext>;
398 readonly startRelay: Effect.Effect<void, never, RelayContext>;
399 readonly workerFiberRef: Ref.Ref<Fiber.Fiber<void, never> | null>;
400}) {
401 const workerFiber = yield* forkParkedFiber(input.runWorker);
402 yield* Ref.set(input.workerFiberRef, workerFiber);
403 yield* input.startRelay.pipe(
404 Effect.onExit((exit) => {
405 if (Exit.isSuccess(exit)) {
406 return Effect.void;
407 }
408 return Ref.getAndSet(input.workerFiberRef, null).pipe(
409 Effect.flatMap((ownedWorkerFiber) =>
410 ownedWorkerFiber === null
411 ? Effect.void
412 : Fiber.interrupt(ownedWorkerFiber).pipe(Effect.asVoid),
413 ),
414 );
415 }),
416 );
417});
418​
419export const runOrderedV2StartupPhases = Effect.fn(
420 "serverRuntimeStartup.runOrderedV2StartupPhases",
421)(function* <
422 Import,
423 Recovery,
424 Bootstrap,
425 ImportError,
426 RecoveryError,
427 DelegationError,
428 WorkerError,
429 BootstrapError,
430 ImportContext,
431 RecoveryContext,
432 DelegationContext,
433 WorkerContext,
434 BootstrapContext,
435>(input: {
436 readonly importLegacyShells: Effect.Effect<Import, ImportError, ImportContext>;
437 readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
438 readonly recoverDelegatedTasks: Effect.Effect<void, DelegationError, DelegationContext>;
439 readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
440 readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
441}) {
442 yield* input.importLegacyShells;
443 const recovery = yield* input.recover;
444 yield* input.recoverDelegatedTasks;
445 yield* input.startEffectWorker;
446 const bootstrap = yield* input.autoBootstrap;
447 return { recovery, bootstrap } as const;
448});
449​
450const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: StartupOptions) {
451 const serverConfig = yield* ServerConfig.ServerConfig;
452 const keybindings = yield* Keybindings.Keybindings;
453 const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
454 const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
455 const orchestrator = yield* Orchestrator.OrchestratorV2;
456 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
457 const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
458 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
459 const serverSettings = yield* ServerSettings.ServerSettingsService;
460 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
461 const crypto = yield* Crypto.Crypto;
462 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
463​
464 const commandGate = yield* makeCommandGate;
465 const httpListening = yield* Deferred.make<void>();
466 const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
467​
468 yield* Effect.addFinalizer(() =>
469 Effect.gen(function* () {
470 yield* commandGate.failCommandReady(
471 new ServerRuntimeStartupError({
472 mode: serverConfig.mode,
473 host: serverConfig.host ?? null,
474 port: serverConfig.port,
475 cause: "Server runtime is shutting down.",
476 }),
477 );
478 const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
479 if (workerFiber !== null) {
480 yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
481 }
482 yield* providerRuntimeRecovery.prepareForShutdown.pipe(
483 Effect.ensuring(providerSessions.shutdown),
484 );
485 const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
486 yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
487 }).pipe(
488 Effect.catchCause((cause) =>
489 Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
490 cause: Cause.pretty(cause),
491 }),
492 ),
493 ),
494 );
495​
496 const startup = Effect.gen(function* () {
497 yield* Effect.logDebug("startup phase: starting keybindings runtime");
498 yield* runStartupPhase(
499 "keybindings.start",
500 keybindings.start.pipe(
501 Effect.catch((error) =>
502 Effect.logWarning("failed to start keybindings runtime", {
503 path: error.configPath,
504 detail: error.detail,
505 cause: error.cause,
506 }),
507 ),
508 ),
509 );
510​
511 yield* Effect.logDebug("startup phase: starting server settings runtime");
512 yield* runStartupPhase(
513 "settings.start",
514 serverSettings.start.pipe(
515 Effect.catch((error) =>
516 Effect.logWarning("failed to start server settings runtime", {
517 path: error.settingsPath,
518 operation: error.operation,
519 providerInstanceId: error.providerInstanceId,
520 environmentVariable: error.environmentVariable,
521 cause: error.cause,
522 }),
523 ),
524 ),
525 );
526​
527 const welcomeBase = yield* resolveWelcomeBase;
528 const environment = yield* serverEnvironment.getDescriptor;
529 const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
530 if (legacyMigrationThreadCount > 0) {
531 yield* lifecycleEvents.publish({
532 version: 1,
533 type: "legacyThreadMigration",
534 payload: {
535 status: "running",
536 totalThreadCount: legacyMigrationThreadCount,
537 },
538 });
539 }
540 const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
541 importLegacyShells: runStartupPhase(
542 "orchestration-v2.legacy-v1.import-shells",
543 legacyV1ThreadImporter.reconcileShells.pipe(
544 Effect.tap((summary) =>
545 summary.importedThreadCount === 0
546 ? Effect.void
547 : Effect.logInfo("Imported legacy v1 thread shells", summary),
548 ),
549 ),
550 ),
551 recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
552 recoverDelegatedTasks: runStartupPhase(
553 "orchestration-v2.delegated-tasks.recover",
554 orchestrator.recoverDelegatedTasks,
555 ),
556 startEffectWorker: runStartupPhase(
557 "orchestration-v2.effect-worker.start",
558 startEffectWorkerWithRelay({
559 runWorker: EffectWorker.runDaemon,
560 startRelay: agentAwarenessRelay.start(),
561 workerFiberRef: effectWorkerFiber,
562 }),
563 ),
564 autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
565 ? runStartupPhase(
566 "welcome.autobootstrap",
567 resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),
568 )
569 : Effect.succeed({})
570 ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
571 });
572 yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
573 // Runs after activation: the status check fetches every enabled project's
574 // remote, and awaiting it here held command readiness for that long.
575 yield* runStartupPhase(
576 "projects.auto-pull",
577 Effect.gen(function* () {
578 const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells();
579 const settings = yield* serverSettings.getSettings;
580 yield* autoPullProjects(projects, settings);
581 }),
582 ).pipe(
583 Effect.catch((cause) =>
584 Effect.logWarning("Failed to load projects for automatic pull", { cause }),
585 ),
586 forkParked,
587 );
588​
589 const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
590 Effect.tap((summary) =>
591 summary.importedThreadCount === 0
592 ? Effect.void
593 : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
594 ),
595 );
596 yield* (
597 legacyMigrationThreadCount > 0
598 ? importPendingTranscripts.pipe(
599 Effect.tap(() =>
600 lifecycleEvents.publish({
601 version: 1,
602 type: "legacyThreadMigration",
603 payload: {
604 status: "complete",
605 totalThreadCount: legacyMigrationThreadCount,
606 },
607 }),
608 ),
609 )
610 : importPendingTranscripts
611 ).pipe(forkParked);
612​
613 yield* forkParked(
614 Effect.gen(function* () {
615 yield* Effect.logDebug("startup phase: recording startup heartbeat");
616 yield* recordStartupHeartbeat.pipe(
617 Effect.withSpan("server.startup.heartbeat.record", {
618 attributes: { "startup.phase": "heartbeat.record" },
619 }),
620 Effect.ignoreCause({ log: true }),
621 );
622 if (serverConfig.startupPresentation === "headless") {
623 yield* Effect.logDebug("startup phase: headless access info");
624 const accessInfo = yield* issueHeadlessServeAccessInfo();
625 yield* runStartupPhase(
626 "headless.output",
627 Console.log(formatHeadlessServeOutput(accessInfo)),
628 );
629 } else {
630 yield* Effect.logDebug("startup phase: browser open check");
631 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
632 if (serverConfig.mode !== "desktop") {
633 yield* announceStartupPairingUrl(startupBrowserTarget);
634 }
635 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
636 }
637 }),
638 );
639​
640 yield* Effect.logDebug("startup phase: waiting for http listener");
641 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
642 yield* runStartupPhase("auxiliary-roots.parked", options?.awaitAuxiliaryParked ?? Effect.void);
643​
644 const updateOutcome = yield* launcher.prepareTrial;
645​
646 yield* Effect.logDebug("startup phase: publishing welcome event", {
647 environmentId: environment.environmentId,
648 cwd: welcomeBase.cwd,
649 projectName: welcomeBase.projectName,
650 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
651 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
652 });
653 yield* runStartupPhase(
654 "welcome.publish",
655 lifecycleEvents.publish({
656 version: 1,
657 type: "welcome",
658 payload: {
659 environment,
660 ...welcomeBase,
661 ...bootstrapTargets,
662 },
663 }),
664 );
665​
666 yield* options?.activate ?? Effect.void;
667 yield* Effect.logDebug("Accepting commands");
668 yield* commandGate.signalCommandReady;
669 yield* Effect.logDebug("startup phase: publishing ready event");
670 yield* runStartupPhase(
671 "ready.publish",
672 lifecycleEvents.publish({
673 version: 1,
674 type: "ready",
675 payload: {
676 at: DateTime.formatIso(yield* DateTime.now),
677 environment,
678 ...(updateOutcome === undefined ? {} : { updateOutcome }),
679 },
680 }),
681 );
682 yield* Effect.logDebug("startup phase: complete");
683 yield* flushCompileCache;
684 }).pipe(
685 Effect.withSpan("server.startup", {
686 kind: "server",
687 root: true,
688 attributes: {
689 "server.mode": serverConfig.mode,
690 "server.port": serverConfig.port,
691 "server.host": serverConfig.host ?? "default",
692 },
693 }),
694 );
695​
696 yield* Effect.forkScoped(
697 Effect.exit(startup).pipe(
698 Effect.flatMap((startupExit) => {
699 if (Exit.isSuccess(startupExit)) return Effect.void;
700 const error = new ServerRuntimeStartupError({
701 mode: serverConfig.mode,
702 host: serverConfig.host ?? null,
703 port: serverConfig.port,
704 cause: startupExit.cause,
705 });
706 return Effect.logError("server runtime startup failed", {
707 cause: Cause.pretty(startupExit.cause),
708 }).pipe(
709 Effect.andThen(commandGate.failCommandReady(error)),
710 Effect.andThen(options?.abort?.(error) ?? Effect.void),
711 );
712 }),
713 ),
714 );
715​
716 return {
717 awaitCommandReady: commandGate.awaitCommandReady,
718 markHttpListening: Deferred.succeed(httpListening, undefined),
719 enqueueCommand: commandGate.enqueueCommand,
720 } satisfies ServerRuntimeStartup["Service"];
721});
722​
723export const layerWithOptions = (options?: StartupOptions) =>
724 Layer.effect(ServerRuntimeStartup, make(options));
725​
726const layer = layerWithOptions();