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

serverRuntimeStartup.ts

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