The best way to control Claude Code, Codex and more from any computer or phone

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