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

serverRuntimeStartup.ts

720 lines26.1 KB

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