Open History to see the last commit
1import {
2 CommandId,
3 DEFAULT_MODEL,
4 DEFAULT_PROVIDER_INTERACTION_MODE,
5 type ModelSelection,
6 type Project,
7 ProjectId,
8 ProviderInstanceId,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Console from "effect/Console";
13import * as Context from "effect/Context";
14import * as Crypto from "effect/Crypto";
15import * as DateTime from "effect/DateTime";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Exit from "effect/Exit";
19import * as Fiber from "effect/Fiber";
20import * as Layer from "effect/Layer";
21import * as Path from "effect/Path";
22import * as Queue from "effect/Queue";
23import * as Ref from "effect/Ref";
24import * as Schema from "effect/Schema";
25
26import * as ServerConfig from "./config.ts";
27import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
28import * as Keybindings from "./keybindings.ts";
29import * as ExternalLauncher from "./process/externalLauncher.ts";
30import * as EffectWorker from "./orchestration-v2/EffectWorker.ts";
31import * as LegacyV1ThreadImporter from "./orchestration-v2/LegacyV1ThreadImporter.ts";
32import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
33import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts";
34import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
35import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts";
36import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
37import * as ProjectService from "./project/ProjectService.ts";
38import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
39import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
40import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
41import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
42import * as ServerSettings from "./serverSettings.ts";
43import { forkParked, forkParkedFiber } from "./serverActivation.ts";
44import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
45import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
46import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
47import {
48 formatHeadlessServeOutput,
49 formatHostForUrl,
50 isWildcardHost,
51 issueHeadlessServeAccessInfo,
52} from "./startupAccess.ts";
53
54export class ServerRuntimeStartupError extends Schema.TaggedErrorClass<ServerRuntimeStartupError>()(
55 "ServerRuntimeStartupError",
56 {
57 mode: ServerConfig.RuntimeMode,
58 host: Schema.NullOr(Schema.String),
59 port: Schema.Number,
60 cause: Schema.Defect(),
61 },
62) {
63 override get message(): string {
64 return "Server runtime startup failed before command readiness.";
65 }
66}
67
68export class ServerRuntimeStartup extends Context.Service<
69 ServerRuntimeStartup,
70 {
71 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
72 readonly markHttpListening: Effect.Effect<void>;
73 readonly enqueueCommand: <A, E>(
74 effect: Effect.Effect<A, E>,
75 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
76 }
77>()("t3/serverRuntimeStartup") {}
78
79interface QueuedCommand {
80 readonly run: Effect.Effect<void, never>;
81}
82
83type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError;
84
85interface CommandGate {
86 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
87 readonly signalCommandReady: Effect.Effect<void>;
88 readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
89 readonly enqueueCommand: <A, E>(
90 effect: Effect.Effect<A, E>,
91 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
92}
93
94const settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>
95 Exit.isSuccess(exit)
96 ? Deferred.succeed(deferred, exit.value)
97 : Deferred.failCause(deferred, exit.cause);
98
99export const makeCommandGate = Effect.gen(function* () {
100 const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
101 const commandQueue = yield* Queue.unbounded<QueuedCommand>();
102 const commandReadinessState = yield* Ref.make<CommandReadinessState>("pending");
103
104 const commandWorker = Effect.forever(
105 Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),
106 );
107 yield* Effect.forkScoped(commandWorker);
108
109 return {
110 awaitCommandReady: Deferred.await(commandReady),
111 signalCommandReady: Effect.gen(function* () {
112 yield* Ref.set(commandReadinessState, "ready");
113 yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
114 }),
115 failCommandReady: (error) =>
116 Effect.gen(function* () {
117 yield* Ref.set(commandReadinessState, error);
118 yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
119 }),
120 enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>
121 Effect.gen(function* () {
122 const readinessState = yield* Ref.get(commandReadinessState);
123 if (readinessState === "ready") {
124 return yield* effect;
125 }
126 if (readinessState !== "pending") {
127 return yield* readinessState;
128 }
129
130 const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
131 yield* Queue.offer(commandQueue, {
132 run: Deferred.await(commandReady).pipe(
133 Effect.flatMap(() => effect),
134 Effect.exit,
135 Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
136 ),
137 });
138 return yield* Deferred.await(result);
139 }),
140 } satisfies CommandGate;
141});
142
143export const recordStartupHeartbeat = Effect.gen(function* () {
144 const analytics = yield* AnalyticsService.AnalyticsService;
145 const projects = yield* ProjectService.ProjectService;
146 const threads = yield* ThreadManagement.ThreadManagementService;
147
148 const { threadCount, projectCount } = yield* Effect.all({
149 projects: projects.snapshot,
150 threads: threads.getShellSnapshot(),
151 }).pipe(
152 Effect.map(({ projects: projectSnapshot, threads: shellSnapshot }) => ({
153 projectCount: projectSnapshot.projects.length,
154 threadCount: shellSnapshot.threads.length + shellSnapshot.archivedThreads.length,
155 })),
156 Effect.catch((cause) =>
157 Effect.logWarning("failed to gather V2 startup counts for telemetry", {
158 cause,
159 }).pipe(
160 Effect.as({
161 threadCount: 0,
162 projectCount: 0,
163 }),
164 ),
165 ),
166 );
167
168 yield* analytics.record("server.boot.heartbeat", {
169 threadCount,
170 projectCount,
171 });
172});
173
174export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(
175 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
176 Effect.withSpan("server.startup.heartbeat.record"),
177 Effect.ignoreCause({ log: true }),
178 Effect.forkScoped,
179 Effect.asVoid,
180);
181
182export const getAutoBootstrapThreadModelSelection = (): ModelSelection => ({
183 instanceId: ProviderInstanceId.make("codex"),
184 model: DEFAULT_MODEL,
185});
186
187interface AutoBootstrapWelcomeTargets {
188 readonly bootstrapProjectId?: ProjectId;
189 readonly bootstrapThreadId?: ThreadId;
190}
191
192export const autoPullProjects = Effect.fn("autoPullProjects")(function* (
193 projects: ReadonlyArray<Pick<Project, "workspaceRoot" | "autoPull">>,
194) {
195 const git = yield* GitVcsDriver.GitVcsDriver;
196 const workspaceRoots = [
197 ...new Set(
198 projects
199 .filter((project) => project.autoPull === true)
200 .map((project) => project.workspaceRoot),
201 ),
202 ];
203
204 yield* Effect.forEach(
205 workspaceRoots,
206 (cwd) =>
207 Effect.gen(function* () {
208 const status = yield* git.statusDetails(cwd);
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
251export 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
262export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
263 const crypto = yield* Crypto.Crypto;
264 const randomUUID = crypto.randomUUIDv4;
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 // Project creation has no user model choice; only the bootstrap thread
276 // gets an automatic selection, and an explicit project default wins.
277 const threadModelSelection = getAutoBootstrapThreadModelSelection();
278 const { project } = yield* projects.bootstrap({
279 commandId: CommandId.make(yield* randomUUID),
280 projectId: ProjectId.make(yield* randomUUID),
281 title: path.basename(serverConfig.cwd) || "project",
282 workspaceRoot: serverConfig.cwd,
283 });
284 const shell = yield* threads.getShellSnapshot();
285 const existingThread = shell.threads.find(
286 (thread) =>
287 thread.projectId === project.id && thread.lineage.relationshipToParent !== "subagent",
288 );
289 if (existingThread === undefined) {
290 const launched = yield* threadLaunch.launch({
291 commandId: CommandId.make(yield* randomUUID),
292 projectId: project.id,
293 title: "New thread",
294 modelSelection: project.defaultModelSelection ?? threadModelSelection,
295 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
296 runtimeMode: "full-access",
297 workspaceStrategy: { type: "root" },
298 createdBy: "system",
299 creationSource: "server",
300 });
301 bootstrapProjectId = project.id;
302 bootstrapThreadId = launched.threadId;
303 } else {
304 bootstrapProjectId = project.id;
305 bootstrapThreadId = existingThread.id;
306 }
307 }
308
309 return {
310 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
311 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
312 } satisfies AutoBootstrapWelcomeTargets;
313});
314
315const resolveStartupBrowserTarget = Effect.gen(function* () {
316 const serverConfig = yield* ServerConfig.ServerConfig;
317 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
318 const localUrl = `http://localhost:${serverConfig.port}`;
319 const bindUrl =
320 serverConfig.host && !isWildcardHost(serverConfig.host)
321 ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
322 : localUrl;
323 const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
324 return yield* Effect.succeed(serverConfig.mode === "desktop" ? baseTarget : undefined).pipe(
325 Effect.flatMap((target) =>
326 target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget),
327 ),
328 );
329});
330
331const maybeOpenBrowser = (target: string) =>
332 Effect.gen(function* () {
333 const serverConfig = yield* ServerConfig.ServerConfig;
334 if (serverConfig.noBrowser) {
335 return;
336 }
337 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
338
339 yield* externalLauncher.launchBrowser(target).pipe(
340 Effect.catch(() =>
341 Effect.logInfo("browser auto-open unavailable", {
342 hint: `Open ${target} in your browser.`,
343 }),
344 ),
345 );
346 });
347
348const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
349 effect.pipe(
350 Effect.annotateSpans({ "startup.phase": phase }),
351 Effect.withSpan(`server.startup.${phase}`),
352 );
353
354interface StartupOptions {
355 readonly activate?: Effect.Effect<void>;
356 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
357 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
358}
359
360export const startEffectWorkerWithRelay = Effect.fn(
361 "ServerRuntimeStartup.startEffectWorkerWithRelay",
362)(function* <WorkerContext, RelayContext>(input: {
363 readonly runWorker: Effect.Effect<void, never, WorkerContext>;
364 readonly startRelay: Effect.Effect<void, never, RelayContext>;
365 readonly workerFiberRef: Ref.Ref<Fiber.Fiber<void, never> | null>;
366}) {
367 const workerFiber = yield* forkParkedFiber(input.runWorker);
368 yield* Ref.set(input.workerFiberRef, workerFiber);
369 yield* input.startRelay.pipe(
370 Effect.onExit((exit) => {
371 if (Exit.isSuccess(exit)) {
372 return Effect.void;
373 }
374 return Ref.getAndSet(input.workerFiberRef, null).pipe(
375 Effect.flatMap((ownedWorkerFiber) =>
376 ownedWorkerFiber === null
377 ? Effect.void
378 : Fiber.interrupt(ownedWorkerFiber).pipe(Effect.asVoid),
379 ),
380 );
381 }),
382 );
383});
384
385export function runOrderedV2StartupPhases<
386 Import,
387 Verification extends { readonly valid: boolean },
388 RebuildVerification extends { readonly valid: boolean },
389 Recovery,
390 Bootstrap,
391 ImportError,
392 VerifyError,
393 RebuildError,
394 RecoveryError,
395 WorkerError,
396 BootstrapError,
397 ImportContext,
398 VerifyContext,
399 RebuildContext,
400 RecoveryContext,
401 WorkerContext,
402 BootstrapContext,
403>(input: {
404 readonly importLegacyShells: Effect.Effect<Import, ImportError, ImportContext>;
405 readonly verify: Effect.Effect<Verification, VerifyError, VerifyContext>;
406 readonly rebuild: Effect.Effect<RebuildVerification, RebuildError, RebuildContext>;
407 readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
408 readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
409 readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
410}) {
411 return Effect.gen(function* () {
412 yield* input.importLegacyShells;
413 const verification = yield* input.verify;
414 if (!verification.valid) {
415 const rebuilt = yield* input.rebuild;
416 if (!rebuilt.valid) {
417 return yield* Effect.die(
418 new Error("V2 orchestration projection rebuild did not produce a valid projection."),
419 );
420 }
421 }
422 const recovery = yield* input.recover;
423 yield* input.startEffectWorker;
424 const bootstrap = yield* input.autoBootstrap;
425 return { recovery, bootstrap } as const;
426 });
427}
428
429export const make = (options?: StartupOptions) =>
430 Effect.gen(function* () {
431 const serverConfig = yield* ServerConfig.ServerConfig;
432 const keybindings = yield* Keybindings.Keybindings;
433 const projectionMaintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
434 const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
435 const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
436 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
437 const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
438 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
439 const serverSettings = yield* ServerSettings.ServerSettingsService;
440 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
441 const crypto = yield* Crypto.Crypto;
442 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
443
444 const commandGate = yield* makeCommandGate;
445 const httpListening = yield* Deferred.make<void>();
446 const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
447
448 yield* Effect.addFinalizer(() =>
449 Effect.gen(function* () {
450 yield* commandGate.failCommandReady(
451 new ServerRuntimeStartupError({
452 mode: serverConfig.mode,
453 host: serverConfig.host ?? null,
454 port: serverConfig.port,
455 cause: "Server runtime is shutting down.",
456 }),
457 );
458 const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
459 if (workerFiber !== null) {
460 yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
461 }
462 yield* providerRuntimeRecovery.prepareForShutdown.pipe(
463 Effect.ensuring(providerSessions.shutdown),
464 );
465 const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
466 yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
467 }).pipe(
468 Effect.catchCause((cause) =>
469 Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
470 cause: Cause.pretty(cause),
471 }),
472 ),
473 ),
474 );
475
476 const startup = Effect.gen(function* () {
477 yield* Effect.logDebug("startup phase: starting keybindings runtime");
478 yield* runStartupPhase(
479 "keybindings.start",
480 keybindings.start.pipe(
481 Effect.catch((error) =>
482 Effect.logWarning("failed to start keybindings runtime", {
483 path: error.configPath,
484 detail: error.detail,
485 cause: error.cause,
486 }),
487 ),
488 ),
489 );
490
491 yield* Effect.logDebug("startup phase: starting server settings runtime");
492 yield* runStartupPhase(
493 "settings.start",
494 serverSettings.start.pipe(
495 Effect.catch((error) =>
496 Effect.logWarning("failed to start server settings runtime", {
497 path: error.settingsPath,
498 operation: error.operation,
499 providerInstanceId: error.providerInstanceId,
500 environmentVariable: error.environmentVariable,
501 cause: error.cause,
502 }),
503 ),
504 ),
505 );
506
507 const welcomeBase = yield* resolveWelcomeBase;
508 const environment = yield* serverEnvironment.getDescriptor;
509 const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
510 if (legacyMigrationThreadCount > 0) {
511 yield* lifecycleEvents.publish({
512 version: 1,
513 type: "legacyThreadMigration",
514 payload: {
515 status: "running",
516 totalThreadCount: legacyMigrationThreadCount,
517 },
518 });
519 }
520 const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
521 importLegacyShells: runStartupPhase(
522 "orchestration-v2.legacy-v1.import-shells",
523 legacyV1ThreadImporter.reconcileShells.pipe(
524 Effect.tap((summary) =>
525 summary.importedThreadCount === 0
526 ? Effect.void
527 : Effect.logInfo("Imported legacy v1 thread shells", summary),
528 ),
529 ),
530 ),
531 verify: runStartupPhase(
532 "orchestration-v2.projections.verify",
533 projectionMaintenance.verify.pipe(
534 Effect.tap((verification) =>
535 verification.valid
536 ? Effect.void
537 : Effect.logWarning(
538 "V2 orchestration projection metadata or structure is invalid; rebuilding",
539 {
540 expectedSequence: verification.expectedSequence,
541 projectionSequence: verification.projectionSequence,
542 schemaVersion: verification.schemaVersion,
543 missingThreadCount: verification.missingThreadIds.length,
544 unexpectedThreadCount: verification.unexpectedThreadIds.length,
545 unreadableThreadCount: verification.unreadableThreadIds.length,
546 },
547 ),
548 ),
549 ),
550 ),
551 rebuild: runStartupPhase(
552 "orchestration-v2.projections.rebuild",
553 projectionMaintenance.rebuild,
554 ),
555 recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
556 startEffectWorker: runStartupPhase(
557 "orchestration-v2.effect-worker.start",
558 startEffectWorkerWithRelay({
559 runWorker: EffectWorker.runDaemon,
560 startRelay: agentAwarenessRelay.start(),
561 workerFiberRef: effectWorkerFiber,
562 }),
563 ),
564 autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
565 ? runStartupPhase(
566 "welcome.autobootstrap",
567 resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),
568 )
569 : Effect.succeed({})
570 ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
571 });
572 yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
573 yield* runStartupPhase(
574 "projects.auto-pull",
575 Effect.gen(function* () {
576 const snapshots = yield* ProjectionSnapshotQuery;
577 const projects = yield* snapshots.getProjectShellsWithoutEnrichment();
578 yield* autoPullProjects(projects);
579 }),
580 );
581
582 const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
583 Effect.tap((summary) =>
584 summary.importedThreadCount === 0
585 ? Effect.void
586 : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
587 ),
588 );
589 yield* (
590 legacyMigrationThreadCount > 0
591 ? importPendingTranscripts.pipe(
592 Effect.tap(() =>
593 lifecycleEvents.publish({
594 version: 1,
595 type: "legacyThreadMigration",
596 payload: {
597 status: "complete",
598 totalThreadCount: legacyMigrationThreadCount,
599 },
600 }),
601 ),
602 )
603 : importPendingTranscripts
604 ).pipe(forkParked);
605
606 // Off the startup path: the first run after an upgrade deletes the whole
607 // superseded-event and legacy-v1 backlog (potentially millions of rows,
608 // paced in small batches), and nothing at boot depends on it.
609 yield* projectionMaintenance.compactEventStore.pipe(
610 Effect.tap((summary) =>
611 summary.deletedEventCount === 0 && summary.deletedReceiptCount === 0
612 ? Effect.void
613 : Effect.logInfo("Compacted orchestration event store", summary),
614 ),
615 Effect.tap((summary) =>
616 // Freed pages are reused, so the file stops growing regardless; only
617 // an offline VACUUM shrinks it, which is not safe to run on the
618 // synchronous sqlite connection while serving.
619 summary.reclaimableBytes >= 512 * 1024 * 1024
620 ? Effect.logInfo(
621 "state.sqlite has substantial reclaimable free space; an offline VACUUM would shrink the file",
622 { reclaimableBytes: summary.reclaimableBytes },
623 )
624 : Effect.void,
625 ),
626 Effect.catch((cause) => Effect.logWarning("Unable to compact the event store", { cause })),
627 forkParked,
628 );
629
630 yield* forkParked(
631 Effect.gen(function* () {
632 yield* Effect.logDebug("startup phase: recording startup heartbeat");
633 yield* recordStartupHeartbeat.pipe(
634 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
635 Effect.withSpan("server.startup.heartbeat.record"),
636 Effect.ignoreCause({ log: true }),
637 );
638 if (serverConfig.startupPresentation === "headless") {
639 yield* Effect.logDebug("startup phase: headless access info");
640 const accessInfo = yield* issueHeadlessServeAccessInfo();
641 yield* runStartupPhase(
642 "headless.output",
643 Console.log(formatHeadlessServeOutput(accessInfo)),
644 );
645 } else {
646 yield* Effect.logDebug("startup phase: browser open check");
647 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
648 if (serverConfig.mode !== "desktop") {
649 yield* Effect.logInfo(
650 "Authentication required. Open T3 Code using the pairing URL.",
651 ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
652 }
653 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
654 }
655 }),
656 );
657
658 yield* Effect.logDebug("startup phase: waiting for http listener");
659 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
660 yield* runStartupPhase(
661 "auxiliary-roots.parked",
662 options?.awaitAuxiliaryParked ?? Effect.void,
663 );
664
665 const updateOutcome = yield* launcher.prepareTrial;
666
667 yield* Effect.logDebug("startup phase: publishing welcome event", {
668 environmentId: environment.environmentId,
669 cwd: welcomeBase.cwd,
670 projectName: welcomeBase.projectName,
671 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
672 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
673 });
674 yield* runStartupPhase(
675 "welcome.publish",
676 lifecycleEvents.publish({
677 version: 1,
678 type: "welcome",
679 payload: {
680 environment,
681 ...welcomeBase,
682 ...bootstrapTargets,
683 },
684 }),
685 );
686
687 yield* options?.activate ?? Effect.void;
688 yield* Effect.logDebug("Accepting commands");
689 yield* commandGate.signalCommandReady;
690 yield* Effect.logDebug("startup phase: publishing ready event");
691 yield* runStartupPhase(
692 "ready.publish",
693 lifecycleEvents.publish({
694 version: 1,
695 type: "ready",
696 payload: {
697 at: DateTime.formatIso(yield* DateTime.now),
698 environment,
699 ...(updateOutcome === undefined ? {} : { updateOutcome }),
700 },
701 }),
702 );
703 yield* Effect.logDebug("startup phase: complete");
704 }).pipe(
705 Effect.annotateSpans({
706 "server.mode": serverConfig.mode,
707 "server.port": serverConfig.port,
708 "server.host": serverConfig.host ?? "default",
709 }),
710 Effect.withSpan("server.startup", { kind: "server", root: true }),
711 );
712
713 yield* Effect.forkScoped(
714 Effect.exit(startup).pipe(
715 Effect.flatMap((startupExit) => {
716 if (Exit.isSuccess(startupExit)) return Effect.void;
717 const error = new ServerRuntimeStartupError({
718 mode: serverConfig.mode,
719 host: serverConfig.host ?? null,
720 port: serverConfig.port,
721 cause: startupExit.cause,
722 });
723 return Effect.logError("server runtime startup failed", {
724 cause: Cause.pretty(startupExit.cause),
725 }).pipe(
726 Effect.andThen(commandGate.failCommandReady(error)),
727 Effect.andThen(options?.abort?.(error) ?? Effect.void),
728 );
729 }),
730 ),
731 );
732
733 return {
734 awaitCommandReady: commandGate.awaitCommandReady,
735 markHttpListening: Deferred.succeed(httpListening, undefined),
736 enqueueCommand: commandGate.enqueueCommand,
737 } satisfies ServerRuntimeStartup["Service"];
738 });
739
740export const layerWithOptions = (options?: StartupOptions) =>
741 Layer.effect(ServerRuntimeStartup, make(options));
742
743export const layer = layerWithOptions();