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 { 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 * 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) => resolveProjectSettings(settings, project.id).settings.defaultAutoPull)
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 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
328const maybeOpenBrowser = (target: string) =>
329 Effect.gen(function* () {
330 const serverConfig = yield* ServerConfig.ServerConfig;
331 if (serverConfig.noBrowser) {
332 return;
333 }
334 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
335
336 yield* externalLauncher.launchBrowser(target).pipe(
337 Effect.catch(() =>
338 Effect.logInfo("browser auto-open unavailable", {
339 hint: `Open ${target} in your browser.`,
340 }),
341 ),
342 );
343 });
344
345const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
346 effect.pipe(
347 Effect.annotateSpans({ "startup.phase": phase }),
348 Effect.withSpan(`server.startup.${phase}`),
349 );
350
351interface StartupOptions {
352 readonly activate?: Effect.Effect<void>;
353 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
354 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
355}
356
357export const startEffectWorkerWithRelay = Effect.fn(
358 "ServerRuntimeStartup.startEffectWorkerWithRelay",
359)(function* <WorkerContext, RelayContext>(input: {
360 readonly runWorker: Effect.Effect<void, never, WorkerContext>;
361 readonly startRelay: Effect.Effect<void, never, RelayContext>;
362 readonly workerFiberRef: Ref.Ref<Fiber.Fiber<void, never> | null>;
363}) {
364 const workerFiber = yield* forkParkedFiber(input.runWorker);
365 yield* Ref.set(input.workerFiberRef, workerFiber);
366 yield* input.startRelay.pipe(
367 Effect.onExit((exit) => {
368 if (Exit.isSuccess(exit)) {
369 return Effect.void;
370 }
371 return Ref.getAndSet(input.workerFiberRef, null).pipe(
372 Effect.flatMap((ownedWorkerFiber) =>
373 ownedWorkerFiber === null
374 ? Effect.void
375 : Fiber.interrupt(ownedWorkerFiber).pipe(Effect.asVoid),
376 ),
377 );
378 }),
379 );
380});
381
382export function runOrderedV2StartupPhases<
383 Import,
384 Recovery,
385 Bootstrap,
386 ImportError,
387 RecoveryError,
388 WorkerError,
389 BootstrapError,
390 ImportContext,
391 RecoveryContext,
392 WorkerContext,
393 BootstrapContext,
394>(input: {
395 readonly importLegacyShells: Effect.Effect<Import, ImportError, ImportContext>;
396 readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
397 readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
398 readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
399}) {
400 return Effect.gen(function* () {
401 yield* input.importLegacyShells;
402 const recovery = yield* input.recover;
403 yield* input.startEffectWorker;
404 const bootstrap = yield* input.autoBootstrap;
405 return { recovery, bootstrap } as const;
406 });
407}
408
409const make = (options?: StartupOptions) =>
410 Effect.gen(function* () {
411 const serverConfig = yield* ServerConfig.ServerConfig;
412 const keybindings = yield* Keybindings.Keybindings;
413 const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
414 const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
415 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
416 const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
417 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
418 const serverSettings = yield* ServerSettings.ServerSettingsService;
419 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
420 const crypto = yield* Crypto.Crypto;
421 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
422
423 const commandGate = yield* makeCommandGate;
424 const httpListening = yield* Deferred.make<void>();
425 const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
426
427 yield* Effect.addFinalizer(() =>
428 Effect.gen(function* () {
429 yield* commandGate.failCommandReady(
430 new ServerRuntimeStartupError({
431 mode: serverConfig.mode,
432 host: serverConfig.host ?? null,
433 port: serverConfig.port,
434 cause: "Server runtime is shutting down.",
435 }),
436 );
437 const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
438 if (workerFiber !== null) {
439 yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
440 }
441 yield* providerRuntimeRecovery.prepareForShutdown.pipe(
442 Effect.ensuring(providerSessions.shutdown),
443 );
444 const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
445 yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
446 }).pipe(
447 Effect.catchCause((cause) =>
448 Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
449 cause: Cause.pretty(cause),
450 }),
451 ),
452 ),
453 );
454
455 const startup = Effect.gen(function* () {
456 yield* Effect.logDebug("startup phase: starting keybindings runtime");
457 yield* runStartupPhase(
458 "keybindings.start",
459 keybindings.start.pipe(
460 Effect.catch((error) =>
461 Effect.logWarning("failed to start keybindings runtime", {
462 path: error.configPath,
463 detail: error.detail,
464 cause: error.cause,
465 }),
466 ),
467 ),
468 );
469
470 yield* Effect.logDebug("startup phase: starting server settings runtime");
471 yield* runStartupPhase(
472 "settings.start",
473 serverSettings.start.pipe(
474 Effect.catch((error) =>
475 Effect.logWarning("failed to start server settings runtime", {
476 path: error.settingsPath,
477 operation: error.operation,
478 providerInstanceId: error.providerInstanceId,
479 environmentVariable: error.environmentVariable,
480 cause: error.cause,
481 }),
482 ),
483 ),
484 );
485
486 const welcomeBase = yield* resolveWelcomeBase;
487 const environment = yield* serverEnvironment.getDescriptor;
488 const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
489 if (legacyMigrationThreadCount > 0) {
490 yield* lifecycleEvents.publish({
491 version: 1,
492 type: "legacyThreadMigration",
493 payload: {
494 status: "running",
495 totalThreadCount: legacyMigrationThreadCount,
496 },
497 });
498 }
499 const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
500 importLegacyShells: runStartupPhase(
501 "orchestration-v2.legacy-v1.import-shells",
502 legacyV1ThreadImporter.reconcileShells.pipe(
503 Effect.tap((summary) =>
504 summary.importedThreadCount === 0
505 ? Effect.void
506 : Effect.logInfo("Imported legacy v1 thread shells", summary),
507 ),
508 ),
509 ),
510 recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
511 startEffectWorker: runStartupPhase(
512 "orchestration-v2.effect-worker.start",
513 startEffectWorkerWithRelay({
514 runWorker: EffectWorker.runDaemon,
515 startRelay: agentAwarenessRelay.start(),
516 workerFiberRef: effectWorkerFiber,
517 }),
518 ),
519 autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
520 ? runStartupPhase(
521 "welcome.autobootstrap",
522 resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),
523 )
524 : Effect.succeed({})
525 ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
526 });
527 yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
528 yield* runStartupPhase(
529 "projects.auto-pull",
530 Effect.gen(function* () {
531 const snapshots = yield* ProjectionSnapshotQuery;
532 const projects = yield* snapshots.getProjectShellsWithoutEnrichment();
533 const settings = yield* serverSettings.getSettings;
534 yield* autoPullProjects(projects, settings);
535 }),
536 );
537
538 const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
539 Effect.tap((summary) =>
540 summary.importedThreadCount === 0
541 ? Effect.void
542 : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
543 ),
544 );
545 yield* (
546 legacyMigrationThreadCount > 0
547 ? importPendingTranscripts.pipe(
548 Effect.tap(() =>
549 lifecycleEvents.publish({
550 version: 1,
551 type: "legacyThreadMigration",
552 payload: {
553 status: "complete",
554 totalThreadCount: legacyMigrationThreadCount,
555 },
556 }),
557 ),
558 )
559 : importPendingTranscripts
560 ).pipe(forkParked);
561
562 yield* forkParked(
563 Effect.gen(function* () {
564 yield* Effect.logDebug("startup phase: recording startup heartbeat");
565 yield* recordStartupHeartbeat.pipe(
566 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
567 Effect.withSpan("server.startup.heartbeat.record"),
568 Effect.ignoreCause({ log: true }),
569 );
570 if (serverConfig.startupPresentation === "headless") {
571 yield* Effect.logDebug("startup phase: headless access info");
572 const accessInfo = yield* issueHeadlessServeAccessInfo();
573 yield* runStartupPhase(
574 "headless.output",
575 Console.log(formatHeadlessServeOutput(accessInfo)),
576 );
577 } else {
578 yield* Effect.logDebug("startup phase: browser open check");
579 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
580 if (serverConfig.mode !== "desktop") {
581 yield* Effect.logInfo(
582 "Authentication required. Open T3 Code using the pairing URL.",
583 ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
584 }
585 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
586 }
587 }),
588 );
589
590 yield* Effect.logDebug("startup phase: waiting for http listener");
591 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
592 yield* runStartupPhase(
593 "auxiliary-roots.parked",
594 options?.awaitAuxiliaryParked ?? Effect.void,
595 );
596
597 const updateOutcome = yield* launcher.prepareTrial;
598
599 yield* Effect.logDebug("startup phase: publishing welcome event", {
600 environmentId: environment.environmentId,
601 cwd: welcomeBase.cwd,
602 projectName: welcomeBase.projectName,
603 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
604 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
605 });
606 yield* runStartupPhase(
607 "welcome.publish",
608 lifecycleEvents.publish({
609 version: 1,
610 type: "welcome",
611 payload: {
612 environment,
613 ...welcomeBase,
614 ...bootstrapTargets,
615 },
616 }),
617 );
618
619 yield* options?.activate ?? Effect.void;
620 yield* Effect.logDebug("Accepting commands");
621 yield* commandGate.signalCommandReady;
622 yield* Effect.logDebug("startup phase: publishing ready event");
623 yield* runStartupPhase(
624 "ready.publish",
625 lifecycleEvents.publish({
626 version: 1,
627 type: "ready",
628 payload: {
629 at: DateTime.formatIso(yield* DateTime.now),
630 environment,
631 ...(updateOutcome === undefined ? {} : { updateOutcome }),
632 },
633 }),
634 );
635 yield* Effect.logDebug("startup phase: complete");
636 }).pipe(
637 Effect.annotateSpans({
638 "server.mode": serverConfig.mode,
639 "server.port": serverConfig.port,
640 "server.host": serverConfig.host ?? "default",
641 }),
642 Effect.withSpan("server.startup", { kind: "server", root: true }),
643 );
644
645 yield* Effect.forkScoped(
646 Effect.exit(startup).pipe(
647 Effect.flatMap((startupExit) => {
648 if (Exit.isSuccess(startupExit)) return Effect.void;
649 const error = new ServerRuntimeStartupError({
650 mode: serverConfig.mode,
651 host: serverConfig.host ?? null,
652 port: serverConfig.port,
653 cause: startupExit.cause,
654 });
655 return Effect.logError("server runtime startup failed", {
656 cause: Cause.pretty(startupExit.cause),
657 }).pipe(
658 Effect.andThen(commandGate.failCommandReady(error)),
659 Effect.andThen(options?.abort?.(error) ?? Effect.void),
660 );
661 }),
662 ),
663 );
664
665 return {
666 awaitCommandReady: commandGate.awaitCommandReady,
667 markHttpListening: Deferred.succeed(httpListening, undefined),
668 enqueueCommand: commandGate.enqueueCommand,
669 } satisfies ServerRuntimeStartup["Service"];
670 });
671
672export const layerWithOptions = (options?: StartupOptions) =>
673 Layer.effect(ServerRuntimeStartup, make(options));
674
675const layer = layerWithOptions();