Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serverRuntimeStartup.ts

694 lines25.3 KB

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