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

serverRuntimeStartup.ts

728 lines27.6 KB

1import {
2 CommandId,
3 DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,
4 DEFAULT_MODEL,
5 DEFAULT_PROVIDER_INTERACTION_MODE,
6 DEFAULT_SERVER_SETTINGS,
7 isListedThreadLineage,
8 type ModelSelection,
9 type Project,
10 ProjectId,
11 ProviderInstanceId,
12 ThreadId,
13} from "@t3tools/contracts";
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 Duration from "effect/Duration";
21import * as Deferred from "effect/Deferred";
22import * as Effect from "effect/Effect";
23import * as Exit from "effect/Exit";
24import * as Fiber from "effect/Fiber";
25import * as Layer from "effect/Layer";
26import * as Path from "effect/Path";
27import * as Queue from "effect/Queue";
28import * as Ref from "effect/Ref";
29import * as Schema from "effect/Schema";
30​
31import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
32import * as ServerConfig from "./config.ts";
33import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
34import { flushCompileCache } from "./compileCache.ts";
35import * as Keybindings from "./keybindings.ts";
36import * as ExternalLauncher from "./process/externalLauncher.ts";
37import * as EffectWorker from "./orchestration-v2/EffectWorker.ts";
38import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
39import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
40import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts";
41import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
42import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts";
43import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
44import * as ProjectService from "./project/ProjectService.ts";
45import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
46import { VcsAutomaticFetchInterval } from "./vcs/VcsAutomaticFetchInterval.ts";
47import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
48import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
49import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
50import * as ServerSettings from "./serverSettings.ts";
51import { forkParked, forkParkedFiber } from "./serverActivation.ts";
52import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
53import { getServerOwners } from "./telemetry/Identify.ts";
54import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
55import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
56import { headlessServeOutput, resolveLocalOrigin } 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 }
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>;
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>;
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 threadCount: threads.countThreads(),
157 }).pipe(
158 Effect.map(({ projects: projectSnapshot, threadCount }) => ({
159 projectCount: projectSnapshot.projects.length,
160 threadCount,
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;
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 // Startup checks once, so it waits for the fetch rather than reading the old references.
209 // The remote status is cheap; the working-tree scan runs only for a checkout that is behind.
210 const remote = yield* git
211 .statusDetailsRemote(cwd, { includeAheadOfDefault: false })
212 .pipe(Effect.provideService(GitVcsDriver.AwaitStatusFetch, true));
213 const skip = (reason: string) =>
214 Effect.logDebug("Skipped automatic project pull", { cwd, reason });
215 if (!remote.isRepo) return yield* skip("not-a-repository");
216 if (!remote.isDefaultBranch) return yield* skip("not-on-default-branch");
217 if (!remote.hasUpstream) return yield* skip("no-upstream");
218 if (remote.aheadCount > 0) return yield* skip("local-commits");
219 if (remote.behindCount <= 0) return;
220​
221 const local = yield* git.statusDetailsLocal(cwd, { includeDivergence: false });
222 if (local.hasWorkingTreeChanges) return yield* skip("working-tree-changes");
223​
224 const result = yield* git.pullCurrentBranch(cwd);
225 yield* Effect.logDebug("Automatic project pull completed", {
226 cwd,
227 status: result.status,
228 refName: result.refName,
229 });
230 }).pipe(
231 Effect.catch((cause) =>
232 Effect.logWarning("Automatic project pull failed", {
233 cwd,
234 cause,
235 }),
236 ),
237 ),
238 { concurrency: 4, discard: true },
239 );
240});
241​
242const resolveWelcomeBase = Effect.gen(function* () {
243 const serverConfig = yield* ServerConfig.ServerConfig;
244 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
245 const projectName = segments[segments.length - 1] ?? "project";
246​
247 return {
248 cwd: serverConfig.cwd,
249 projectName,
250 } as const;
251});
252​
253const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
254 const random = yield* SecureRandom.SecureRandom;
255 const randomUUID = random.uuidV4();
256 const serverConfig = yield* ServerConfig.ServerConfig;
257 const projects = yield* ProjectService.ProjectService;
258 const threads = yield* ThreadManagement.ThreadManagementService;
259 const threadLaunch = yield* ThreadLaunch.ThreadLaunchService;
260 const path = yield* Path.Path;
261​
262 let bootstrapProjectId: ProjectId | undefined;
263 let bootstrapThreadId: ThreadId | undefined;
264​
265 if (serverConfig.autoBootstrapProjectFromCwd) {
266 const threadModelSelection = getAutoBootstrapThreadModelSelection();
267 const bootstrapped = yield* projects
268 .bootstrap({
269 commandId: CommandId.make(yield* randomUUID),
270 projectId: ProjectId.make(yield* randomUUID),
271 title: path.basename(serverConfig.cwd) || "project",
272 workspaceRoot: serverConfig.cwd,
273 })
274 .pipe(
275 // A folder the project rules refuse must not stop the server from starting there.
276 Effect.catchTags({
277 ProjectInvalidError: (error) =>
278 Effect.logWarning("Skipped bootstrap project", { detail: error.detail }).pipe(
279 Effect.as(undefined),
280 ),
281 }),
282 );
283 if (bootstrapped === undefined) return {} satisfies AutoBootstrapWelcomeTargets;
284 const { project } = bootstrapped;
285 const existingThread = (yield* threads.listActiveShellIndex()).find(
286 (thread) => thread.projectId === project.id && isListedThreadLineage(thread.lineage),
287 );
288 if (existingThread === undefined) {
289 const serverSettings = yield* ServerSettings.ServerSettingsService;
290 const settings = yield* serverSettings.getSettings;
291 const launched = yield* threadLaunch
292 .launch({
293 commandId: CommandId.make(yield* randomUUID),
294 projectId: project.id,
295 title: "New thread",
296 modelSelection:
297 resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ??
298 threadModelSelection,
299 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
300 runtimeMode: resolveProjectSettings(settings, project.id, project).settings
301 .defaultRuntimeMode,
302 workspaceStrategy: { type: "root" },
303 createdBy: "system",
304 creationSource: "server",
305 })
306 .pipe(
307 // The bootstrap thread is optional; its launch must not prevent opening the app.
308 Effect.catchTags({
309 ThreadManagementProviderInstanceDisabledError: (error) =>
310 Effect.logInfo("Skipped bootstrap thread because its provider instance is disabled", {
311 projectId: project.id,
312 instanceId: error.instanceId,
313 }).pipe(Effect.as(undefined)),
314 ThreadLaunchError: (error) =>
315 Effect.logWarning("Failed to launch bootstrap thread", {
316 projectId: project.id,
317 operation: error.operation,
318 }).pipe(Effect.as(undefined)),
319 }),
320 );
321 bootstrapProjectId = project.id;
322 bootstrapThreadId = launched?.threadId;
323 } else {
324 bootstrapProjectId = project.id;
325 bootstrapThreadId = existingThread.id;
326 }
327 }
328​
329 return {
330 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
331 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
332 } satisfies AutoBootstrapWelcomeTargets;
333});
334​
335const resolveStartupBrowserTarget = Effect.gen(function* () {
336 const serverConfig = yield* ServerConfig.ServerConfig;
337 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
338 const baseTarget =
339 serverConfig.devUrl?.toString() ?? resolveLocalOrigin(serverConfig.host, serverConfig.port);
340 return serverConfig.mode === "desktop"
341 ? baseTarget
342 : yield* serverAuth.issueStartupPairingUrl(baseTarget);
343});
344​
345/** Prints the one-time admin pairing URL to stdout only; logger records reach trace files and collectors. */
346export const announceStartupPairingUrl = (pairingUrl: string) =>
347 Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe(
348 Effect.andThen(Console.log(` pairingUrl: ${pairingUrl}`)),
349 );
350​
351// Pairing tokens belong only in announceStartupPairingUrl's stdout output.
352export const logBrowserAutoOpenUnavailable = Effect.logInfo("browser auto-open unavailable", {
353 hint: "Open the pairing URL above in your browser.",
354});
355​
356export const maybeOpenBrowser = Effect.fn("serverRuntimeStartup.maybeOpenBrowser")(function* (
357 target: string,
358) {
359 const serverConfig = yield* ServerConfig.ServerConfig;
360 if (serverConfig.noBrowser) {
361 return;
362 }
363 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
364​
365 yield* externalLauncher.launchBrowser(target).pipe(
366 // The target carries the pairing token, and a failed launch records its
367 // command line on the span, so this call stays out of traces.
368 Effect.withTracerEnabled(false),
369 Effect.catch(() => logBrowserAutoOpenUnavailable),
370 );
371});
372​
373const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
374 effect.pipe(
375 // Use span attributes; annotations would follow long-lived forked fibers for the server's lifetime.
376 Effect.withSpan(`server.startup.${phase}`, { attributes: { "startup.phase": phase } }),
377 );
378​
379interface StartupOptions {
380 readonly activate?: Effect.Effect<void>;
381 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
382 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
384​
385export const startEffectWorkerWithRelay = Effect.fn(
386 "ServerRuntimeStartup.startEffectWorkerWithRelay",
387)(function* <WorkerContext, RelayContext>(input: {
388 readonly runWorker: Effect.Effect<void, never, WorkerContext>;
389 readonly startRelay: Effect.Effect<void, never, RelayContext>;
390 readonly workerFiberRef: Ref.Ref<Fiber.Fiber<void, never> | null>;
391}) {
392 const workerFiber = yield* forkParkedFiber(input.runWorker);
393 yield* Ref.set(input.workerFiberRef, workerFiber);
394 yield* input.startRelay.pipe(
395 Effect.onExit((exit) => {
396 if (Exit.isSuccess(exit)) {
397 return Effect.void;
398 }
399 return Ref.getAndSet(input.workerFiberRef, null).pipe(
400 Effect.flatMap((ownedWorkerFiber) =>
401 ownedWorkerFiber === null
402 ? Effect.void
403 : Fiber.interrupt(ownedWorkerFiber).pipe(Effect.asVoid),
404 ),
405 );
406 }),
407 );
408});
409​
410const runOrderedV2StartupPhases = Effect.fn("serverRuntimeStartup.runOrderedV2StartupPhases")(
411 function* <
412 Import,
413 Recovery,
414 Bootstrap,
415 ImportError,
416 RecoveryError,
417 DelegationError,
418 WorkerError,
419 BootstrapError,
420 ImportContext,
421 RecoveryContext,
422 DelegationContext,
423 WorkerContext,
424 BootstrapContext,
425 >(input: {
426 readonly importLegacyShells: Effect.Effect<Import, ImportError, ImportContext>;
427 readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
428 readonly recoverDelegatedTasks: Effect.Effect<void, DelegationError, DelegationContext>;
429 readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
430 readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
431 }) {
432 yield* input.importLegacyShells;
433 const recovery = yield* input.recover;
434 yield* input.recoverDelegatedTasks;
435 yield* input.startEffectWorker;
436 const bootstrap = yield* input.autoBootstrap;
437 return { recovery, bootstrap } as const;
438 },
439);
440​
441const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: StartupOptions) {
442 const serverConfig = yield* ServerConfig.ServerConfig;
443 const keybindings = yield* Keybindings.Keybindings;
444 const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
445 const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
446 const orchestrator = yield* Orchestrator.OrchestratorV2;
447 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
448 const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
449 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
450 const serverSettings = yield* ServerSettings.ServerSettingsService;
451 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
452 const random = yield* SecureRandom.SecureRandom;
453 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
454​
455 const commandGate = yield* makeCommandGate;
456 const httpListening = yield* Deferred.make<void>();
457 const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
458​
459 yield* Effect.addFinalizer(() =>
460 Effect.gen(function* () {
461 yield* commandGate.failCommandReady(
462 new ServerRuntimeStartupError({
463 mode: serverConfig.mode,
464 host: serverConfig.host ?? null,
465 port: serverConfig.port,
466 cause: "Server runtime is shutting down.",
467 }),
468 );
469 const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
470 if (workerFiber !== null) {
471 yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
472 }
473 yield* providerRuntimeRecovery.prepareForShutdown.pipe(
474 Effect.ensuring(providerSessions.shutdown),
475 );
476 const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
477 yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
478 }).pipe(
479 Effect.withSpan("server.shutdown"),
480 Effect.catchCause((cause) =>
481 Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
482 cause: Cause.pretty(cause),
483 }),
484 ),
485 ),
486 );
487​
488 const startup = Effect.gen(function* () {
489 yield* Effect.logDebug("startup phase: starting keybindings runtime");
490 yield* runStartupPhase(
491 "keybindings.start",
492 keybindings.start.pipe(
493 Effect.catch((error) =>
494 Effect.logWarning("failed to start keybindings runtime", {
495 path: error.configPath,
496 detail: error.detail,
497 cause: error.cause,
498 }),
499 ),
500 ),
501 );
502​
503 yield* Effect.logDebug("startup phase: starting server settings runtime");
504 yield* runStartupPhase(
505 "settings.start",
506 serverSettings.start.pipe(
507 Effect.catch((error) =>
508 Effect.logWarning("failed to start server settings runtime", {
509 path: error.settingsPath,
510 operation: error.operation,
511 providerInstanceId: error.providerInstanceId,
512 environmentVariable: error.environmentVariable,
513 cause: error.cause,
514 }),
515 ),
516 ),
517 );
518​
519 const welcomeBase = yield* resolveWelcomeBase;
520 const environment = yield* serverEnvironment.getDescriptor;
521 const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
522 if (legacyMigrationThreadCount > 0) {
523 yield* lifecycleEvents.publish({
524 version: 1,
525 type: "legacyThreadMigration",
526 payload: {
527 status: "running",
528 totalThreadCount: legacyMigrationThreadCount,
529 },
530 });
531 }
532 const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
533 importLegacyShells: runStartupPhase(
534 "orchestration-v2.legacy-v1.import-shells",
535 legacyV1ThreadImporter.reconcileShells.pipe(
536 Effect.tap((summary) =>
537 summary.importedThreadCount === 0
538 ? Effect.void
539 : Effect.logInfo("Imported legacy v1 thread shells", summary),
540 ),
541 ),
542 ),
543 recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
544 recoverDelegatedTasks: runStartupPhase(
545 "orchestration-v2.delegated-tasks.recover",
546 orchestrator.recoverDelegatedTasks,
547 ),
548 startEffectWorker: runStartupPhase(
549 "orchestration-v2.effect-worker.start",
550 startEffectWorkerWithRelay({
551 runWorker: EffectWorker.runDaemon,
552 startRelay: agentAwarenessRelay.start(),
553 workerFiberRef: effectWorkerFiber,
554 }),
555 ),
556 autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
557 ? runStartupPhase(
558 "welcome.autobootstrap",
559 resolveAutoBootstrapWelcomeTargets.pipe(
560 Effect.provideService(SecureRandom.SecureRandom, random),
561 ),
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 const projectStore = yield* ProjectStore.ProjectStoreV2;
570 const automaticFetchInterval = yield* VcsAutomaticFetchInterval;
571 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
572 const autoPullEnabledProjects = Effect.gen(function* () {
573 const projects = yield* projectStore.listShells();
574 const settings = yield* serverSettings.getSettings;
575 yield* autoPullProjects(projects, settings);
576 }).pipe(
577 Effect.catch((cause) =>
578 Effect.logWarning("Failed to load projects for automatic pull", { cause }),
579 ),
580 );
581 // Status subscriptions only poll roots someone views, so unviewed roots are pulled here.
582 const autoPullOnFetchInterval = Effect.gen(function* () {
583 const interval = yield* automaticFetchInterval;
584 yield* Effect.sleep(
585 Duration.isZero(interval) ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL : interval,
586 );
587 if (!Duration.isZero(interval) && (yield* backgroundPolicy.shouldRunHostWork)) {
588 yield* autoPullEnabledProjects;
589 }
590 }).pipe(Effect.forever);
591 yield* runStartupPhase("projects.auto-pull", autoPullEnabledProjects).pipe(
592 Effect.andThen(autoPullOnFetchInterval),
593 forkParked,
594 );
595​
596 const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
597 Effect.tap((summary) =>
598 summary.importedThreadCount === 0
599 ? Effect.void
600 : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
601 ),
602 );
603 yield* (
604 legacyMigrationThreadCount > 0
605 ? importPendingTranscripts.pipe(
606 Effect.tap(() =>
607 lifecycleEvents.publish({
608 version: 1,
609 type: "legacyThreadMigration",
610 payload: {
611 status: "complete",
612 totalThreadCount: legacyMigrationThreadCount,
613 },
614 }),
615 ),
616 )
617 : importPendingTranscripts
618 ).pipe(forkParked);
619​
620 yield* forkParked(
621 Effect.gen(function* () {
622 yield* Effect.logDebug("startup phase: recording startup heartbeat");
623 yield* recordStartupHeartbeat.pipe(
624 Effect.withSpan("server.startup.heartbeat.record", {
625 attributes: { "startup.phase": "heartbeat.record" },
626 }),
627 Effect.ignoreCause({ log: true }),
628 );
629 if (serverConfig.startupPresentation === "headless") {
630 yield* Effect.logDebug("startup phase: headless access info");
631 const output = yield* headlessServeOutput({ serviceManaged: launcher.managed });
632 yield* runStartupPhase("headless.output", Console.log(output));
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));