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

serverRuntimeStartup.ts

670 lines25.0 KB

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