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

serverRuntimeStartup.ts

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