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 Crypto from "effect/Crypto";
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 }
71}
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>;
86}
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>;
97}
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;
190}
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 crypto = yield* Crypto.Crypto;
265 const randomUUID = crypto.randomUUIDv4();
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>;
385}
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 crypto = yield* Crypto.Crypto;
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.catchCause((cause) =>
482 Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
483 cause: Cause.pretty(cause),
484 }),
485 ),
486 ),
487 );
488
489 const startup = Effect.gen(function* () {
490 yield* Effect.logDebug("startup phase: starting keybindings runtime");
491 yield* runStartupPhase(
492 "keybindings.start",
493 keybindings.start.pipe(
494 Effect.catch((error) =>
495 Effect.logWarning("failed to start keybindings runtime", {
496 path: error.configPath,
497 detail: error.detail,
498 cause: error.cause,
499 }),
500 ),
501 ),
502 );
503
504 yield* Effect.logDebug("startup phase: starting server settings runtime");
505 yield* runStartupPhase(
506 "settings.start",
507 serverSettings.start.pipe(
508 Effect.catch((error) =>
509 Effect.logWarning("failed to start server settings runtime", {
510 path: error.settingsPath,
511 operation: error.operation,
512 providerInstanceId: error.providerInstanceId,
513 environmentVariable: error.environmentVariable,
514 cause: error.cause,
515 }),
516 ),
517 ),
518 );
519
520 const welcomeBase = yield* resolveWelcomeBase;
521 const environment = yield* serverEnvironment.getDescriptor;
522 const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
523 if (legacyMigrationThreadCount > 0) {
524 yield* lifecycleEvents.publish({
525 version: 1,
526 type: "legacyThreadMigration",
527 payload: {
528 status: "running",
529 totalThreadCount: legacyMigrationThreadCount,
530 },
531 });
532 }
533 const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
534 importLegacyShells: runStartupPhase(
535 "orchestration-v2.legacy-v1.import-shells",
536 legacyV1ThreadImporter.reconcileShells.pipe(
537 Effect.tap((summary) =>
538 summary.importedThreadCount === 0
539 ? Effect.void
540 : Effect.logInfo("Imported legacy v1 thread shells", summary),
541 ),
542 ),
543 ),
544 recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
545 recoverDelegatedTasks: runStartupPhase(
546 "orchestration-v2.delegated-tasks.recover",
547 orchestrator.recoverDelegatedTasks,
548 ),
549 startEffectWorker: runStartupPhase(
550 "orchestration-v2.effect-worker.start",
551 startEffectWorkerWithRelay({
552 runWorker: EffectWorker.runDaemon,
553 startRelay: agentAwarenessRelay.start(),
554 workerFiberRef: effectWorkerFiber,
555 }),
556 ),
557 autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
558 ? runStartupPhase(
559 "welcome.autobootstrap",
560 resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),
561 )
562 : Effect.succeed({})
563 ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
564 });
565 yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
566 // Runs after activation: the status check fetches every enabled project's
567 // remote, and awaiting it here held command readiness for that long.
568 yield* runStartupPhase(
569 "projects.auto-pull",
570 Effect.gen(function* () {
571 const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells();
572 const settings = yield* serverSettings.getSettings;
573 yield* autoPullProjects(projects, settings);
574 }),
575 ).pipe(
576 Effect.catch((cause) =>
577 Effect.logWarning("Failed to load projects for automatic pull", { cause }),
578 ),
579 forkParked,
580 );
581
582 const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
583 Effect.tap((summary) =>
584 summary.importedThreadCount === 0
585 ? Effect.void
586 : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
587 ),
588 );
589 yield* (
590 legacyMigrationThreadCount > 0
591 ? importPendingTranscripts.pipe(
592 Effect.tap(() =>
593 lifecycleEvents.publish({
594 version: 1,
595 type: "legacyThreadMigration",
596 payload: {
597 status: "complete",
598 totalThreadCount: legacyMigrationThreadCount,
599 },
600 }),
601 ),
602 )
603 : importPendingTranscripts
604 ).pipe(forkParked);
605
606 yield* forkParked(
607 Effect.gen(function* () {
608 yield* Effect.logDebug("startup phase: recording startup heartbeat");
609 yield* recordStartupHeartbeat.pipe(
610 Effect.withSpan("server.startup.heartbeat.record", {
611 attributes: { "startup.phase": "heartbeat.record" },
612 }),
613 Effect.ignoreCause({ log: true }),
614 );
615 if (serverConfig.startupPresentation === "headless") {
616 yield* Effect.logDebug("startup phase: headless access info");
617 const accessInfo = yield* issueHeadlessServeAccessInfo();
618 yield* runStartupPhase(
619 "headless.output",
620 Console.log(formatHeadlessServeOutput(accessInfo)),
621 );
622 } else {
623 yield* Effect.logDebug("startup phase: browser open check");
624 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
625 if (serverConfig.mode !== "desktop") {
626 yield* announceStartupPairingUrl(startupBrowserTarget);
627 }
628 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
629 }
630 }),
631 );
632
633 yield* Effect.logDebug("startup phase: waiting for http listener");
634 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
635 yield* runStartupPhase("auxiliary-roots.parked", options?.awaitAuxiliaryParked ?? Effect.void);
636
637 const updateOutcome = yield* launcher.prepareTrial;
638
639 yield* Effect.logDebug("startup phase: publishing welcome event", {
640 environmentId: environment.environmentId,
641 cwd: welcomeBase.cwd,
642 projectName: welcomeBase.projectName,
643 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
644 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
645 });
646 yield* runStartupPhase(
647 "welcome.publish",
648 lifecycleEvents.publish({
649 version: 1,
650 type: "welcome",
651 payload: {
652 environment,
653 ...welcomeBase,
654 ...bootstrapTargets,
655 },
656 }),
657 );
658
659 yield* options?.activate ?? Effect.void;
660 yield* Effect.logDebug("Accepting commands");
661 yield* commandGate.signalCommandReady;
662 yield* Effect.logDebug("startup phase: publishing ready event");
663 yield* runStartupPhase(
664 "ready.publish",
665 lifecycleEvents.publish({
666 version: 1,
667 type: "ready",
668 payload: {
669 at: DateTime.formatIso(yield* DateTime.now),
670 environment,
671 ...(updateOutcome === undefined ? {} : { updateOutcome }),
672 },
673 }),
674 );
675 yield* Effect.logDebug("startup phase: complete");
676 yield* flushCompileCache;
677 }).pipe(
678 Effect.withSpan("server.startup", {
679 kind: "server",
680 root: true,
681 attributes: {
682 "server.mode": serverConfig.mode,
683 "server.port": serverConfig.port,
684 "server.host": serverConfig.host ?? "default",
685 },
686 }),
687 );
688
689 yield* Effect.forkScoped(
690 Effect.exit(startup).pipe(
691 Effect.flatMap((startupExit) => {
692 if (Exit.isSuccess(startupExit)) return Effect.void;
693 const error = new ServerRuntimeStartupError({
694 mode: serverConfig.mode,
695 host: serverConfig.host ?? null,
696 port: serverConfig.port,
697 cause: startupExit.cause,
698 });
699 return Effect.logError("server runtime startup failed", {
700 cause: Cause.pretty(startupExit.cause),
701 }).pipe(
702 Effect.andThen(commandGate.failCommandReady(error)),
703 Effect.andThen(options?.abort?.(error) ?? Effect.void),
704 );
705 }),
706 ),
707 );
708
709 return {
710 awaitCommandReady: commandGate.awaitCommandReady,
711 markHttpListening: Deferred.succeed(httpListening, undefined),
712 enqueueCommand: commandGate.enqueueCommand,
713 } satisfies ServerRuntimeStartup["Service"];
714});
715
716export const layerWithOptions = (options?: StartupOptions) =>
717 Layer.effect(ServerRuntimeStartup, make(options));