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