Open History to see the last commit
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 issueHeadlessServeAccessInfo,
55 resolveLocalOrigin,
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 }
70}
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>;
85}
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>;
96}
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 threadCount: threads.countThreads(),
157 }).pipe(
158 Effect.map(({ projects: projectSnapshot, threadCount }) => ({
159 projectCount: projectSnapshot.projects.length,
160 threadCount,
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;
189}
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 // Startup checks once, so it waits for the fetch rather than reading the old references.
209 const status = yield* git
210 .statusDetails(cwd)
211 .pipe(Effect.provideService(GitVcsDriver.AwaitStatusFetch, true));
212 if (
213 !status.isRepo ||
214 !status.isDefaultBranch ||
215 !status.hasUpstream ||
216 status.hasWorkingTreeChanges ||
217 status.aheadCount > 0
218 ) {
219 yield* Effect.logDebug("Skipped automatic project pull", {
220 cwd,
221 reason: !status.isRepo
222 ? "not-a-repository"
223 : !status.isDefaultBranch
224 ? "not-on-default-branch"
225 : !status.hasUpstream
226 ? "no-upstream"
227 : status.hasWorkingTreeChanges
228 ? "working-tree-changes"
229 : "local-commits",
230 });
231 return;
232 }
233
234 if (status.behindCount <= 0) return;
235
236 const result = yield* git.pullCurrentBranch(cwd);
237 yield* Effect.logDebug("Automatic project pull completed", {
238 cwd,
239 status: result.status,
240 refName: result.refName,
241 });
242 }).pipe(
243 Effect.catch((cause) =>
244 Effect.logWarning("Automatic project pull failed", {
245 cwd,
246 cause,
247 }),
248 ),
249 ),
250 { concurrency: 4, discard: true },
251 );
252});
253
254const resolveWelcomeBase = Effect.gen(function* () {
255 const serverConfig = yield* ServerConfig.ServerConfig;
256 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
257 const projectName = segments[segments.length - 1] ?? "project";
258
259 return {
260 cwd: serverConfig.cwd,
261 projectName,
262 } as const;
263});
264
265const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
266 const random = yield* SecureRandom.SecureRandom;
267 const randomUUID = random.uuidV4();
268 const serverConfig = yield* ServerConfig.ServerConfig;
269 const projects = yield* ProjectService.ProjectService;
270 const threads = yield* ThreadManagement.ThreadManagementService;
271 const threadLaunch = yield* ThreadLaunch.ThreadLaunchService;
272 const path = yield* Path.Path;
273
274 let bootstrapProjectId: ProjectId | undefined;
275 let bootstrapThreadId: ThreadId | undefined;
276
277 if (serverConfig.autoBootstrapProjectFromCwd) {
278 const threadModelSelection = getAutoBootstrapThreadModelSelection();
279 const bootstrapped = yield* projects
280 .bootstrap({
281 commandId: CommandId.make(yield* randomUUID),
282 projectId: ProjectId.make(yield* randomUUID),
283 title: path.basename(serverConfig.cwd) || "project",
284 workspaceRoot: serverConfig.cwd,
285 })
286 .pipe(
287 // A folder the project rules refuse must not stop the server from starting there.
288 Effect.catchTags({
289 ProjectInvalidError: (error) =>
290 Effect.logWarning("Skipped bootstrap project", { detail: error.detail }).pipe(
291 Effect.as(undefined),
292 ),
293 }),
294 );
295 if (bootstrapped === undefined) return {} satisfies AutoBootstrapWelcomeTargets;
296 const { project } = bootstrapped;
297 const existingThread = (yield* threads.listActiveShellIndex()).find(
298 (thread) => thread.projectId === project.id && isListedThreadLineage(thread.lineage),
299 );
300 if (existingThread === undefined) {
301 const serverSettings = yield* ServerSettings.ServerSettingsService;
302 const settings = yield* serverSettings.getSettings;
303 const launched = yield* threadLaunch
304 .launch({
305 commandId: CommandId.make(yield* randomUUID),
306 projectId: project.id,
307 title: "New thread",
308 modelSelection:
309 resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ??
310 threadModelSelection,
311 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
312 runtimeMode: resolveProjectSettings(settings, project.id, project).settings
313 .defaultRuntimeMode,
314 workspaceStrategy: { type: "root" },
315 createdBy: "system",
316 creationSource: "server",
317 })
318 .pipe(
319 // The bootstrap thread is optional; its launch must not prevent opening the app.
320 Effect.catchTags({
321 ThreadManagementProviderInstanceDisabledError: (error) =>
322 Effect.logInfo("Skipped bootstrap thread because its provider instance is disabled", {
323 projectId: project.id,
324 instanceId: error.instanceId,
325 }).pipe(Effect.as(undefined)),
326 ThreadLaunchError: (error) =>
327 Effect.logWarning("Failed to launch bootstrap thread", {
328 projectId: project.id,
329 operation: error.operation,
330 }).pipe(Effect.as(undefined)),
331 }),
332 );
333 bootstrapProjectId = project.id;
334 bootstrapThreadId = launched?.threadId;
335 } else {
336 bootstrapProjectId = project.id;
337 bootstrapThreadId = existingThread.id;
338 }
339 }
340
341 return {
342 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
343 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
344 } satisfies AutoBootstrapWelcomeTargets;
345});
346
347const resolveStartupBrowserTarget = Effect.gen(function* () {
348 const serverConfig = yield* ServerConfig.ServerConfig;
349 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
350 const baseTarget =
351 serverConfig.devUrl?.toString() ?? resolveLocalOrigin(serverConfig.host, serverConfig.port);
352 return serverConfig.mode === "desktop"
353 ? baseTarget
354 : yield* serverAuth.issueStartupPairingUrl(baseTarget);
355});
356
357/** Prints the one-time admin pairing URL to stdout only; logger records reach trace files and collectors. */
358export const announceStartupPairingUrl = (pairingUrl: string) =>
359 Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe(
360 Effect.andThen(Console.log(` pairingUrl: ${pairingUrl}`)),
361 );
362
363// Pairing tokens belong only in announceStartupPairingUrl's stdout output.
364export const logBrowserAutoOpenUnavailable = Effect.logInfo("browser auto-open unavailable", {
365 hint: "Open the pairing URL above in your browser.",
366});
367
368export const maybeOpenBrowser = Effect.fn("serverRuntimeStartup.maybeOpenBrowser")(function* (
369 target: string,
370) {
371 const serverConfig = yield* ServerConfig.ServerConfig;
372 if (serverConfig.noBrowser) {
373 return;
374 }
375 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
376
377 yield* externalLauncher.launchBrowser(target).pipe(
378 // The target carries the pairing token, and a failed launch records its
379 // command line on the span, so this call stays out of traces.
380 Effect.withTracerEnabled(false),
381 Effect.catch(() => logBrowserAutoOpenUnavailable),
382 );
383});
384
385const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
386 effect.pipe(
387 // Use span attributes; annotations would follow long-lived forked fibers for the server's lifetime.
388 Effect.withSpan(`server.startup.${phase}`, { attributes: { "startup.phase": phase } }),
389 );
390
391interface StartupOptions {
392 readonly activate?: Effect.Effect<void>;
393 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
394 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
395}
396
397export const startEffectWorkerWithRelay = Effect.fn(
398 "ServerRuntimeStartup.startEffectWorkerWithRelay",
399)(function* <WorkerContext, RelayContext>(input: {
400 readonly runWorker: Effect.Effect<void, never, WorkerContext>;
401 readonly startRelay: Effect.Effect<void, never, RelayContext>;
402 readonly workerFiberRef: Ref.Ref<Fiber.Fiber<void, never> | null>;
403}) {
404 const workerFiber = yield* forkParkedFiber(input.runWorker);
405 yield* Ref.set(input.workerFiberRef, workerFiber);
406 yield* input.startRelay.pipe(
407 Effect.onExit((exit) => {
408 if (Exit.isSuccess(exit)) {
409 return Effect.void;
410 }
411 return Ref.getAndSet(input.workerFiberRef, null).pipe(
412 Effect.flatMap((ownedWorkerFiber) =>
413 ownedWorkerFiber === null
414 ? Effect.void
415 : Fiber.interrupt(ownedWorkerFiber).pipe(Effect.asVoid),
416 ),
417 );
418 }),
419 );
420});
421
422const runOrderedV2StartupPhases = Effect.fn("serverRuntimeStartup.runOrderedV2StartupPhases")(
423 function* <
424 Import,
425 Recovery,
426 Bootstrap,
427 ImportError,
428 RecoveryError,
429 DelegationError,
430 WorkerError,
431 BootstrapError,
432 ImportContext,
433 RecoveryContext,
434 DelegationContext,
435 WorkerContext,
436 BootstrapContext,
437 >(input: {
438 readonly importLegacyShells: Effect.Effect<Import, ImportError, ImportContext>;
439 readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
440 readonly recoverDelegatedTasks: Effect.Effect<void, DelegationError, DelegationContext>;
441 readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
442 readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
443 }) {
444 yield* input.importLegacyShells;
445 const recovery = yield* input.recover;
446 yield* input.recoverDelegatedTasks;
447 yield* input.startEffectWorker;
448 const bootstrap = yield* input.autoBootstrap;
449 return { recovery, bootstrap } as const;
450 },
451);
452
453const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: StartupOptions) {
454 const serverConfig = yield* ServerConfig.ServerConfig;
455 const keybindings = yield* Keybindings.Keybindings;
456 const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
457 const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
458 const orchestrator = yield* Orchestrator.OrchestratorV2;
459 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
460 const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
461 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
462 const serverSettings = yield* ServerSettings.ServerSettingsService;
463 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
464 const random = yield* SecureRandom.SecureRandom;
465 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
466
467 const commandGate = yield* makeCommandGate;
468 const httpListening = yield* Deferred.make<void>();
469 const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
470
471 yield* Effect.addFinalizer(() =>
472 Effect.gen(function* () {
473 yield* commandGate.failCommandReady(
474 new ServerRuntimeStartupError({
475 mode: serverConfig.mode,
476 host: serverConfig.host ?? null,
477 port: serverConfig.port,
478 cause: "Server runtime is shutting down.",
479 }),
480 );
481 const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
482 if (workerFiber !== null) {
483 yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
484 }
485 yield* providerRuntimeRecovery.prepareForShutdown.pipe(
486 Effect.ensuring(providerSessions.shutdown),
487 );
488 const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
489 yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
490 }).pipe(
491 Effect.withSpan("server.shutdown"),
492 Effect.catchCause((cause) =>
493 Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
494 cause: Cause.pretty(cause),
495 }),
496 ),
497 ),
498 );
499
500 const startup = Effect.gen(function* () {
501 yield* Effect.logDebug("startup phase: starting keybindings runtime");
502 yield* runStartupPhase(
503 "keybindings.start",
504 keybindings.start.pipe(
505 Effect.catch((error) =>
506 Effect.logWarning("failed to start keybindings runtime", {
507 path: error.configPath,
508 detail: error.detail,
509 cause: error.cause,
510 }),
511 ),
512 ),
513 );
514
515 yield* Effect.logDebug("startup phase: starting server settings runtime");
516 yield* runStartupPhase(
517 "settings.start",
518 serverSettings.start.pipe(
519 Effect.catch((error) =>
520 Effect.logWarning("failed to start server settings runtime", {
521 path: error.settingsPath,
522 operation: error.operation,
523 providerInstanceId: error.providerInstanceId,
524 environmentVariable: error.environmentVariable,
525 cause: error.cause,
526 }),
527 ),
528 ),
529 );
530
531 const welcomeBase = yield* resolveWelcomeBase;
532 const environment = yield* serverEnvironment.getDescriptor;
533 const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
534 if (legacyMigrationThreadCount > 0) {
535 yield* lifecycleEvents.publish({
536 version: 1,
537 type: "legacyThreadMigration",
538 payload: {
539 status: "running",
540 totalThreadCount: legacyMigrationThreadCount,
541 },
542 });
543 }
544 const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
545 importLegacyShells: runStartupPhase(
546 "orchestration-v2.legacy-v1.import-shells",
547 legacyV1ThreadImporter.reconcileShells.pipe(
548 Effect.tap((summary) =>
549 summary.importedThreadCount === 0
550 ? Effect.void
551 : Effect.logInfo("Imported legacy v1 thread shells", summary),
552 ),
553 ),
554 ),
555 recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
556 recoverDelegatedTasks: runStartupPhase(
557 "orchestration-v2.delegated-tasks.recover",
558 orchestrator.recoverDelegatedTasks,
559 ),
560 startEffectWorker: runStartupPhase(
561 "orchestration-v2.effect-worker.start",
562 startEffectWorkerWithRelay({
563 runWorker: EffectWorker.runDaemon,
564 startRelay: agentAwarenessRelay.start(),
565 workerFiberRef: effectWorkerFiber,
566 }),
567 ),
568 autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
569 ? runStartupPhase(
570 "welcome.autobootstrap",
571 resolveAutoBootstrapWelcomeTargets.pipe(
572 Effect.provideService(SecureRandom.SecureRandom, random),
573 ),
574 )
575 : Effect.succeed({})
576 ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
577 });
578 yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
579 // Runs after activation: the status check fetches every enabled project's
580 // remote, and awaiting it here held command readiness for that long.
581 yield* runStartupPhase(
582 "projects.auto-pull",
583 Effect.gen(function* () {
584 const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells();
585 const settings = yield* serverSettings.getSettings;
586 yield* autoPullProjects(projects, settings);
587 }),
588 ).pipe(
589 Effect.catch((cause) =>
590 Effect.logWarning("Failed to load projects for automatic pull", { cause }),
591 ),
592 forkParked,
593 );
594
595 const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
596 Effect.tap((summary) =>
597 summary.importedThreadCount === 0
598 ? Effect.void
599 : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
600 ),
601 );
602 yield* (
603 legacyMigrationThreadCount > 0
604 ? importPendingTranscripts.pipe(
605 Effect.tap(() =>
606 lifecycleEvents.publish({
607 version: 1,
608 type: "legacyThreadMigration",
609 payload: {
610 status: "complete",
611 totalThreadCount: legacyMigrationThreadCount,
612 },
613 }),
614 ),
615 )
616 : importPendingTranscripts
617 ).pipe(forkParked);
618
619 yield* forkParked(
620 Effect.gen(function* () {
621 yield* Effect.logDebug("startup phase: recording startup heartbeat");
622 yield* recordStartupHeartbeat.pipe(
623 Effect.withSpan("server.startup.heartbeat.record", {
624 attributes: { "startup.phase": "heartbeat.record" },
625 }),
626 Effect.ignoreCause({ log: true }),
627 );
628 if (serverConfig.startupPresentation === "headless") {
629 yield* Effect.logDebug("startup phase: headless access info");
630 const accessInfo = yield* issueHeadlessServeAccessInfo();
631 yield* runStartupPhase(
632 "headless.output",
633 Console.log(formatHeadlessServeOutput(accessInfo)),
634 );
635 } else {
636 yield* Effect.logDebug("startup phase: browser open check");
637 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
638 if (serverConfig.mode !== "desktop") {
639 yield* announceStartupPairingUrl(startupBrowserTarget);
640 }
641 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
642 }
643 }),
644 );
645
646 yield* Effect.logDebug("startup phase: waiting for http listener");
647 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
648 yield* runStartupPhase("auxiliary-roots.parked", options?.awaitAuxiliaryParked ?? Effect.void);
649
650 const updateOutcome = yield* launcher.prepareTrial({ baseDir: serverConfig.baseDir });
651
652 yield* Effect.logDebug("startup phase: publishing welcome event", {
653 environmentId: environment.environmentId,
654 cwd: welcomeBase.cwd,
655 projectName: welcomeBase.projectName,
656 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
657 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
658 });
659 yield* runStartupPhase(
660 "welcome.publish",
661 lifecycleEvents.publish({
662 version: 1,
663 type: "welcome",
664 payload: {
665 environment,
666 ...welcomeBase,
667 ...bootstrapTargets,
668 },
669 }),
670 );
671
672 yield* options?.activate ?? Effect.void;
673 yield* Effect.logDebug("Accepting commands");
674 yield* commandGate.signalCommandReady;
675 yield* Effect.logDebug("startup phase: publishing ready event");
676 yield* runStartupPhase(
677 "ready.publish",
678 lifecycleEvents.publish({
679 version: 1,
680 type: "ready",
681 payload: {
682 at: DateTime.formatIso(yield* DateTime.now),
683 environment,
684 ...(updateOutcome === undefined ? {} : { updateOutcome }),
685 },
686 }),
687 );
688 yield* Effect.logDebug("startup phase: complete");
689 yield* flushCompileCache;
690 }).pipe(
691 Effect.withSpan("server.startup", {
692 kind: "server",
693 root: true,
694 attributes: {
695 "server.mode": serverConfig.mode,
696 "server.port": serverConfig.port,
697 "server.host": serverConfig.host ?? "default",
698 },
699 }),
700 );
701
702 yield* Effect.forkScoped(
703 Effect.exit(startup).pipe(
704 Effect.flatMap((startupExit) => {
705 if (Exit.isSuccess(startupExit)) return Effect.void;
706 const error = new ServerRuntimeStartupError({
707 mode: serverConfig.mode,
708 host: serverConfig.host ?? null,
709 port: serverConfig.port,
710 cause: startupExit.cause,
711 });
712 return Effect.logError("server runtime startup failed", {
713 cause: Cause.pretty(startupExit.cause),
714 }).pipe(
715 Effect.andThen(commandGate.failCommandReady(error)),
716 Effect.andThen(options?.abort?.(error) ?? Effect.void),
717 );
718 }),
719 ),
720 );
721
722 return {
723 awaitCommandReady: commandGate.awaitCommandReady,
724 markHttpListening: Deferred.succeed(httpListening, undefined),
725 enqueueCommand: commandGate.enqueueCommand,
726 } satisfies ServerRuntimeStartup["Service"];
727});
728
729export const layerWithOptions = (options?: StartupOptions) =>
730 Layer.effect(ServerRuntimeStartup, make(options));