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 { 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 }
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 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;
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 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/** Prints the one-time admin pairing URL to stdout only; logger records reach trace files and collectors. */
349export const announceStartupPairingUrl = (pairingUrl: string) =>
350 Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe(
351 Effect.andThen(Console.log(` pairingUrl: ${pairingUrl}`)),
352 );
353
354// Pairing tokens belong only in announceStartupPairingUrl's stdout output.
355export const logBrowserAutoOpenUnavailable = Effect.logInfo("browser auto-open unavailable", {
356 hint: "Open the pairing URL above in your browser.",
357});
358
359export const maybeOpenBrowser = Effect.fn("serverRuntimeStartup.maybeOpenBrowser")(function* (
360 target: string,
361) {
362 const serverConfig = yield* ServerConfig.ServerConfig;
363 if (serverConfig.noBrowser) {
364 return;
365 }
366 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
367
368 yield* externalLauncher.launchBrowser(target).pipe(
369 // The target carries the pairing token, and a failed launch records its
370 // command line on the span, so this call stays out of traces.
371 Effect.withTracerEnabled(false),
372 Effect.catch(() => logBrowserAutoOpenUnavailable),
373 );
374});
375
376const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
377 effect.pipe(
378 // Use span attributes; annotations would follow long-lived forked fibers for the server's lifetime.
379 Effect.withSpan(`server.startup.${phase}`, { attributes: { "startup.phase": phase } }),
380 );
381
382interface StartupOptions {
383 readonly activate?: Effect.Effect<void>;
384 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
385 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
386}
387
388export const startEffectWorkerWithRelay = Effect.fn(
389 "ServerRuntimeStartup.startEffectWorkerWithRelay",
390)(function* <WorkerContext, RelayContext>(input: {
391 readonly runWorker: Effect.Effect<void, never, WorkerContext>;
392 readonly startRelay: Effect.Effect<void, never, RelayContext>;
393 readonly workerFiberRef: Ref.Ref<Fiber.Fiber<void, never> | null>;
394}) {
395 const workerFiber = yield* forkParkedFiber(input.runWorker);
396 yield* Ref.set(input.workerFiberRef, workerFiber);
397 yield* input.startRelay.pipe(
398 Effect.onExit((exit) => {
399 if (Exit.isSuccess(exit)) {
400 return Effect.void;
401 }
402 return Ref.getAndSet(input.workerFiberRef, null).pipe(
403 Effect.flatMap((ownedWorkerFiber) =>
404 ownedWorkerFiber === null
405 ? Effect.void
406 : Fiber.interrupt(ownedWorkerFiber).pipe(Effect.asVoid),
407 ),
408 );
409 }),
410 );
411});
412
413const runOrderedV2StartupPhases = Effect.fn("serverRuntimeStartup.runOrderedV2StartupPhases")(
414 function* <
415 Import,
416 Recovery,
417 Bootstrap,
418 ImportError,
419 RecoveryError,
420 DelegationError,
421 WorkerError,
422 BootstrapError,
423 ImportContext,
424 RecoveryContext,
425 DelegationContext,
426 WorkerContext,
427 BootstrapContext,
428 >(input: {
429 readonly importLegacyShells: Effect.Effect<Import, ImportError, ImportContext>;
430 readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
431 readonly recoverDelegatedTasks: Effect.Effect<void, DelegationError, DelegationContext>;
432 readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
433 readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
434 }) {
435 yield* input.importLegacyShells;
436 const recovery = yield* input.recover;
437 yield* input.recoverDelegatedTasks;
438 yield* input.startEffectWorker;
439 const bootstrap = yield* input.autoBootstrap;
440 return { recovery, bootstrap } as const;
441 },
442);
443
444const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: StartupOptions) {
445 const serverConfig = yield* ServerConfig.ServerConfig;
446 const keybindings = yield* Keybindings.Keybindings;
447 const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
448 const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
449 const orchestrator = yield* Orchestrator.OrchestratorV2;
450 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
451 const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
452 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
453 const serverSettings = yield* ServerSettings.ServerSettingsService;
454 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
455 const crypto = yield* Crypto.Crypto;
456 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
457
458 const commandGate = yield* makeCommandGate;
459 const httpListening = yield* Deferred.make<void>();
460 const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
461
462 yield* Effect.addFinalizer(() =>
463 Effect.gen(function* () {
464 yield* commandGate.failCommandReady(
465 new ServerRuntimeStartupError({
466 mode: serverConfig.mode,
467 host: serverConfig.host ?? null,
468 port: serverConfig.port,
469 cause: "Server runtime is shutting down.",
470 }),
471 );
472 const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
473 if (workerFiber !== null) {
474 yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
475 }
476 yield* providerRuntimeRecovery.prepareForShutdown.pipe(
477 Effect.ensuring(providerSessions.shutdown),
478 );
479 const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
480 yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
481 }).pipe(
482 Effect.catchCause((cause) =>
483 Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
484 cause: Cause.pretty(cause),
485 }),
486 ),
487 ),
488 );
489
490 const startup = Effect.gen(function* () {
491 yield* Effect.logDebug("startup phase: starting keybindings runtime");
492 yield* runStartupPhase(
493 "keybindings.start",
494 keybindings.start.pipe(
495 Effect.catch((error) =>
496 Effect.logWarning("failed to start keybindings runtime", {
497 path: error.configPath,
498 detail: error.detail,
499 cause: error.cause,
500 }),
501 ),
502 ),
503 );
504
505 yield* Effect.logDebug("startup phase: starting server settings runtime");
506 yield* runStartupPhase(
507 "settings.start",
508 serverSettings.start.pipe(
509 Effect.catch((error) =>
510 Effect.logWarning("failed to start server settings runtime", {
511 path: error.settingsPath,
512 operation: error.operation,
513 providerInstanceId: error.providerInstanceId,
514 environmentVariable: error.environmentVariable,
515 cause: error.cause,
516 }),
517 ),
518 ),
519 );
520
521 const welcomeBase = yield* resolveWelcomeBase;
522 const environment = yield* serverEnvironment.getDescriptor;
523 const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
524 if (legacyMigrationThreadCount > 0) {
525 yield* lifecycleEvents.publish({
526 version: 1,
527 type: "legacyThreadMigration",
528 payload: {
529 status: "running",
530 totalThreadCount: legacyMigrationThreadCount,
531 },
532 });
533 }
534 const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
535 importLegacyShells: runStartupPhase(
536 "orchestration-v2.legacy-v1.import-shells",
537 legacyV1ThreadImporter.reconcileShells.pipe(
538 Effect.tap((summary) =>
539 summary.importedThreadCount === 0
540 ? Effect.void
541 : Effect.logInfo("Imported legacy v1 thread shells", summary),
542 ),
543 ),
544 ),
545 recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
546 recoverDelegatedTasks: runStartupPhase(
547 "orchestration-v2.delegated-tasks.recover",
548 orchestrator.recoverDelegatedTasks,
549 ),
550 startEffectWorker: runStartupPhase(
551 "orchestration-v2.effect-worker.start",
552 startEffectWorkerWithRelay({
553 runWorker: EffectWorker.runDaemon,
554 startRelay: agentAwarenessRelay.start(),
555 workerFiberRef: effectWorkerFiber,
556 }),
557 ),
558 autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
559 ? runStartupPhase(
560 "welcome.autobootstrap",
561 resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),
562 )
563 : Effect.succeed({})
564 ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
565 });
566 yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
567 // Runs after activation: the status check fetches every enabled project's
568 // remote, and awaiting it here held command readiness for that long.
569 yield* runStartupPhase(
570 "projects.auto-pull",
571 Effect.gen(function* () {
572 const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells();
573 const settings = yield* serverSettings.getSettings;
574 yield* autoPullProjects(projects, settings);
575 }),
576 ).pipe(
577 Effect.catch((cause) =>
578 Effect.logWarning("Failed to load projects for automatic pull", { cause }),
579 ),
580 forkParked,
581 );
582
583 const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
584 Effect.tap((summary) =>
585 summary.importedThreadCount === 0
586 ? Effect.void
587 : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
588 ),
589 );
590 yield* (
591 legacyMigrationThreadCount > 0
592 ? importPendingTranscripts.pipe(
593 Effect.tap(() =>
594 lifecycleEvents.publish({
595 version: 1,
596 type: "legacyThreadMigration",
597 payload: {
598 status: "complete",
599 totalThreadCount: legacyMigrationThreadCount,
600 },
601 }),
602 ),
603 )
604 : importPendingTranscripts
605 ).pipe(forkParked);
606
607 yield* forkParked(
608 Effect.gen(function* () {
609 yield* Effect.logDebug("startup phase: recording startup heartbeat");
610 yield* recordStartupHeartbeat.pipe(
611 Effect.withSpan("server.startup.heartbeat.record", {
612 attributes: { "startup.phase": "heartbeat.record" },
613 }),
614 Effect.ignoreCause({ log: true }),
615 );
616 if (serverConfig.startupPresentation === "headless") {
617 yield* Effect.logDebug("startup phase: headless access info");
618 const accessInfo = yield* issueHeadlessServeAccessInfo();
619 yield* runStartupPhase(
620 "headless.output",
621 Console.log(formatHeadlessServeOutput(accessInfo)),
622 );
623 } else {
624 yield* Effect.logDebug("startup phase: browser open check");
625 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
626 if (serverConfig.mode !== "desktop") {
627 yield* announceStartupPairingUrl(startupBrowserTarget);
628 }
629 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
630 }
631 }),
632 );
633
634 yield* Effect.logDebug("startup phase: waiting for http listener");
635 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
636 yield* runStartupPhase("auxiliary-roots.parked", options?.awaitAuxiliaryParked ?? Effect.void);
637
638 const updateOutcome = yield* launcher.prepareTrial;
639
640 yield* Effect.logDebug("startup phase: publishing welcome event", {
641 environmentId: environment.environmentId,
642 cwd: welcomeBase.cwd,
643 projectName: welcomeBase.projectName,
644 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
645 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
646 });
647 yield* runStartupPhase(
648 "welcome.publish",
649 lifecycleEvents.publish({
650 version: 1,
651 type: "welcome",
652 payload: {
653 environment,
654 ...welcomeBase,
655 ...bootstrapTargets,
656 },
657 }),
658 );
659
660 yield* options?.activate ?? Effect.void;
661 yield* Effect.logDebug("Accepting commands");
662 yield* commandGate.signalCommandReady;
663 yield* Effect.logDebug("startup phase: publishing ready event");
664 yield* runStartupPhase(
665 "ready.publish",
666 lifecycleEvents.publish({
667 version: 1,
668 type: "ready",
669 payload: {
670 at: DateTime.formatIso(yield* DateTime.now),
671 environment,
672 ...(updateOutcome === undefined ? {} : { updateOutcome }),
673 },
674 }),
675 );
676 yield* Effect.logDebug("startup phase: complete");
677 yield* flushCompileCache;
678 }).pipe(
679 Effect.withSpan("server.startup", {
680 kind: "server",
681 root: true,
682 attributes: {
683 "server.mode": serverConfig.mode,
684 "server.port": serverConfig.port,
685 "server.host": serverConfig.host ?? "default",
686 },
687 }),
688 );
689
690 yield* Effect.forkScoped(
691 Effect.exit(startup).pipe(
692 Effect.flatMap((startupExit) => {
693 if (Exit.isSuccess(startupExit)) return Effect.void;
694 const error = new ServerRuntimeStartupError({
695 mode: serverConfig.mode,
696 host: serverConfig.host ?? null,
697 port: serverConfig.port,
698 cause: startupExit.cause,
699 });
700 return Effect.logError("server runtime startup failed", {
701 cause: Cause.pretty(startupExit.cause),
702 }).pipe(
703 Effect.andThen(commandGate.failCommandReady(error)),
704 Effect.andThen(options?.abort?.(error) ?? Effect.void),
705 );
706 }),
707 ),
708 );
709
710 return {
711 awaitCommandReady: commandGate.awaitCommandReady,
712 markHttpListening: Deferred.succeed(httpListening, undefined),
713 enqueueCommand: commandGate.enqueueCommand,
714 } satisfies ServerRuntimeStartup["Service"];
715});
716
717export const layerWithOptions = (options?: StartupOptions) =>
718 Layer.effect(ServerRuntimeStartup, make(options));