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