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

serverRuntimeStartup.ts

740 lines27.5 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 const status = yield* git
210 .statusDetails(cwd)
211 .pipe(Effect.provideService(GitVcsDriver.AwaitStatusFetch, true));
212 if (
213 !status.isRepo ||
214 !status.isDefaultBranch ||
215 !status.hasUpstream ||
216 status.hasWorkingTreeChanges ||
217 status.aheadCount > 0
218 ) {
219 yield* Effect.logDebug("Skipped automatic project pull", {
220 cwd,
221 reason: !status.isRepo
222 ? "not-a-repository"
223 : !status.isDefaultBranch
224 ? "not-on-default-branch"
225 : !status.hasUpstream
226 ? "no-upstream"
227 : status.hasWorkingTreeChanges
228 ? "working-tree-changes"
229 : "local-commits",
230 });
231 return;
232 }
233​
234 if (status.behindCount <= 0) return;
235​
236 const result = yield* git.pullCurrentBranch(cwd);
237 yield* Effect.logDebug("Automatic project pull completed", {
238 cwd,
239 status: result.status,
240 refName: result.refName,
241 });
242 }).pipe(
243 Effect.catch((cause) =>
244 Effect.logWarning("Automatic project pull failed", {
245 cwd,
246 cause,
247 }),
248 ),
249 ),
250 { concurrency: 4, discard: true },
251 );
252});
253​
254const resolveWelcomeBase = Effect.gen(function* () {
255 const serverConfig = yield* ServerConfig.ServerConfig;
256 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
257 const projectName = segments[segments.length - 1] ?? "project";
258​
259 return {
260 cwd: serverConfig.cwd,
261 projectName,
262 } as const;
263});
264​
265const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
266 const random = yield* SecureRandom.SecureRandom;
267 const randomUUID = random.uuidV4();
268 const serverConfig = yield* ServerConfig.ServerConfig;
269 const projects = yield* ProjectService.ProjectService;
270 const threads = yield* ThreadManagement.ThreadManagementService;
271 const threadLaunch = yield* ThreadLaunch.ThreadLaunchService;
272 const path = yield* Path.Path;
273​
274 let bootstrapProjectId: ProjectId | undefined;
275 let bootstrapThreadId: ThreadId | undefined;
276​
277 if (serverConfig.autoBootstrapProjectFromCwd) {
278 const threadModelSelection = getAutoBootstrapThreadModelSelection();
279 const bootstrapped = yield* projects
280 .bootstrap({
281 commandId: CommandId.make(yield* randomUUID),
282 projectId: ProjectId.make(yield* randomUUID),
283 title: path.basename(serverConfig.cwd) || "project",
284 workspaceRoot: serverConfig.cwd,
285 })
286 .pipe(
287 // A folder the project rules refuse must not stop the server from starting there.
288 Effect.catchTags({
289 ProjectInvalidError: (error) =>
290 Effect.logWarning("Skipped bootstrap project", { detail: error.detail }).pipe(
291 Effect.as(undefined),
292 ),
293 }),
294 );
295 if (bootstrapped === undefined) return {} satisfies AutoBootstrapWelcomeTargets;
296 const { project } = bootstrapped;
297 const existingThread = (yield* threads.listActiveShellIndex()).find(
298 (thread) => thread.projectId === project.id && isListedThreadLineage(thread.lineage),
299 );
300 if (existingThread === undefined) {
301 const serverSettings = yield* ServerSettings.ServerSettingsService;
302 const settings = yield* serverSettings.getSettings;
303 const launched = yield* threadLaunch
304 .launch({
305 commandId: CommandId.make(yield* randomUUID),
306 projectId: project.id,
307 title: "New thread",
308 modelSelection:
309 resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ??
310 threadModelSelection,
311 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
312 runtimeMode: resolveProjectSettings(settings, project.id, project).settings
313 .defaultRuntimeMode,
314 workspaceStrategy: { type: "root" },
315 createdBy: "system",
316 creationSource: "server",
317 })
318 .pipe(
319 // The bootstrap thread is optional; its launch must not prevent opening the app.
320 Effect.catchTags({
321 ThreadManagementProviderInstanceDisabledError: (error) =>
322 Effect.logInfo("Skipped bootstrap thread because its provider instance is disabled", {
323 projectId: project.id,
324 instanceId: error.instanceId,
325 }).pipe(Effect.as(undefined)),
326 ThreadLaunchError: (error) =>
327 Effect.logWarning("Failed to launch bootstrap thread", {
328 projectId: project.id,
329 operation: error.operation,
330 }).pipe(Effect.as(undefined)),
331 }),
332 );
333 bootstrapProjectId = project.id;
334 bootstrapThreadId = launched?.threadId;
335 } else {
336 bootstrapProjectId = project.id;
337 bootstrapThreadId = existingThread.id;
338 }
339 }
340​
341 return {
342 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
343 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
344 } satisfies AutoBootstrapWelcomeTargets;
345});
346​
347const resolveStartupBrowserTarget = Effect.gen(function* () {
348 const serverConfig = yield* ServerConfig.ServerConfig;
349 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
350 const baseTarget =
351 serverConfig.devUrl?.toString() ?? resolveLocalOrigin(serverConfig.host, serverConfig.port);
352 return serverConfig.mode === "desktop"
353 ? baseTarget
354 : yield* serverAuth.issueStartupPairingUrl(baseTarget);
355});
356​
357/** Prints the one-time admin pairing URL to stdout only; logger records reach trace files and collectors. */
358export const announceStartupPairingUrl = (pairingUrl: string) =>
359 Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe(
360 Effect.andThen(Console.log(` pairingUrl: ${pairingUrl}`)),
361 );
362​
363// Pairing tokens belong only in announceStartupPairingUrl's stdout output.
364export const logBrowserAutoOpenUnavailable = Effect.logInfo("browser auto-open unavailable", {
365 hint: "Open the pairing URL above in your browser.",
366});
367​
368export const maybeOpenBrowser = Effect.fn("serverRuntimeStartup.maybeOpenBrowser")(function* (
369 target: string,
370) {
371 const serverConfig = yield* ServerConfig.ServerConfig;
372 if (serverConfig.noBrowser) {
373 return;
374 }
375 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
376​
377 yield* externalLauncher.launchBrowser(target).pipe(
378 // The target carries the pairing token, and a failed launch records its
379 // command line on the span, so this call stays out of traces.
380 Effect.withTracerEnabled(false),
381 Effect.catch(() => logBrowserAutoOpenUnavailable),
382 );
383});
384​
385const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
386 effect.pipe(
387 // Use span attributes; annotations would follow long-lived forked fibers for the server's lifetime.
388 Effect.withSpan(`server.startup.${phase}`, { attributes: { "startup.phase": phase } }),
389 );
390​
391interface StartupOptions {
392 readonly activate?: Effect.Effect<void>;
393 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
394 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
396​
397export const startEffectWorkerWithRelay = Effect.fn(
398 "ServerRuntimeStartup.startEffectWorkerWithRelay",
399)(function* <WorkerContext, RelayContext>(input: {
400 readonly runWorker: Effect.Effect<void, never, WorkerContext>;
401 readonly startRelay: Effect.Effect<void, never, RelayContext>;
402 readonly workerFiberRef: Ref.Ref<Fiber.Fiber<void, never> | null>;
403}) {
404 const workerFiber = yield* forkParkedFiber(input.runWorker);
405 yield* Ref.set(input.workerFiberRef, workerFiber);
406 yield* input.startRelay.pipe(
407 Effect.onExit((exit) => {
408 if (Exit.isSuccess(exit)) {
409 return Effect.void;
410 }
411 return Ref.getAndSet(input.workerFiberRef, null).pipe(
412 Effect.flatMap((ownedWorkerFiber) =>
413 ownedWorkerFiber === null
414 ? Effect.void
415 : Fiber.interrupt(ownedWorkerFiber).pipe(Effect.asVoid),
416 ),
417 );
418 }),
419 );
420});
421​
422const runOrderedV2StartupPhases = Effect.fn("serverRuntimeStartup.runOrderedV2StartupPhases")(
423 function* <
424 Import,
425 Recovery,
426 Bootstrap,
427 ImportError,
428 RecoveryError,
429 DelegationError,
430 WorkerError,
431 BootstrapError,
432 ImportContext,
433 RecoveryContext,
434 DelegationContext,
435 WorkerContext,
436 BootstrapContext,
437 >(input: {
438 readonly importLegacyShells: Effect.Effect<Import, ImportError, ImportContext>;
439 readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
440 readonly recoverDelegatedTasks: Effect.Effect<void, DelegationError, DelegationContext>;
441 readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
442 readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
443 }) {
444 yield* input.importLegacyShells;
445 const recovery = yield* input.recover;
446 yield* input.recoverDelegatedTasks;
447 yield* input.startEffectWorker;
448 const bootstrap = yield* input.autoBootstrap;
449 return { recovery, bootstrap } as const;
450 },
451);
452​
453const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: StartupOptions) {
454 const serverConfig = yield* ServerConfig.ServerConfig;
455 const keybindings = yield* Keybindings.Keybindings;
456 const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
457 const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
458 const orchestrator = yield* Orchestrator.OrchestratorV2;
459 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
460 const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
461 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
462 const serverSettings = yield* ServerSettings.ServerSettingsService;
463 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
464 const random = yield* SecureRandom.SecureRandom;
465 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
466​
467 const commandGate = yield* makeCommandGate;
468 const httpListening = yield* Deferred.make<void>();
469 const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
470​
471 yield* Effect.addFinalizer(() =>
472 Effect.gen(function* () {
473 yield* commandGate.failCommandReady(
474 new ServerRuntimeStartupError({
475 mode: serverConfig.mode,
476 host: serverConfig.host ?? null,
477 port: serverConfig.port,
478 cause: "Server runtime is shutting down.",
479 }),
480 );
481 const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
482 if (workerFiber !== null) {
483 yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
484 }
485 yield* providerRuntimeRecovery.prepareForShutdown.pipe(
486 Effect.ensuring(providerSessions.shutdown),
487 );
488 const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
489 yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
490 }).pipe(
491 Effect.withSpan("server.shutdown"),
492 Effect.catchCause((cause) =>
493 Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
494 cause: Cause.pretty(cause),
495 }),
496 ),
497 ),
498 );
499​
500 const startup = Effect.gen(function* () {
501 yield* Effect.logDebug("startup phase: starting keybindings runtime");
502 yield* runStartupPhase(
503 "keybindings.start",
504 keybindings.start.pipe(
505 Effect.catch((error) =>
506 Effect.logWarning("failed to start keybindings runtime", {
507 path: error.configPath,
508 detail: error.detail,
509 cause: error.cause,
510 }),
511 ),
512 ),
513 );
514​
515 yield* Effect.logDebug("startup phase: starting server settings runtime");
516 yield* runStartupPhase(
517 "settings.start",
518 serverSettings.start.pipe(
519 Effect.catch((error) =>
520 Effect.logWarning("failed to start server settings runtime", {
521 path: error.settingsPath,
522 operation: error.operation,
523 providerInstanceId: error.providerInstanceId,
524 environmentVariable: error.environmentVariable,
525 cause: error.cause,
526 }),
527 ),
528 ),
529 );
530​
531 const welcomeBase = yield* resolveWelcomeBase;
532 const environment = yield* serverEnvironment.getDescriptor;
533 const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
534 if (legacyMigrationThreadCount > 0) {
535 yield* lifecycleEvents.publish({
536 version: 1,
537 type: "legacyThreadMigration",
538 payload: {
539 status: "running",
540 totalThreadCount: legacyMigrationThreadCount,
541 },
542 });
543 }
544 const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
545 importLegacyShells: runStartupPhase(
546 "orchestration-v2.legacy-v1.import-shells",
547 legacyV1ThreadImporter.reconcileShells.pipe(
548 Effect.tap((summary) =>
549 summary.importedThreadCount === 0
550 ? Effect.void
551 : Effect.logInfo("Imported legacy v1 thread shells", summary),
552 ),
553 ),
554 ),
555 recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
556 recoverDelegatedTasks: runStartupPhase(
557 "orchestration-v2.delegated-tasks.recover",
558 orchestrator.recoverDelegatedTasks,
559 ),
560 startEffectWorker: runStartupPhase(
561 "orchestration-v2.effect-worker.start",
562 startEffectWorkerWithRelay({
563 runWorker: EffectWorker.runDaemon,
564 startRelay: agentAwarenessRelay.start(),
565 workerFiberRef: effectWorkerFiber,
566 }),
567 ),
568 autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
569 ? runStartupPhase(
570 "welcome.autobootstrap",
571 resolveAutoBootstrapWelcomeTargets.pipe(
572 Effect.provideService(SecureRandom.SecureRandom, random),
573 ),
574 )
575 : Effect.succeed({})
576 ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
577 });
578 yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
579 // Runs after activation: the status check fetches every enabled project's
580 // remote, and awaiting it here held command readiness for that long.
581 const projectStore = yield* ProjectStore.ProjectStoreV2;
582 const automaticFetchInterval = yield* VcsAutomaticFetchInterval;
583 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
584 const autoPullEnabledProjects = Effect.gen(function* () {
585 const projects = yield* projectStore.listShells();
586 const settings = yield* serverSettings.getSettings;
587 yield* autoPullProjects(projects, settings);
588 }).pipe(
589 Effect.catch((cause) =>
590 Effect.logWarning("Failed to load projects for automatic pull", { cause }),
591 ),
592 );
593 // Status subscriptions only poll roots someone views, so unviewed roots are pulled here.
594 const autoPullOnFetchInterval = Effect.gen(function* () {
595 const interval = yield* automaticFetchInterval;
596 yield* Effect.sleep(
597 Duration.isZero(interval) ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL : interval,
598 );
599 if (!Duration.isZero(interval) && (yield* backgroundPolicy.shouldRunHostWork)) {
600 yield* autoPullEnabledProjects;
601 }
602 }).pipe(Effect.forever);
603 yield* runStartupPhase("projects.auto-pull", autoPullEnabledProjects).pipe(
604 Effect.andThen(autoPullOnFetchInterval),
605 forkParked,
606 );
607​
608 const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
609 Effect.tap((summary) =>
610 summary.importedThreadCount === 0
611 ? Effect.void
612 : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
613 ),
614 );
615 yield* (
616 legacyMigrationThreadCount > 0
617 ? importPendingTranscripts.pipe(
618 Effect.tap(() =>
619 lifecycleEvents.publish({
620 version: 1,
621 type: "legacyThreadMigration",
622 payload: {
623 status: "complete",
624 totalThreadCount: legacyMigrationThreadCount,
625 },
626 }),
627 ),
628 )
629 : importPendingTranscripts
630 ).pipe(forkParked);
631​
632 yield* forkParked(
633 Effect.gen(function* () {
634 yield* Effect.logDebug("startup phase: recording startup heartbeat");
635 yield* recordStartupHeartbeat.pipe(
636 Effect.withSpan("server.startup.heartbeat.record", {
637 attributes: { "startup.phase": "heartbeat.record" },
638 }),
639 Effect.ignoreCause({ log: true }),
640 );
641 if (serverConfig.startupPresentation === "headless") {
642 yield* Effect.logDebug("startup phase: headless access info");
643 const output = yield* headlessServeOutput({ serviceManaged: launcher.managed });
644 yield* runStartupPhase("headless.output", Console.log(output));
645 } else {
646 yield* Effect.logDebug("startup phase: browser open check");
647 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
648 if (serverConfig.mode !== "desktop") {
649 yield* announceStartupPairingUrl(startupBrowserTarget);
650 }
651 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
652 }
653 }),
654 );
655​
656 yield* Effect.logDebug("startup phase: waiting for http listener");
657 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
658 yield* runStartupPhase("auxiliary-roots.parked", options?.awaitAuxiliaryParked ?? Effect.void);
659​
660 const updateOutcome = yield* launcher.prepareTrial({ baseDir: serverConfig.baseDir });
661​
662 yield* Effect.logDebug("startup phase: publishing welcome event", {
663 environmentId: environment.environmentId,
664 cwd: welcomeBase.cwd,
665 projectName: welcomeBase.projectName,
666 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
667 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
668 });
669 yield* runStartupPhase(
670 "welcome.publish",
671 lifecycleEvents.publish({
672 version: 1,
673 type: "welcome",
674 payload: {
675 environment,
676 ...welcomeBase,
677 ...bootstrapTargets,
678 },
679 }),
680 );
681​
682 yield* options?.activate ?? Effect.void;
683 yield* Effect.logDebug("Accepting commands");
684 yield* commandGate.signalCommandReady;
685 yield* Effect.logDebug("startup phase: publishing ready event");
686 yield* runStartupPhase(
687 "ready.publish",
688 lifecycleEvents.publish({
689 version: 1,
690 type: "ready",
691 payload: {
692 at: DateTime.formatIso(yield* DateTime.now),
693 environment,
694 ...(updateOutcome === undefined ? {} : { updateOutcome }),
695 },
696 }),
697 );
698 yield* Effect.logDebug("startup phase: complete");
699 yield* flushCompileCache;
700 }).pipe(
701 Effect.withSpan("server.startup", {
702 kind: "server",
703 root: true,
704 attributes: {
705 "server.mode": serverConfig.mode,
706 "server.port": serverConfig.port,
707 "server.host": serverConfig.host ?? "default",
708 },
709 }),
710 );
711​
712 yield* Effect.forkScoped(
713 Effect.exit(startup).pipe(
714 Effect.flatMap((startupExit) => {
715 if (Exit.isSuccess(startupExit)) return Effect.void;
716 const error = new ServerRuntimeStartupError({
717 mode: serverConfig.mode,
718 host: serverConfig.host ?? null,
719 port: serverConfig.port,
720 cause: startupExit.cause,
721 });
722 return Effect.logError("server runtime startup failed", {
723 cause: Cause.pretty(startupExit.cause),
724 }).pipe(
725 Effect.andThen(commandGate.failCommandReady(error)),
726 Effect.andThen(options?.abort?.(error) ?? Effect.void),
727 );
728 }),
729 ),
730 );
731​
732 return {
733 awaitCommandReady: commandGate.awaitCommandReady,
734 markHttpListening: Deferred.succeed(httpListening, undefined),
735 enqueueCommand: commandGate.enqueueCommand,
736 } satisfies ServerRuntimeStartup["Service"];
737});
738​
739export const layerWithOptions = (options?: StartupOptions) =>
740 Layer.effect(ServerRuntimeStartup, make(options));