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

serverRuntimeStartup.ts

541 lines19.6 KB

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 Keybindings from "./keybindings.ts";
27import * as ExternalLauncher from "./process/externalLauncher.ts";
28import * as EffectWorker from "./orchestration-v2/EffectWorker.ts";
29import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
30import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts";
31import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
32import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts";
33import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
34import * as ProjectService from "./project/ProjectService.ts";
35import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
36import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
37import * as ServerSettings from "./serverSettings.ts";
38import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
39import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
40import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
41import {
42 formatHeadlessServeOutput,
43 formatHostForUrl,
44 isWildcardHost,
45 issueHeadlessServeAccessInfo,
46} from "./startupAccess.ts";
47​
48export class ServerRuntimeStartupError extends Schema.TaggedErrorClass<ServerRuntimeStartupError>()(
49 "ServerRuntimeStartupError",
50 {
51 mode: ServerConfig.RuntimeMode,
52 host: Schema.NullOr(Schema.String),
53 port: Schema.Number,
54 cause: Schema.Defect(),
55 },
56) {
57 override get message(): string {
58 return "Server runtime startup failed before command readiness.";
59 }
61​
62export class ServerRuntimeStartup extends Context.Service<
63 ServerRuntimeStartup,
64 {
65 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
66 readonly markHttpListening: Effect.Effect<void>;
67 readonly enqueueCommand: <A, E>(
68 effect: Effect.Effect<A, E>,
69 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
70 }
71>()("t3/serverRuntimeStartup") {}
72​
73interface QueuedCommand {
74 readonly run: Effect.Effect<void, never>;
76​
77type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError;
78​
79interface CommandGate {
80 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
81 readonly signalCommandReady: Effect.Effect<void>;
82 readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
83 readonly enqueueCommand: <A, E>(
84 effect: Effect.Effect<A, E>,
85 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
87​
88const settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>
89 Exit.isSuccess(exit)
90 ? Deferred.succeed(deferred, exit.value)
91 : Deferred.failCause(deferred, exit.cause);
92​
93export const makeCommandGate = Effect.gen(function* () {
94 const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
95 const commandQueue = yield* Queue.unbounded<QueuedCommand>();
96 const commandReadinessState = yield* Ref.make<CommandReadinessState>("pending");
97​
98 const commandWorker = Effect.forever(
99 Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),
100 );
101 yield* Effect.forkScoped(commandWorker);
102​
103 return {
104 awaitCommandReady: Deferred.await(commandReady),
105 signalCommandReady: Effect.gen(function* () {
106 yield* Ref.set(commandReadinessState, "ready");
107 yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
108 }),
109 failCommandReady: (error) =>
110 Effect.gen(function* () {
111 yield* Ref.set(commandReadinessState, error);
112 yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
113 }),
114 enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>
115 Effect.gen(function* () {
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 } satisfies CommandGate;
135});
136​
137export const recordStartupHeartbeat = Effect.gen(function* () {
138 const analytics = yield* AnalyticsService.AnalyticsService;
139 const projects = yield* ProjectService.ProjectService;
140 const threads = yield* ThreadManagement.ThreadManagementService;
141​
142 const { threadCount, projectCount } = yield* Effect.all({
143 projects: projects.snapshot,
144 threads: threads.getShellSnapshot(),
145 }).pipe(
146 Effect.map(({ projects: projectSnapshot, threads: shellSnapshot }) => ({
147 projectCount: projectSnapshot.projects.length,
148 threadCount: shellSnapshot.threads.length + shellSnapshot.archivedThreads.length,
149 })),
150 Effect.catch((cause) =>
151 Effect.logWarning("failed to gather V2 startup counts for telemetry", {
152 cause,
153 }).pipe(
154 Effect.as({
155 threadCount: 0,
156 projectCount: 0,
157 }),
158 ),
159 ),
160 );
161​
162 yield* analytics.record("server.boot.heartbeat", {
163 threadCount,
164 projectCount,
165 });
166});
167​
168export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(
169 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
170 Effect.withSpan("server.startup.heartbeat.record"),
171 Effect.ignoreCause({ log: true }),
172 Effect.forkScoped,
173 Effect.asVoid,
174);
175​
176export const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({
177 instanceId: ProviderInstanceId.make("codex"),
178 model: DEFAULT_MODEL,
179});
180​
181interface AutoBootstrapWelcomeTargets {
182 readonly bootstrapProjectId?: ProjectId;
183 readonly bootstrapThreadId?: ThreadId;
185​
186export const resolveWelcomeBase = Effect.gen(function* () {
187 const serverConfig = yield* ServerConfig.ServerConfig;
188 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
189 const projectName = segments[segments.length - 1] ?? "project";
190​
191 return {
192 cwd: serverConfig.cwd,
193 projectName,
194 } as const;
195});
196​
197export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
198 const crypto = yield* Crypto.Crypto;
199 const randomUUID = crypto.randomUUIDv4;
200 const serverConfig = yield* ServerConfig.ServerConfig;
201 const projects = yield* ProjectService.ProjectService;
202 const threads = yield* ThreadManagement.ThreadManagementService;
203 const threadLaunch = yield* ThreadLaunch.ThreadLaunchService;
204 const path = yield* Path.Path;
205​
206 let bootstrapProjectId: ProjectId | undefined;
207 let bootstrapThreadId: ThreadId | undefined;
208​
209 if (serverConfig.autoBootstrapProjectFromCwd) {
210 const defaultModelSelection = getAutoBootstrapDefaultModelSelection();
211 const { project } = yield* projects.bootstrap({
212 commandId: CommandId.make(yield* randomUUID),
213 projectId: ProjectId.make(yield* randomUUID),
214 title: path.basename(serverConfig.cwd) || "project",
215 workspaceRoot: serverConfig.cwd,
216 defaultModelSelection,
217 });
218 const shell = yield* threads.getShellSnapshot();
219 const existingThread = shell.threads.find(
220 (thread) =>
221 thread.projectId === project.id && thread.lineage.relationshipToParent !== "subagent",
222 );
223 if (existingThread === undefined) {
224 const launched = yield* threadLaunch.launch({
225 commandId: CommandId.make(yield* randomUUID),
226 projectId: project.id,
227 title: "New thread",
228 modelSelection: project.defaultModelSelection ?? defaultModelSelection,
229 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
230 runtimeMode: "full-access",
231 workspaceStrategy: { type: "root" },
232 createdBy: "system",
233 creationSource: "server",
234 });
235 bootstrapProjectId = project.id;
236 bootstrapThreadId = launched.threadId;
237 } else {
238 bootstrapProjectId = project.id;
239 bootstrapThreadId = existingThread.id;
240 }
241 }
242​
243 return {
244 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
245 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
246 } satisfies AutoBootstrapWelcomeTargets;
247});
248​
249const resolveStartupBrowserTarget = Effect.gen(function* () {
250 const serverConfig = yield* ServerConfig.ServerConfig;
251 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
252 const localUrl = `http://localhost:${serverConfig.port}`;
253 const bindUrl =
254 serverConfig.host && !isWildcardHost(serverConfig.host)
255 ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
256 : localUrl;
257 const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
258 return yield* Effect.succeed(serverConfig.mode === "desktop" ? baseTarget : undefined).pipe(
259 Effect.flatMap((target) =>
260 target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget),
261 ),
262 );
263});
264​
265const maybeOpenBrowser = (target: string) =>
266 Effect.gen(function* () {
267 const serverConfig = yield* ServerConfig.ServerConfig;
268 if (serverConfig.noBrowser) {
269 return;
270 }
271 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
272​
273 yield* externalLauncher.launchBrowser(target).pipe(
274 Effect.catch(() =>
275 Effect.logInfo("browser auto-open unavailable", {
276 hint: `Open ${target} in your browser.`,
277 }),
278 ),
279 );
280 });
281​
282const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
283 effect.pipe(
284 Effect.annotateSpans({ "startup.phase": phase }),
285 Effect.withSpan(`server.startup.${phase}`),
286 );
287​
288export function runOrderedV2StartupPhases<
289 Verification extends { readonly valid: boolean },
290 RebuildVerification extends { readonly valid: boolean },
291 Recovery,
292 Bootstrap,
293 VerifyError,
294 RebuildError,
295 RecoveryError,
296 WorkerError,
297 BootstrapError,
298 VerifyContext,
299 RebuildContext,
300 RecoveryContext,
301 WorkerContext,
302 BootstrapContext,
303>(input: {
304 readonly verify: Effect.Effect<Verification, VerifyError, VerifyContext>;
305 readonly rebuild: Effect.Effect<RebuildVerification, RebuildError, RebuildContext>;
306 readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
307 readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
308 readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
309}) {
310 return Effect.gen(function* () {
311 const verification = yield* input.verify;
312 if (!verification.valid) {
313 const rebuilt = yield* input.rebuild;
314 if (!rebuilt.valid) {
315 return yield* Effect.die(
316 new Error("V2 orchestration projection rebuild did not produce a valid projection."),
317 );
318 }
319 }
320 const recovery = yield* input.recover;
321 yield* input.startEffectWorker;
322 const bootstrap = yield* input.autoBootstrap;
323 return { recovery, bootstrap } as const;
324 });
326​
327export const make = Effect.gen(function* () {
328 const serverConfig = yield* ServerConfig.ServerConfig;
329 const keybindings = yield* Keybindings.Keybindings;
330 const projectionMaintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
331 const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
332 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
333 const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
334 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
335 const serverSettings = yield* ServerSettings.ServerSettingsService;
336 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
337 const crypto = yield* Crypto.Crypto;
338​
339 const commandGate = yield* makeCommandGate;
340 const httpListening = yield* Deferred.make<void>();
341 const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
342​
343 yield* Effect.addFinalizer(() =>
344 Effect.gen(function* () {
345 yield* commandGate.failCommandReady(
346 new ServerRuntimeStartupError({
347 mode: serverConfig.mode,
348 host: serverConfig.host ?? null,
349 port: serverConfig.port,
350 cause: "Server runtime is shutting down.",
351 }),
352 );
353 const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
354 if (workerFiber !== null) {
355 yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
356 }
357 yield* providerSessions.shutdown;
358 const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
359 yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
360 }).pipe(
361 Effect.catchCause((cause) =>
362 Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
363 cause: Cause.pretty(cause),
364 }),
365 ),
366 ),
367 );
368​
369 const startup = Effect.gen(function* () {
370 yield* Effect.logDebug("startup phase: starting keybindings runtime");
371 yield* runStartupPhase(
372 "keybindings.start",
373 keybindings.start.pipe(
374 Effect.catch((error) =>
375 Effect.logWarning("failed to start keybindings runtime", {
376 path: error.configPath,
377 detail: error.detail,
378 cause: error.cause,
379 }),
380 ),
381 Effect.forkScoped,
382 ),
383 );
384​
385 yield* Effect.logDebug("startup phase: starting server settings runtime");
386 yield* runStartupPhase(
387 "settings.start",
388 serverSettings.start.pipe(
389 Effect.catch((error) =>
390 Effect.logWarning("failed to start server settings runtime", {
391 path: error.settingsPath,
392 operation: error.operation,
393 providerInstanceId: error.providerInstanceId,
394 environmentVariable: error.environmentVariable,
395 cause: error.cause,
396 }),
397 ),
398 Effect.forkScoped,
399 ),
400 );
401​
402 const welcomeBase = yield* resolveWelcomeBase;
403 const environment = yield* serverEnvironment.getDescriptor;
404 const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
405 verify: runStartupPhase(
406 "orchestration-v2.projections.verify",
407 projectionMaintenance.verify.pipe(
408 Effect.tap((verification) =>
409 verification.valid
410 ? Effect.void
411 : Effect.logWarning(
412 "V2 orchestration projection metadata or structure is invalid; rebuilding",
413 {
414 expectedSequence: verification.expectedSequence,
415 projectionSequence: verification.projectionSequence,
416 schemaVersion: verification.schemaVersion,
417 missingThreadCount: verification.missingThreadIds.length,
418 unexpectedThreadCount: verification.unexpectedThreadIds.length,
419 unreadableThreadCount: verification.unreadableThreadIds.length,
420 },
421 ),
422 ),
423 ),
424 ),
425 rebuild: runStartupPhase(
426 "orchestration-v2.projections.rebuild",
427 projectionMaintenance.rebuild,
428 ),
429 recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
430 startEffectWorker: runStartupPhase(
431 "orchestration-v2.effect-worker.start",
432 Effect.gen(function* () {
433 const workerFiber = yield* EffectWorker.runDaemon.pipe(Effect.forkScoped);
434 yield* Ref.set(effectWorkerFiber, workerFiber);
435 yield* agentAwarenessRelay.start();
436 }),
437 ),
438 autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
439 ? runStartupPhase(
440 "welcome.autobootstrap",
441 resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),
442 )
443 : Effect.succeed({})
444 ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
445 });
446 yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
447​
448 yield* Effect.logDebug("Accepting commands");
449 yield* commandGate.signalCommandReady;
450​
451 yield* Effect.logDebug("startup phase: publishing welcome event", {
452 environmentId: environment.environmentId,
453 cwd: welcomeBase.cwd,
454 projectName: welcomeBase.projectName,
455 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
456 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
457 });
458 yield* runStartupPhase(
459 "welcome.publish",
460 lifecycleEvents.publish({
461 version: 1,
462 type: "welcome",
463 payload: {
464 environment,
465 ...welcomeBase,
466 ...bootstrapTargets,
467 },
468 }),
469 );
470 }).pipe(
471 Effect.annotateSpans({
472 "server.mode": serverConfig.mode,
473 "server.port": serverConfig.port,
474 "server.host": serverConfig.host ?? "default",
475 }),
476 Effect.withSpan("server.startup", { kind: "server", root: true }),
477 );
478​
479 yield* Effect.forkScoped(
480 Effect.gen(function* () {
481 const startupExit = yield* Effect.exit(startup);
482 if (Exit.isFailure(startupExit)) {
483 const error = new ServerRuntimeStartupError({
484 mode: serverConfig.mode,
485 host: serverConfig.host ?? null,
486 port: serverConfig.port,
487 cause: startupExit.cause,
488 });
489 yield* Effect.logError("server runtime startup failed", {
490 cause: Cause.pretty(startupExit.cause),
491 });
492 yield* commandGate.failCommandReady(error);
493 return;
494 }
495​
496 yield* Effect.logDebug("startup phase: waiting for http listener");
497 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
498 yield* Effect.logDebug("startup phase: publishing ready event");
499 yield* runStartupPhase(
500 "ready.publish",
501 lifecycleEvents.publish({
502 version: 1,
503 type: "ready",
504 payload: {
505 at: DateTime.formatIso(yield* DateTime.now),
506 environment: yield* serverEnvironment.getDescriptor,
507 },
508 }),
509 );
510​
511 yield* Effect.logDebug("startup phase: recording startup heartbeat");
512 yield* launchStartupHeartbeat;
513 if (serverConfig.startupPresentation === "headless") {
514 yield* Effect.logDebug("startup phase: headless access info");
515 const accessInfo = yield* issueHeadlessServeAccessInfo();
516 yield* runStartupPhase(
517 "headless.output",
518 Console.log(formatHeadlessServeOutput(accessInfo)),
519 );
520 } else {
521 yield* Effect.logDebug("startup phase: browser open check");
522 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
523 if (serverConfig.mode !== "desktop") {
524 yield* Effect.logInfo(
525 "Authentication required. Open T3 Code using the pairing URL.",
526 ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
527 }
528 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
529 }
530 yield* Effect.logDebug("startup phase: complete");
531 }),
532 );
533​
534 return {
535 awaitCommandReady: commandGate.awaitCommandReady,
536 markHttpListening: Deferred.succeed(httpListening, undefined),
537 enqueueCommand: commandGate.enqueueCommand,
538 } satisfies ServerRuntimeStartup["Service"];
539});
540​
541export const layer = Layer.effect(ServerRuntimeStartup, make);