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