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

serverRuntimeStartup.ts

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