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