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

serverRuntimeStartup.ts

587 lines21.1 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 Cause from "effect/Cause";
11import * as Console from "effect/Console";
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 Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Path from "effect/Path";
21import * as Queue from "effect/Queue";
22import * as Ref from "effect/Ref";
23import * as Schema from "effect/Schema";
24import * as Scope from "effect/Scope";
25​
26import * as ServerConfig from "./config.ts";
27import * as Keybindings from "./keybindings.ts";
28import * as ExternalLauncher from "./process/externalLauncher.ts";
29import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
30import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
31import * as OrchestrationReactor from "./orchestration/Services/OrchestrationReactor.ts";
32import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
33import * as ServerSettings from "./serverSettings.ts";
34import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
35import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
36import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
37import * as ProviderService from "./provider/Services/ProviderService.ts";
38import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
39import * as ProviderSessionReaper from "./provider/Services/ProviderSessionReaper.ts";
40import { forkParked } from "./serverActivation.ts";
41import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
42import {
43 formatHeadlessServeOutput,
44 formatHostForUrl,
45 isWildcardHost,
46 issueHeadlessServeAccessInfo,
47} from "./startupAccess.ts";
48​
49export class ServerRuntimeStartupError extends Schema.TaggedErrorClass<ServerRuntimeStartupError>()(
50 "ServerRuntimeStartupError",
51 {
52 mode: ServerConfig.RuntimeMode,
53 host: Schema.NullOr(Schema.String),
54 port: Schema.Number,
55 cause: Schema.Defect(),
56 },
57) {
58 override get message(): string {
59 return "Server runtime startup failed before command readiness.";
60 }
62​
63export class ServerRuntimeStartup extends Context.Service<
64 ServerRuntimeStartup,
65 {
66 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
67 readonly markHttpListening: Effect.Effect<void>;
68 readonly enqueueCommand: <A, E>(
69 effect: Effect.Effect<A, E>,
70 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
71 }
72>()("t3/serverRuntimeStartup") {}
73​
74interface QueuedCommand {
75 readonly run: Effect.Effect<void, never>;
77​
78type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError;
79​
80interface CommandGate {
81 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
82 readonly signalCommandReady: Effect.Effect<void>;
83 readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
84 readonly enqueueCommand: <A, E>(
85 effect: Effect.Effect<A, E>,
86 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
88​
89const settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>
90 Exit.isSuccess(exit)
91 ? Deferred.succeed(deferred, exit.value)
92 : Deferred.failCause(deferred, exit.cause);
93​
94export const makeCommandGate = Effect.gen(function* () {
95 const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
96 const commandQueue = yield* Queue.unbounded<QueuedCommand>();
97 const commandReadinessState = yield* Ref.make<CommandReadinessState>("pending");
98​
99 const commandWorker = Effect.forever(
100 Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),
101 );
102 yield* Effect.forkScoped(commandWorker);
103​
104 return {
105 awaitCommandReady: Deferred.await(commandReady),
106 signalCommandReady: Effect.gen(function* () {
107 yield* Ref.set(commandReadinessState, "ready");
108 yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
109 }),
110 failCommandReady: (error) =>
111 Effect.gen(function* () {
112 yield* Ref.set(commandReadinessState, error);
113 yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
114 }),
115 enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>
116 Effect.gen(function* () {
117 const readinessState = yield* Ref.get(commandReadinessState);
118 if (readinessState === "ready") {
119 return yield* effect;
120 }
121 if (readinessState !== "pending") {
122 return yield* readinessState;
123 }
124​
125 const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
126 yield* Queue.offer(commandQueue, {
127 run: Deferred.await(commandReady).pipe(
128 Effect.flatMap(() => effect),
129 Effect.exit,
130 Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
131 ),
132 });
133 return yield* Deferred.await(result);
134 }),
135 } satisfies CommandGate;
136});
137​
138export const recordStartupHeartbeat = Effect.gen(function* () {
139 const analytics = yield* AnalyticsService.AnalyticsService;
140 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
141​
142 const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe(
143 Effect.catch((cause) =>
144 Effect.logWarning("failed to gather startup projection counts for telemetry", {
145 cause,
146 }).pipe(
147 Effect.as({
148 threadCount: 0,
149 projectCount: 0,
150 }),
151 ),
152 ),
153 );
154​
155 yield* analytics.record("server.boot.heartbeat", {
156 threadCount,
157 projectCount,
158 });
159});
160​
161export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(
162 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
163 Effect.withSpan("server.startup.heartbeat.record"),
164 Effect.ignoreCause({ log: true }),
165 Effect.forkScoped,
166 Effect.asVoid,
167);
168​
169export const getAutoBootstrapThreadModelSelection = (): ModelSelection => ({
170 instanceId: ProviderInstanceId.make("codex"),
171 model: DEFAULT_MODEL,
172});
173​
174export const resolveWelcomeBase = Effect.gen(function* () {
175 const serverConfig = yield* ServerConfig.ServerConfig;
176 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
177 const projectName = segments[segments.length - 1] ?? "project";
178​
179 return {
180 cwd: serverConfig.cwd,
181 projectName,
182 } as const;
183});
184​
185export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
186 const crypto = yield* Crypto.Crypto;
187 const randomUUID = crypto.randomUUIDv4;
188 const serverConfig = yield* ServerConfig.ServerConfig;
189 const projectionReadModelQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
190 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
191 const path = yield* Path.Path;
192​
193 let bootstrapProjectId: ProjectId | undefined;
194 let bootstrapThreadId: ThreadId | undefined;
195​
196 if (serverConfig.autoBootstrapProjectFromCwd) {
197 yield* Effect.gen(function* () {
198 const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot(
199 serverConfig.cwd,
200 );
201 let nextProjectId: ProjectId;
202 let nextThreadModelSelection: ModelSelection;
203​
204 if (Option.isNone(existingProject)) {
205 const createdAt = DateTime.formatIso(yield* DateTime.now);
206 nextProjectId = ProjectId.make(yield* randomUUID);
207 const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
208 nextThreadModelSelection = getAutoBootstrapThreadModelSelection();
209 yield* orchestrationEngine.dispatch({
210 type: "project.create",
211 commandId: CommandId.make(yield* randomUUID),
212 projectId: nextProjectId,
213 title: bootstrapProjectTitle,
214 workspaceRoot: serverConfig.cwd,
215 createdAt,
216 });
217 } else {
218 nextProjectId = existingProject.value.id;
219 nextThreadModelSelection =
220 existingProject.value.defaultModelSelection ?? getAutoBootstrapThreadModelSelection();
221 }
222​
223 const existingThreadId =
224 yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
225 if (Option.isNone(existingThreadId)) {
226 const createdAt = DateTime.formatIso(yield* DateTime.now);
227 const createdThreadId = ThreadId.make(yield* randomUUID);
228 yield* orchestrationEngine.dispatch({
229 type: "thread.create",
230 commandId: CommandId.make(yield* randomUUID),
231 threadId: createdThreadId,
232 projectId: nextProjectId,
233 title: "New thread",
234 modelSelection: nextThreadModelSelection,
235 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
236 runtimeMode: "full-access",
237 branch: null,
238 worktreePath: null,
239 createdAt,
240 });
241 bootstrapProjectId = nextProjectId;
242 bootstrapThreadId = createdThreadId;
243 } else {
244 bootstrapProjectId = nextProjectId;
245 bootstrapThreadId = existingThreadId.value;
246 }
247 });
248 }
249​
250 return {
251 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
252 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
253 } as const;
254});
255​
256const resolveStartupBrowserTarget = Effect.gen(function* () {
257 const serverConfig = yield* ServerConfig.ServerConfig;
258 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
259 const localUrl = `http://localhost:${serverConfig.port}`;
260 const bindUrl =
261 serverConfig.host && !isWildcardHost(serverConfig.host)
262 ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
263 : localUrl;
264 const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
265 return yield* Effect.succeed(serverConfig.mode === "desktop" ? baseTarget : undefined).pipe(
266 Effect.flatMap((target) =>
267 target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget),
268 ),
269 );
270});
271​
272const maybeOpenBrowser = (target: string) =>
273 Effect.gen(function* () {
274 const serverConfig = yield* ServerConfig.ServerConfig;
275 if (serverConfig.noBrowser) {
276 return;
277 }
278 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
279​
280 yield* externalLauncher.launchBrowser(target).pipe(
281 Effect.catch(() =>
282 Effect.logInfo("browser auto-open unavailable", {
283 hint: `Open ${target} in your browser.`,
284 }),
285 ),
286 );
287 });
288​
289const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
290 effect.pipe(
291 Effect.annotateSpans({ "startup.phase": phase }),
292 Effect.withSpan(`server.startup.${phase}`),
293 );
294​
295const ORPHANED_PROVIDER_SESSION_ERROR =
296 "Provider session did not survive a server restart. Send a new message to continue.";
297​
298export const reconcileProviderSessions = Effect.gen(function* () {
299 const crypto = yield* Crypto.Crypto;
300 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
301 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
302 const providerService = yield* ProviderService.ProviderService;
303 const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
304​
305 const liveThreadIds = new Set(
306 (yield* providerService.listSessions()).map((session) => session.threadId),
307 );
308 const { threads } = yield* query.getCommandReadModel();
309 const orphanedThreads = threads.filter(
310 (thread) =>
311 thread.session !== null &&
312 (thread.session.status === "starting" ||
313 thread.session.status === "running" ||
314 thread.session.activeTurnId !== null) &&
315 !liveThreadIds.has(thread.id),
316 );
317​
318 for (const thread of orphanedThreads) {
319 const session = thread.session;
320 if (session === null) {
321 continue;
322 }
323 yield* Effect.gen(function* () {
324 const binding = yield* directory.getBinding(thread.id);
325 if (Option.isSome(binding)) {
326 yield* directory.upsert({
327 ...binding.value,
328 status: "stopped",
329 runtimePayload: { activeTurnId: null },
330 });
331 }
332 }).pipe(
333 Effect.catchCause((cause) =>
334 Cause.hasInterrupts(cause)
335 ? Effect.failCause(cause)
336 : Effect.logWarning("failed to reconcile orphaned provider session directory binding", {
337 threadId: thread.id,
338 cause,
339 }),
340 ),
341 );
342​
343 yield* Effect.gen(function* () {
344 const reconciledAt = DateTime.formatIso(yield* DateTime.now);
345 yield* orchestrationEngine.dispatch({
346 type: "thread.session.set",
347 commandId: CommandId.make(yield* crypto.randomUUIDv4),
348 threadId: thread.id,
349 session: {
350 ...session,
351 status: "error",
352 activeTurnId: null,
353 lastError: ORPHANED_PROVIDER_SESSION_ERROR,
354 updatedAt: reconciledAt,
355 },
356 createdAt: reconciledAt,
357 });
358 }).pipe(
359 Effect.retry({ times: 1 }),
360 Effect.catchCause((cause) =>
361 Cause.hasInterrupts(cause)
362 ? Effect.failCause(cause)
363 : Effect.logWarning("failed to settle orphaned provider session projection", {
364 threadId: thread.id,
365 cause,
366 }),
367 ),
368 );
369 }
370}).pipe(
371 Effect.catchCause((cause) =>
372 Cause.hasInterrupts(cause)
373 ? Effect.failCause(cause)
374 : Effect.logWarning("provider session startup reconciliation failed", { cause }),
375 ),
376);
377​
378interface StartupOptions {
379 readonly activate?: Effect.Effect<void>;
380 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
381 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
383​
384export const make = (options?: StartupOptions) =>
385 Effect.gen(function* () {
386 const serverConfig = yield* ServerConfig.ServerConfig;
387 const keybindings = yield* Keybindings.Keybindings;
388 const orchestrationReactor = yield* OrchestrationReactor.OrchestrationReactor;
389 const providerSessionReaper = yield* ProviderSessionReaper.ProviderSessionReaper;
390 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
391 const serverSettings = yield* ServerSettings.ServerSettingsService;
392 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
393 const crypto = yield* Crypto.Crypto;
394 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
395​
396 const commandGate = yield* makeCommandGate;
397 const httpListening = yield* Deferred.make<void>();
398 const reactorScope = yield* Scope.make("sequential");
399​
400 yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
401​
402 const startup = Effect.gen(function* () {
403 yield* Effect.logDebug("startup phase: starting keybindings runtime");
404 yield* runStartupPhase(
405 "keybindings.start",
406 keybindings.start.pipe(
407 Effect.catch((error) =>
408 Effect.logWarning("failed to start keybindings runtime", {
409 path: error.configPath,
410 detail: error.detail,
411 cause: error.cause,
412 }),
413 ),
414 ),
415 );
416​
417 yield* Effect.logDebug("startup phase: starting server settings runtime");
418 yield* runStartupPhase(
419 "settings.start",
420 serverSettings.start.pipe(
421 Effect.catch((error) =>
422 Effect.logWarning("failed to start server settings runtime", {
423 path: error.settingsPath,
424 operation: error.operation,
425 providerInstanceId: error.providerInstanceId,
426 environmentVariable: error.environmentVariable,
427 cause: error.cause,
428 }),
429 ),
430 ),
431 );
432​
433 yield* Effect.logDebug("startup phase: parking orchestration roots at activation");
434 yield* runStartupPhase(
435 "reactors.start",
436 Effect.gen(function* () {
437 yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
438 yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));
439 }),
440 );
441​
442 yield* runStartupPhase("provider-sessions.reconcile", reconcileProviderSessions);
443​
444 const welcomeBase = yield* resolveWelcomeBase;
445 const environment = yield* serverEnvironment.getDescriptor;
446 yield* Effect.logDebug("startup phase: preparing welcome payload");
447​
448 if (serverConfig.autoBootstrapProjectFromCwd) {
449 yield* forkParked(
450 runStartupPhase(
451 "welcome.autobootstrap",
452 Effect.gen(function* () {
453 const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets.pipe(
454 Effect.provideService(Crypto.Crypto, crypto),
455 );
456 if (!bootstrapTargets.bootstrapProjectId && !bootstrapTargets.bootstrapThreadId) {
457 return;
458 }
459​
460 yield* Effect.logDebug("startup phase: publishing bootstrapped welcome event", {
461 environmentId: environment.environmentId,
462 cwd: welcomeBase.cwd,
463 projectName: welcomeBase.projectName,
464 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
465 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
466 });
467 yield* lifecycleEvents.publish({
468 version: 1,
469 type: "welcome",
470 payload: {
471 environment,
472 ...welcomeBase,
473 ...bootstrapTargets,
474 },
475 });
476 }).pipe(
477 Effect.catch((cause) =>
478 Effect.logWarning("startup auto-bootstrap welcome failed", {
479 cause,
480 }),
481 ),
482 ),
483 ),
484 );
485 }
486​
487 yield* forkParked(
488 Effect.gen(function* () {
489 yield* Effect.logDebug("startup phase: recording startup heartbeat");
490 yield* recordStartupHeartbeat.pipe(
491 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
492 Effect.withSpan("server.startup.heartbeat.record"),
493 Effect.ignoreCause({ log: true }),
494 );
495 if (serverConfig.startupPresentation === "headless") {
496 const accessInfo = yield* issueHeadlessServeAccessInfo();
497 yield* runStartupPhase(
498 "headless.output",
499 Console.log(formatHeadlessServeOutput(accessInfo)),
500 );
501 } else {
502 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
503 if (serverConfig.mode !== "desktop") {
504 yield* Effect.logInfo(
505 "Authentication required. Open T3 Code using the pairing URL.",
506 ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
507 }
508 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
509 }
510 }),
511 );
512​
513 yield* Effect.logDebug("startup phase: waiting for http listener");
514 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
515 yield* runStartupPhase(
516 "auxiliary-roots.parked",
517 options?.awaitAuxiliaryParked ?? Effect.void,
518 );
519​
520 // This is the prepared boundary. Every dependency has been acquired and
521 // every runtime root has confirmed that it is parked before this request.
522 const updateOutcome = yield* launcher.prepareTrial;
523 yield* runStartupPhase(
524 "welcome.publish",
525 lifecycleEvents.publish({
526 version: 1,
527 type: "welcome",
528 payload: { environment, ...welcomeBase },
529 }),
530 );
531 yield* options?.activate ?? Effect.void;
532​
533 yield* Effect.logDebug("Accepting commands");
534 yield* commandGate.signalCommandReady;
535 yield* runStartupPhase(
536 "ready.publish",
537 lifecycleEvents.publish({
538 version: 1,
539 type: "ready",
540 payload: {
541 at: DateTime.formatIso(yield* DateTime.now),
542 environment,
543 ...(updateOutcome === undefined ? {} : { updateOutcome }),
544 },
545 }),
546 );
547 yield* Effect.logDebug("startup phase: complete");
548 }).pipe(
549 Effect.annotateSpans({
550 "server.mode": serverConfig.mode,
551 "server.port": serverConfig.port,
552 "server.host": serverConfig.host ?? "default",
553 }),
554 Effect.withSpan("server.startup", { kind: "server", root: true }),
555 );
556​
557 yield* Effect.forkScoped(
558 Effect.exit(startup).pipe(
559 Effect.flatMap((startupExit) => {
560 if (Exit.isSuccess(startupExit)) return Effect.void;
561 const error = new ServerRuntimeStartupError({
562 mode: serverConfig.mode,
563 host: serverConfig.host ?? null,
564 port: serverConfig.port,
565 cause: startupExit.cause,
566 });
567 return Effect.logError("server runtime startup failed", {
568 cause: startupExit.cause,
569 }).pipe(
570 Effect.andThen(commandGate.failCommandReady(error)),
571 Effect.andThen(options?.abort?.(error) ?? Effect.void),
572 );
573 }),
574 ),
575 );
576​
577 return {
578 awaitCommandReady: commandGate.awaitCommandReady,
579 markHttpListening: Deferred.succeed(httpListening, undefined),
580 enqueueCommand: commandGate.enqueueCommand,
581 } satisfies ServerRuntimeStartup["Service"];
582 });
583​
584export const layerWithOptions = (options?: StartupOptions) =>
585 Layer.effect(ServerRuntimeStartup, make(options));
586​
587export const layer = layerWithOptions();