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 // Project creation has no user model choice; only the bootstrap thread
272 // gets an automatic selection, and an explicit project default wins.
273 const threadModelSelection = getAutoBootstrapThreadModelSelection();
274 const { project } = yield* projects.bootstrap({
275 commandId: CommandId.make(yield* randomUUID),
276 projectId: ProjectId.make(yield* randomUUID),
277 title: path.basename(serverConfig.cwd) || "project",
278 workspaceRoot: serverConfig.cwd,
279 });
280 const shell = yield* threads.getShellSnapshot();
281 const existingThread = shell.threads.find(
282 (thread) =>
283 thread.projectId === project.id && thread.lineage.relationshipToParent !== "subagent",
284 );
285 if (existingThread === undefined) {
286 const serverSettings = yield* ServerSettings.ServerSettingsService;
287 const settings = yield* serverSettings.getSettings;
288 const launched = yield* threadLaunch.launch({
289 commandId: CommandId.make(yield* randomUUID),
290 projectId: project.id,
291 title: "New thread",
292 modelSelection:
293 resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ??
294 threadModelSelection,
295 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
296 runtimeMode: resolveProjectSettings(settings, project.id, project).settings
297 .defaultRuntimeMode,
298 workspaceStrategy: { type: "root" },
299 createdBy: "system",
300 creationSource: "server",
301 });
302 bootstrapProjectId = project.id;
303 bootstrapThreadId = launched.threadId;
304 } else {
305 bootstrapProjectId = project.id;
306 bootstrapThreadId = existingThread.id;
307 }
308 }
309
310 return {
311 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
312 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
313 } satisfies AutoBootstrapWelcomeTargets;
314});
315
316const resolveStartupBrowserTarget = Effect.gen(function* () {
317 const serverConfig = yield* ServerConfig.ServerConfig;
318 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
319 const localUrl = `http://localhost:${serverConfig.port}`;
320 const bindUrl =
321 serverConfig.host && !isWildcardHost(serverConfig.host)
322 ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
323 : localUrl;
324 const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
325 return serverConfig.mode === "desktop"
326 ? baseTarget
327 : yield* serverAuth.issueStartupPairingUrl(baseTarget);
328});
329
330const maybeOpenBrowser = (target: string) =>
331 Effect.gen(function* () {
332 const serverConfig = yield* ServerConfig.ServerConfig;
333 if (serverConfig.noBrowser) {
334 return;
335 }
336 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
337
338 yield* externalLauncher.launchBrowser(target).pipe(
339 Effect.catch(() =>
340 Effect.logInfo("browser auto-open unavailable", {
341 hint: `Open ${target} in your browser.`,
342 }),
343 ),
344 );
345 });
346
347const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
348 effect.pipe(
349 // Attributes on the span itself, not annotateSpans: an annotation follows
350 // every fiber forked inside the phase, such as the effect worker, for the
351 // life of the server.
352 Effect.withSpan(`server.startup.${phase}`, { attributes: { "startup.phase": phase } }),
353 );
354
355interface StartupOptions {
356 readonly activate?: Effect.Effect<void>;
357 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
358 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
359}
360
361export const startEffectWorkerWithRelay = Effect.fn(
362 "ServerRuntimeStartup.startEffectWorkerWithRelay",
363)(function* <WorkerContext, RelayContext>(input: {
364 readonly runWorker: Effect.Effect<void, never, WorkerContext>;
365 readonly startRelay: Effect.Effect<void, never, RelayContext>;
366 readonly workerFiberRef: Ref.Ref<Fiber.Fiber<void, never> | null>;
367}) {
368 const workerFiber = yield* forkParkedFiber(input.runWorker);
369 yield* Ref.set(input.workerFiberRef, workerFiber);
370 yield* input.startRelay.pipe(
371 Effect.onExit((exit) => {
372 if (Exit.isSuccess(exit)) {
373 return Effect.void;
374 }
375 return Ref.getAndSet(input.workerFiberRef, null).pipe(
376 Effect.flatMap((ownedWorkerFiber) =>
377 ownedWorkerFiber === null
378 ? Effect.void
379 : Fiber.interrupt(ownedWorkerFiber).pipe(Effect.asVoid),
380 ),
381 );
382 }),
383 );
384});
385
386export function runOrderedV2StartupPhases<
387 Import,
388 Recovery,
389 Bootstrap,
390 ImportError,
391 RecoveryError,
392 DelegationError,
393 WorkerError,
394 BootstrapError,
395 ImportContext,
396 RecoveryContext,
397 DelegationContext,
398 WorkerContext,
399 BootstrapContext,
400>(input: {
401 readonly importLegacyShells: Effect.Effect<Import, ImportError, ImportContext>;
402 readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
403 /** Settles delegated tasks whose runs recovery just terminalized. */
404 readonly recoverDelegatedTasks: Effect.Effect<void, DelegationError, DelegationContext>;
405 readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
406 readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
407}) {
408 return Effect.gen(function* () {
409 yield* input.importLegacyShells;
410 const recovery = yield* input.recover;
411 yield* input.recoverDelegatedTasks;
412 yield* input.startEffectWorker;
413 const bootstrap = yield* input.autoBootstrap;
414 return { recovery, bootstrap } as const;
415 });
416}
417
418const make = (options?: StartupOptions) =>
419 Effect.gen(function* () {
420 const serverConfig = yield* ServerConfig.ServerConfig;
421 const keybindings = yield* Keybindings.Keybindings;
422 const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
423 const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
424 const orchestrator = yield* Orchestrator.OrchestratorV2;
425 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
426 const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
427 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
428 const serverSettings = yield* ServerSettings.ServerSettingsService;
429 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
430 const crypto = yield* Crypto.Crypto;
431 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
432
433 const commandGate = yield* makeCommandGate;
434 const httpListening = yield* Deferred.make<void>();
435 const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
436
437 yield* Effect.addFinalizer(() =>
438 Effect.gen(function* () {
439 yield* commandGate.failCommandReady(
440 new ServerRuntimeStartupError({
441 mode: serverConfig.mode,
442 host: serverConfig.host ?? null,
443 port: serverConfig.port,
444 cause: "Server runtime is shutting down.",
445 }),
446 );
447 const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
448 if (workerFiber !== null) {
449 yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
450 }
451 yield* providerRuntimeRecovery.prepareForShutdown.pipe(
452 Effect.ensuring(providerSessions.shutdown),
453 );
454 const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
455 yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
456 }).pipe(
457 Effect.catchCause((cause) =>
458 Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
459 cause: Cause.pretty(cause),
460 }),
461 ),
462 ),
463 );
464
465 const startup = Effect.gen(function* () {
466 yield* Effect.logDebug("startup phase: starting keybindings runtime");
467 yield* runStartupPhase(
468 "keybindings.start",
469 keybindings.start.pipe(
470 Effect.catch((error) =>
471 Effect.logWarning("failed to start keybindings runtime", {
472 path: error.configPath,
473 detail: error.detail,
474 cause: error.cause,
475 }),
476 ),
477 ),
478 );
479
480 yield* Effect.logDebug("startup phase: starting server settings runtime");
481 yield* runStartupPhase(
482 "settings.start",
483 serverSettings.start.pipe(
484 Effect.catch((error) =>
485 Effect.logWarning("failed to start server settings runtime", {
486 path: error.settingsPath,
487 operation: error.operation,
488 providerInstanceId: error.providerInstanceId,
489 environmentVariable: error.environmentVariable,
490 cause: error.cause,
491 }),
492 ),
493 ),
494 );
495
496 const welcomeBase = yield* resolveWelcomeBase;
497 const environment = yield* serverEnvironment.getDescriptor;
498 const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
499 if (legacyMigrationThreadCount > 0) {
500 yield* lifecycleEvents.publish({
501 version: 1,
502 type: "legacyThreadMigration",
503 payload: {
504 status: "running",
505 totalThreadCount: legacyMigrationThreadCount,
506 },
507 });
508 }
509 const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
510 importLegacyShells: runStartupPhase(
511 "orchestration-v2.legacy-v1.import-shells",
512 legacyV1ThreadImporter.reconcileShells.pipe(
513 Effect.tap((summary) =>
514 summary.importedThreadCount === 0
515 ? Effect.void
516 : Effect.logInfo("Imported legacy v1 thread shells", summary),
517 ),
518 ),
519 ),
520 recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
521 recoverDelegatedTasks: runStartupPhase(
522 "orchestration-v2.delegated-tasks.recover",
523 orchestrator.recoverDelegatedTasks,
524 ),
525 startEffectWorker: runStartupPhase(
526 "orchestration-v2.effect-worker.start",
527 startEffectWorkerWithRelay({
528 runWorker: EffectWorker.runDaemon,
529 startRelay: agentAwarenessRelay.start(),
530 workerFiberRef: effectWorkerFiber,
531 }),
532 ),
533 autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
534 ? runStartupPhase(
535 "welcome.autobootstrap",
536 resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),
537 )
538 : Effect.succeed({})
539 ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
540 });
541 yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
542 // Runs after activation: the status check fetches every enabled project's
543 // remote, and awaiting it here held command readiness for that long.
544 yield* runStartupPhase(
545 "projects.auto-pull",
546 Effect.gen(function* () {
547 const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells();
548 const settings = yield* serverSettings.getSettings;
549 yield* autoPullProjects(projects, settings);
550 }),
551 ).pipe(
552 Effect.catch((cause) =>
553 Effect.logWarning("Failed to load projects for automatic pull", { cause }),
554 ),
555 forkParked,
556 );
557
558 const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
559 Effect.tap((summary) =>
560 summary.importedThreadCount === 0
561 ? Effect.void
562 : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
563 ),
564 );
565 yield* (
566 legacyMigrationThreadCount > 0
567 ? importPendingTranscripts.pipe(
568 Effect.tap(() =>
569 lifecycleEvents.publish({
570 version: 1,
571 type: "legacyThreadMigration",
572 payload: {
573 status: "complete",
574 totalThreadCount: legacyMigrationThreadCount,
575 },
576 }),
577 ),
578 )
579 : importPendingTranscripts
580 ).pipe(forkParked);
581
582 yield* forkParked(
583 Effect.gen(function* () {
584 yield* Effect.logDebug("startup phase: recording startup heartbeat");
585 yield* recordStartupHeartbeat.pipe(
586 Effect.withSpan("server.startup.heartbeat.record", {
587 attributes: { "startup.phase": "heartbeat.record" },
588 }),
589 Effect.ignoreCause({ log: true }),
590 );
591 if (serverConfig.startupPresentation === "headless") {
592 yield* Effect.logDebug("startup phase: headless access info");
593 const accessInfo = yield* issueHeadlessServeAccessInfo();
594 yield* runStartupPhase(
595 "headless.output",
596 Console.log(formatHeadlessServeOutput(accessInfo)),
597 );
598 } else {
599 yield* Effect.logDebug("startup phase: browser open check");
600 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
601 if (serverConfig.mode !== "desktop") {
602 yield* Effect.logInfo(
603 "Authentication required. Open T3 Code using the pairing URL.",
604 ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
605 }
606 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
607 }
608 }),
609 );
610
611 yield* Effect.logDebug("startup phase: waiting for http listener");
612 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
613 yield* runStartupPhase(
614 "auxiliary-roots.parked",
615 options?.awaitAuxiliaryParked ?? Effect.void,
616 );
617
618 const updateOutcome = yield* launcher.prepareTrial;
619
620 yield* Effect.logDebug("startup phase: publishing welcome event", {
621 environmentId: environment.environmentId,
622 cwd: welcomeBase.cwd,
623 projectName: welcomeBase.projectName,
624 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
625 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
626 });
627 yield* runStartupPhase(
628 "welcome.publish",
629 lifecycleEvents.publish({
630 version: 1,
631 type: "welcome",
632 payload: {
633 environment,
634 ...welcomeBase,
635 ...bootstrapTargets,
636 },
637 }),
638 );
639
640 yield* options?.activate ?? Effect.void;
641 yield* Effect.logDebug("Accepting commands");
642 yield* commandGate.signalCommandReady;
643 yield* Effect.logDebug("startup phase: publishing ready event");
644 yield* runStartupPhase(
645 "ready.publish",
646 lifecycleEvents.publish({
647 version: 1,
648 type: "ready",
649 payload: {
650 at: DateTime.formatIso(yield* DateTime.now),
651 environment,
652 ...(updateOutcome === undefined ? {} : { updateOutcome }),
653 },
654 }),
655 );
656 yield* Effect.logDebug("startup phase: complete");
657 yield* flushCompileCache;
658 }).pipe(
659 Effect.withSpan("server.startup", {
660 kind: "server",
661 root: true,
662 attributes: {
663 "server.mode": serverConfig.mode,
664 "server.port": serverConfig.port,
665 "server.host": serverConfig.host ?? "default",
666 },
667 }),
668 );
669
670 yield* Effect.forkScoped(
671 Effect.exit(startup).pipe(
672 Effect.flatMap((startupExit) => {
673 if (Exit.isSuccess(startupExit)) return Effect.void;
674 const error = new ServerRuntimeStartupError({
675 mode: serverConfig.mode,
676 host: serverConfig.host ?? null,
677 port: serverConfig.port,
678 cause: startupExit.cause,
679 });
680 return Effect.logError("server runtime startup failed", {
681 cause: Cause.pretty(startupExit.cause),
682 }).pipe(
683 Effect.andThen(commandGate.failCommandReady(error)),
684 Effect.andThen(options?.abort?.(error) ?? Effect.void),
685 );
686 }),
687 ),
688 );
689
690 return {
691 awaitCommandReady: commandGate.awaitCommandReady,
692 markHttpListening: Deferred.succeed(httpListening, undefined),
693 enqueueCommand: commandGate.enqueueCommand,
694 } satisfies ServerRuntimeStartup["Service"];
695 });
696
697export const layerWithOptions = (options?: StartupOptions) =>
698 Layer.effect(ServerRuntimeStartup, make(options));
699
700const layer = layerWithOptions();