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

serverRuntimeStartup.ts

728 lines26.7 KB

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