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