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

serverRuntimeStartup.ts

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