Open History to see the last commit
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 { resolveProjectAutoPull } from "@t3tools/shared/serverSettings";
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 * as Keybindings from "./keybindings.ts";
31import * as ExternalLauncher from "./process/externalLauncher.ts";
32import * as EffectWorker from "./orchestration-v2/EffectWorker.ts";
33import * as LegacyV1ThreadImporter from "./orchestration-v2/LegacyV1ThreadImporter.ts";
34import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts";
35import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
36import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts";
37import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
38import * as ProjectService from "./project/ProjectService.ts";
39import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
40import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
41import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
42import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
43import * as ServerSettings from "./serverSettings.ts";
44import { forkParked, forkParkedFiber } from "./serverActivation.ts";
45import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
46import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
47import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
48import {
49 formatHeadlessServeOutput,
50 formatHostForUrl,
51 isWildcardHost,
52 issueHeadlessServeAccessInfo,
53} from "./startupAccess.ts";
54
55export class ServerRuntimeStartupError extends Schema.TaggedError<ServerRuntimeStartupError>()(
56 "ServerRuntimeStartupError",
57 {
58 mode: ServerConfig.RuntimeMode,
59 host: Schema.NullOr(Schema.String),
60 port: Schema.Number,
61 cause: Schema.Defect(),
62 },
63) {
64 override get message(): string {
65 return "Server runtime startup failed before command readiness.";
66 }
67}
68
69export class ServerRuntimeStartup extends Context.Service<
70 ServerRuntimeStartup,
71 {
72 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
73 readonly markHttpListening: Effect.Effect<void>;
74 readonly enqueueCommand: <A, E>(
75 effect: Effect.Effect<A, E>,
76 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
77 }
78>()("t3/serverRuntimeStartup") {}
79
80interface QueuedCommand {
81 readonly run: Effect.Effect<void, never>;
82}
83
84type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError;
85
86interface CommandGate {
87 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
88 readonly signalCommandReady: Effect.Effect<void>;
89 readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
90 readonly enqueueCommand: <A, E>(
91 effect: Effect.Effect<A, E>,
92 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
93}
94
95const settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>
96 Exit.isSuccess(exit)
97 ? Deferred.succeed(deferred, exit.value)
98 : Deferred.failCause(deferred, exit.cause);
99
100export const makeCommandGate = Effect.gen(function* () {
101 const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
102 const commandQueue = yield* Queue.unbounded<QueuedCommand>();
103 const commandReadinessState = yield* Ref.make<CommandReadinessState>("pending");
104
105 const commandWorker = Effect.forever(
106 Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),
107 );
108 yield* Effect.forkScoped(commandWorker);
109
110 return {
111 awaitCommandReady: Deferred.await(commandReady),
112 signalCommandReady: Effect.gen(function* () {
113 yield* Ref.set(commandReadinessState, "ready");
114 yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
115 }),
116 failCommandReady: (error) =>
117 Effect.gen(function* () {
118 yield* Ref.set(commandReadinessState, error);
119 yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
120 }),
121 enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>
122 Effect.gen(function* () {
123 const readinessState = yield* Ref.get(commandReadinessState);
124 if (readinessState === "ready") {
125 return yield* effect;
126 }
127 if (readinessState !== "pending") {
128 return yield* readinessState;
129 }
130
131 const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
132 yield* Queue.offer(commandQueue, {
133 run: Deferred.await(commandReady).pipe(
134 Effect.flatMap(() => effect),
135 Effect.exit,
136 Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
137 ),
138 });
139 return yield* Deferred.await(result);
140 }),
141 } satisfies CommandGate;
142});
143
144const recordStartupHeartbeat = Effect.gen(function* () {
145 const analytics = yield* AnalyticsService.AnalyticsService;
146 const projects = yield* ProjectService.ProjectService;
147 const threads = yield* ThreadManagement.ThreadManagementService;
148
149 const { threadCount, projectCount } = yield* Effect.all({
150 projects: projects.snapshot,
151 threads: threads.getShellSnapshot(),
152 }).pipe(
153 Effect.map(({ projects: projectSnapshot, threads: shellSnapshot }) => ({
154 projectCount: projectSnapshot.projects.length,
155 threadCount: shellSnapshot.threads.length + shellSnapshot.archivedThreads.length,
156 })),
157 Effect.catch((cause) =>
158 Effect.logWarning("failed to gather V2 startup counts for telemetry", {
159 cause,
160 }).pipe(
161 Effect.as({
162 threadCount: 0,
163 projectCount: 0,
164 }),
165 ),
166 ),
167 );
168
169 yield* analytics.record("server.boot.heartbeat", {
170 threadCount,
171 projectCount,
172 });
173});
174
175export const getAutoBootstrapThreadModelSelection = (): ModelSelection => ({
176 instanceId: ProviderInstanceId.make("codex"),
177 model: DEFAULT_MODEL,
178});
179
180interface AutoBootstrapWelcomeTargets {
181 readonly bootstrapProjectId?: ProjectId;
182 readonly bootstrapThreadId?: ThreadId;
183}
184
185export const autoPullProjects = Effect.fn("autoPullProjects")(function* (
186 projects: ReadonlyArray<Pick<Project, "id" | "workspaceRoot" | "autoPull">>,
187 settings = DEFAULT_SERVER_SETTINGS,
188) {
189 const git = yield* GitVcsDriver.GitVcsDriver;
190 const workspaceRoots = [
191 ...new Set(
192 projects
193 .filter((project) => resolveProjectAutoPull(settings, project.id, project.autoPull))
194 .map((project) => project.workspaceRoot),
195 ),
196 ];
197
198 yield* Effect.forEach(
199 workspaceRoots,
200 (cwd) =>
201 Effect.gen(function* () {
202 const status = yield* git.statusDetails(cwd);
203 if (
204 !status.isRepo ||
205 !status.isDefaultBranch ||
206 !status.hasUpstream ||
207 status.hasWorkingTreeChanges ||
208 status.aheadCount > 0
209 ) {
210 yield* Effect.logDebug("Skipped automatic project pull", {
211 cwd,
212 reason: !status.isRepo
213 ? "not-a-repository"
214 : !status.isDefaultBranch
215 ? "not-on-default-branch"
216 : !status.hasUpstream
217 ? "no-upstream"
218 : status.hasWorkingTreeChanges
219 ? "working-tree-changes"
220 : "local-commits",
221 });
222 return;
223 }
224
225 if (status.behindCount <= 0) return;
226
227 const result = yield* git.pullCurrentBranch(cwd);
228 yield* Effect.logDebug("Automatic project pull completed", {
229 cwd,
230 status: result.status,
231 refName: result.refName,
232 });
233 }).pipe(
234 Effect.catch((cause) =>
235 Effect.logWarning("Automatic project pull failed", {
236 cwd,
237 cause,
238 }),
239 ),
240 ),
241 { concurrency: 4, discard: true },
242 );
243});
244
245export const resolveWelcomeBase = Effect.gen(function* () {
246 const serverConfig = yield* ServerConfig.ServerConfig;
247 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
248 const projectName = segments[segments.length - 1] ?? "project";
249
250 return {
251 cwd: serverConfig.cwd,
252 projectName,
253 } as const;
254});
255
256const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
257 const crypto = yield* Crypto.Crypto;
258 const randomUUID = crypto.randomUUIDv4;
259 const serverConfig = yield* ServerConfig.ServerConfig;
260 const projects = yield* ProjectService.ProjectService;
261 const threads = yield* ThreadManagement.ThreadManagementService;
262 const threadLaunch = yield* ThreadLaunch.ThreadLaunchService;
263 const path = yield* Path.Path;
264
265 let bootstrapProjectId: ProjectId | undefined;
266 let bootstrapThreadId: ThreadId | undefined;
267
268 if (serverConfig.autoBootstrapProjectFromCwd) {
269 // Project creation has no user model choice; only the bootstrap thread
270 // gets an automatic selection, and an explicit project default wins.
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 launched = yield* threadLaunch.launch({
285 commandId: CommandId.make(yield* randomUUID),
286 projectId: project.id,
287 title: "New thread",
288 modelSelection: project.defaultModelSelection ?? threadModelSelection,
289 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
290 runtimeMode: "full-access",
291 workspaceStrategy: { type: "root" },
292 createdBy: "system",
293 creationSource: "server",
294 });
295 bootstrapProjectId = project.id;
296 bootstrapThreadId = launched.threadId;
297 } else {
298 bootstrapProjectId = project.id;
299 bootstrapThreadId = existingThread.id;
300 }
301 }
302
303 return {
304 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
305 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
306 } satisfies AutoBootstrapWelcomeTargets;
307});
308
309const resolveStartupBrowserTarget = Effect.gen(function* () {
310 const serverConfig = yield* ServerConfig.ServerConfig;
311 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
312 const localUrl = `http://localhost:${serverConfig.port}`;
313 const bindUrl =
314 serverConfig.host && !isWildcardHost(serverConfig.host)
315 ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
316 : localUrl;
317 const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
318 return yield* Effect.succeed(serverConfig.mode === "desktop" ? baseTarget : undefined).pipe(
319 Effect.flatMap((target) =>
320 target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget),
321 ),
322 );
323});
324
325const maybeOpenBrowser = (target: string) =>
326 Effect.gen(function* () {
327 const serverConfig = yield* ServerConfig.ServerConfig;
328 if (serverConfig.noBrowser) {
329 return;
330 }
331 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
332
333 yield* externalLauncher.launchBrowser(target).pipe(
334 Effect.catch(() =>
335 Effect.logInfo("browser auto-open unavailable", {
336 hint: `Open ${target} in your browser.`,
337 }),
338 ),
339 );
340 });
341
342const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
343 effect.pipe(
344 Effect.annotateSpans({ "startup.phase": phase }),
345 Effect.withSpan(`server.startup.${phase}`),
346 );
347
348interface StartupOptions {
349 readonly activate?: Effect.Effect<void>;
350 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
351 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
352}
353
354export const startEffectWorkerWithRelay = Effect.fn(
355 "ServerRuntimeStartup.startEffectWorkerWithRelay",
356)(function* <WorkerContext, RelayContext>(input: {
357 readonly runWorker: Effect.Effect<void, never, WorkerContext>;
358 readonly startRelay: Effect.Effect<void, never, RelayContext>;
359 readonly workerFiberRef: Ref.Ref<Fiber.Fiber<void, never> | null>;
360}) {
361 const workerFiber = yield* forkParkedFiber(input.runWorker);
362 yield* Ref.set(input.workerFiberRef, workerFiber);
363 yield* input.startRelay.pipe(
364 Effect.onExit((exit) => {
365 if (Exit.isSuccess(exit)) {
366 return Effect.void;
367 }
368 return Ref.getAndSet(input.workerFiberRef, null).pipe(
369 Effect.flatMap((ownedWorkerFiber) =>
370 ownedWorkerFiber === null
371 ? Effect.void
372 : Fiber.interrupt(ownedWorkerFiber).pipe(Effect.asVoid),
373 ),
374 );
375 }),
376 );
377});
378
379export function runOrderedV2StartupPhases<
380 Import,
381 Recovery,
382 Bootstrap,
383 ImportError,
384 RecoveryError,
385 WorkerError,
386 BootstrapError,
387 ImportContext,
388 RecoveryContext,
389 WorkerContext,
390 BootstrapContext,
391>(input: {
392 readonly importLegacyShells: Effect.Effect<Import, ImportError, ImportContext>;
393 readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
394 readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
395 readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
396}) {
397 return Effect.gen(function* () {
398 yield* input.importLegacyShells;
399 const recovery = yield* input.recover;
400 yield* input.startEffectWorker;
401 const bootstrap = yield* input.autoBootstrap;
402 return { recovery, bootstrap } as const;
403 });
404}
405
406const make = (options?: StartupOptions) =>
407 Effect.gen(function* () {
408 const serverConfig = yield* ServerConfig.ServerConfig;
409 const keybindings = yield* Keybindings.Keybindings;
410 const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
411 const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
412 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
413 const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
414 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
415 const serverSettings = yield* ServerSettings.ServerSettingsService;
416 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
417 const crypto = yield* Crypto.Crypto;
418 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
419
420 const commandGate = yield* makeCommandGate;
421 const httpListening = yield* Deferred.make<void>();
422 const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
423
424 yield* Effect.addFinalizer(() =>
425 Effect.gen(function* () {
426 yield* commandGate.failCommandReady(
427 new ServerRuntimeStartupError({
428 mode: serverConfig.mode,
429 host: serverConfig.host ?? null,
430 port: serverConfig.port,
431 cause: "Server runtime is shutting down.",
432 }),
433 );
434 const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
435 if (workerFiber !== null) {
436 yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
437 }
438 yield* providerRuntimeRecovery.prepareForShutdown.pipe(
439 Effect.ensuring(providerSessions.shutdown),
440 );
441 const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
442 yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
443 }).pipe(
444 Effect.catchCause((cause) =>
445 Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
446 cause: Cause.pretty(cause),
447 }),
448 ),
449 ),
450 );
451
452 const startup = Effect.gen(function* () {
453 yield* Effect.logDebug("startup phase: starting keybindings runtime");
454 yield* runStartupPhase(
455 "keybindings.start",
456 keybindings.start.pipe(
457 Effect.catch((error) =>
458 Effect.logWarning("failed to start keybindings runtime", {
459 path: error.configPath,
460 detail: error.detail,
461 cause: error.cause,
462 }),
463 ),
464 ),
465 );
466
467 yield* Effect.logDebug("startup phase: starting server settings runtime");
468 yield* runStartupPhase(
469 "settings.start",
470 serverSettings.start.pipe(
471 Effect.catch((error) =>
472 Effect.logWarning("failed to start server settings runtime", {
473 path: error.settingsPath,
474 operation: error.operation,
475 providerInstanceId: error.providerInstanceId,
476 environmentVariable: error.environmentVariable,
477 cause: error.cause,
478 }),
479 ),
480 ),
481 );
482
483 const welcomeBase = yield* resolveWelcomeBase;
484 const environment = yield* serverEnvironment.getDescriptor;
485 const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
486 if (legacyMigrationThreadCount > 0) {
487 yield* lifecycleEvents.publish({
488 version: 1,
489 type: "legacyThreadMigration",
490 payload: {
491 status: "running",
492 totalThreadCount: legacyMigrationThreadCount,
493 },
494 });
495 }
496 const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
497 importLegacyShells: runStartupPhase(
498 "orchestration-v2.legacy-v1.import-shells",
499 legacyV1ThreadImporter.reconcileShells.pipe(
500 Effect.tap((summary) =>
501 summary.importedThreadCount === 0
502 ? Effect.void
503 : Effect.logInfo("Imported legacy v1 thread shells", summary),
504 ),
505 ),
506 ),
507 recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
508 startEffectWorker: runStartupPhase(
509 "orchestration-v2.effect-worker.start",
510 startEffectWorkerWithRelay({
511 runWorker: EffectWorker.runDaemon,
512 startRelay: agentAwarenessRelay.start(),
513 workerFiberRef: effectWorkerFiber,
514 }),
515 ),
516 autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
517 ? runStartupPhase(
518 "welcome.autobootstrap",
519 resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),
520 )
521 : Effect.succeed({})
522 ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
523 });
524 yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
525 yield* runStartupPhase(
526 "projects.auto-pull",
527 Effect.gen(function* () {
528 const snapshots = yield* ProjectionSnapshotQuery;
529 const projects = yield* snapshots.getProjectShellsWithoutEnrichment();
530 const settings = yield* serverSettings.getSettings;
531 yield* autoPullProjects(projects, settings);
532 }),
533 );
534
535 const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
536 Effect.tap((summary) =>
537 summary.importedThreadCount === 0
538 ? Effect.void
539 : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
540 ),
541 );
542 yield* (
543 legacyMigrationThreadCount > 0
544 ? importPendingTranscripts.pipe(
545 Effect.tap(() =>
546 lifecycleEvents.publish({
547 version: 1,
548 type: "legacyThreadMigration",
549 payload: {
550 status: "complete",
551 totalThreadCount: legacyMigrationThreadCount,
552 },
553 }),
554 ),
555 )
556 : importPendingTranscripts
557 ).pipe(forkParked);
558
559 yield* forkParked(
560 Effect.gen(function* () {
561 yield* Effect.logDebug("startup phase: recording startup heartbeat");
562 yield* recordStartupHeartbeat.pipe(
563 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
564 Effect.withSpan("server.startup.heartbeat.record"),
565 Effect.ignoreCause({ log: true }),
566 );
567 if (serverConfig.startupPresentation === "headless") {
568 yield* Effect.logDebug("startup phase: headless access info");
569 const accessInfo = yield* issueHeadlessServeAccessInfo();
570 yield* runStartupPhase(
571 "headless.output",
572 Console.log(formatHeadlessServeOutput(accessInfo)),
573 );
574 } else {
575 yield* Effect.logDebug("startup phase: browser open check");
576 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
577 if (serverConfig.mode !== "desktop") {
578 yield* Effect.logInfo(
579 "Authentication required. Open T3 Code using the pairing URL.",
580 ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
581 }
582 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
583 }
584 }),
585 );
586
587 yield* Effect.logDebug("startup phase: waiting for http listener");
588 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
589 yield* runStartupPhase(
590 "auxiliary-roots.parked",
591 options?.awaitAuxiliaryParked ?? Effect.void,
592 );
593
594 const updateOutcome = yield* launcher.prepareTrial;
595
596 yield* Effect.logDebug("startup phase: publishing welcome event", {
597 environmentId: environment.environmentId,
598 cwd: welcomeBase.cwd,
599 projectName: welcomeBase.projectName,
600 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
601 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
602 });
603 yield* runStartupPhase(
604 "welcome.publish",
605 lifecycleEvents.publish({
606 version: 1,
607 type: "welcome",
608 payload: {
609 environment,
610 ...welcomeBase,
611 ...bootstrapTargets,
612 },
613 }),
614 );
615
616 yield* options?.activate ?? Effect.void;
617 yield* Effect.logDebug("Accepting commands");
618 yield* commandGate.signalCommandReady;
619 yield* Effect.logDebug("startup phase: publishing ready event");
620 yield* runStartupPhase(
621 "ready.publish",
622 lifecycleEvents.publish({
623 version: 1,
624 type: "ready",
625 payload: {
626 at: DateTime.formatIso(yield* DateTime.now),
627 environment,
628 ...(updateOutcome === undefined ? {} : { updateOutcome }),
629 },
630 }),
631 );
632 yield* Effect.logDebug("startup phase: complete");
633 }).pipe(
634 Effect.annotateSpans({
635 "server.mode": serverConfig.mode,
636 "server.port": serverConfig.port,
637 "server.host": serverConfig.host ?? "default",
638 }),
639 Effect.withSpan("server.startup", { kind: "server", root: true }),
640 );
641
642 yield* Effect.forkScoped(
643 Effect.exit(startup).pipe(
644 Effect.flatMap((startupExit) => {
645 if (Exit.isSuccess(startupExit)) return Effect.void;
646 const error = new ServerRuntimeStartupError({
647 mode: serverConfig.mode,
648 host: serverConfig.host ?? null,
649 port: serverConfig.port,
650 cause: startupExit.cause,
651 });
652 return Effect.logError("server runtime startup failed", {
653 cause: Cause.pretty(startupExit.cause),
654 }).pipe(
655 Effect.andThen(commandGate.failCommandReady(error)),
656 Effect.andThen(options?.abort?.(error) ?? Effect.void),
657 );
658 }),
659 ),
660 );
661
662 return {
663 awaitCommandReady: commandGate.awaitCommandReady,
664 markHttpListening: Deferred.succeed(httpListening, undefined),
665 enqueueCommand: commandGate.enqueueCommand,
666 } satisfies ServerRuntimeStartup["Service"];
667 });
668
669export const layerWithOptions = (options?: StartupOptions) =>
670 Layer.effect(ServerRuntimeStartup, make(options));
671
672const layer = layerWithOptions();