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

serverRuntimeStartup.ts

348 lines11.7 KB

1import {
2 CommandId,
3 DEFAULT_PROVIDER_INTERACTION_MODE,
4 type ModelSelection,
5 ProjectId,
6 ThreadId,
7} from "@t3tools/contracts";
8import {
9 Data,
10 Deferred,
11 Effect,
12 Exit,
13 Layer,
14 Option,
15 Path,
16 Queue,
17 Ref,
18 Scope,
19 ServiceMap,
20} from "effect";
21​
22import { ServerConfig } from "./config";
23import { Keybindings } from "./keybindings";
24import { Open } from "./open";
25import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
26import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
27import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
28import { ServerLifecycleEvents } from "./serverLifecycleEvents";
29import { ServerSettingsService } from "./serverSettings";
30import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
31​
32const isWildcardHost = (host: string | undefined): boolean =>
33 host === "0.0.0.0" || host === "::" || host === "[::]";
34​
35const formatHostForUrl = (host: string): string =>
36 host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
37​
38export class ServerRuntimeStartupError extends Data.TaggedError("ServerRuntimeStartupError")<{
39 readonly message: string;
40 readonly cause?: unknown;
41}> {}
42​
43export interface ServerRuntimeStartupShape {
44 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
45 readonly markHttpListening: Effect.Effect<void>;
46 readonly enqueueCommand: <A, E>(
47 effect: Effect.Effect<A, E>,
48 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
50​
51export class ServerRuntimeStartup extends ServiceMap.Service<
52 ServerRuntimeStartup,
53 ServerRuntimeStartupShape
54>()("t3/serverRuntimeStartup") {}
55​
56interface QueuedCommand {
57 readonly run: Effect.Effect<void, never>;
59​
60type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError;
61​
62interface CommandGate {
63 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
64 readonly signalCommandReady: Effect.Effect<void>;
65 readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
66 readonly enqueueCommand: <A, E>(
67 effect: Effect.Effect<A, E>,
68 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
70​
71const settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>
72 Exit.isSuccess(exit)
73 ? Deferred.succeed(deferred, exit.value)
74 : Deferred.failCause(deferred, exit.cause);
75​
76export const makeCommandGate = Effect.gen(function* () {
77 const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
78 const commandQueue = yield* Queue.unbounded<QueuedCommand>();
79 const commandReadinessState = yield* Ref.make<CommandReadinessState>("pending");
80​
81 const commandWorker = Effect.forever(
82 Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),
83 );
84 yield* Effect.forkScoped(commandWorker);
85​
86 return {
87 awaitCommandReady: Deferred.await(commandReady),
88 signalCommandReady: Effect.gen(function* () {
89 yield* Ref.set(commandReadinessState, "ready");
90 yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
91 }),
92 failCommandReady: (error) =>
93 Effect.gen(function* () {
94 yield* Ref.set(commandReadinessState, error);
95 yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
96 }),
97 enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>
98 Effect.gen(function* () {
99 const readinessState = yield* Ref.get(commandReadinessState);
100 if (readinessState === "ready") {
101 return yield* effect;
102 }
103 if (readinessState !== "pending") {
104 return yield* readinessState;
105 }
106​
107 const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
108 yield* Queue.offer(commandQueue, {
109 run: Deferred.await(commandReady).pipe(
110 Effect.flatMap(() => effect),
111 Effect.exit,
112 Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
113 ),
114 });
115 return yield* Deferred.await(result);
116 }),
117 } satisfies CommandGate;
118});
119​
120export const recordStartupHeartbeat = Effect.gen(function* () {
121 const analytics = yield* AnalyticsService;
122 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
123​
124 const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe(
125 Effect.catch((cause) =>
126 Effect.logWarning("failed to gather startup projection counts for telemetry", {
127 cause,
128 }).pipe(
129 Effect.as({
130 threadCount: 0,
131 projectCount: 0,
132 }),
133 ),
134 ),
135 );
136​
137 yield* analytics.record("server.boot.heartbeat", {
138 threadCount,
139 projectCount,
140 });
141});
142​
143export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(
144 Effect.ignoreCause({ log: true }),
145 Effect.forkScoped,
146 Effect.asVoid,
147);
148​
149const autoBootstrapWelcome = Effect.gen(function* () {
150 const serverConfig = yield* ServerConfig;
151 const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
152 const orchestrationEngine = yield* OrchestrationEngineService;
153 const path = yield* Path.Path;
154​
155 let bootstrapProjectId: ProjectId | undefined;
156 let bootstrapThreadId: ThreadId | undefined;
157​
158 if (serverConfig.autoBootstrapProjectFromCwd) {
159 yield* Effect.gen(function* () {
160 const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot(
161 serverConfig.cwd,
162 );
163 let nextProjectId: ProjectId;
164 let nextProjectDefaultModelSelection: ModelSelection;
165​
166 if (Option.isNone(existingProject)) {
167 const createdAt = new Date().toISOString();
168 nextProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
169 const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
170 nextProjectDefaultModelSelection = {
171 provider: "codex",
172 model: "gpt-5-codex",
173 };
174 yield* orchestrationEngine.dispatch({
175 type: "project.create",
176 commandId: CommandId.makeUnsafe(crypto.randomUUID()),
177 projectId: nextProjectId,
178 title: bootstrapProjectTitle,
179 workspaceRoot: serverConfig.cwd,
180 defaultModelSelection: nextProjectDefaultModelSelection,
181 createdAt,
182 });
183 } else {
184 nextProjectId = existingProject.value.id;
185 nextProjectDefaultModelSelection = existingProject.value.defaultModelSelection ?? {
186 provider: "codex",
187 model: "gpt-5-codex",
188 };
189 }
190​
191 const existingThreadId =
192 yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
193 if (Option.isNone(existingThreadId)) {
194 const createdAt = new Date().toISOString();
195 const createdThreadId = ThreadId.makeUnsafe(crypto.randomUUID());
196 yield* orchestrationEngine.dispatch({
197 type: "thread.create",
198 commandId: CommandId.makeUnsafe(crypto.randomUUID()),
199 threadId: createdThreadId,
200 projectId: nextProjectId,
201 title: "New thread",
202 modelSelection: nextProjectDefaultModelSelection,
203 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
204 runtimeMode: "full-access",
205 branch: null,
206 worktreePath: null,
207 createdAt,
208 });
209 bootstrapProjectId = nextProjectId;
210 bootstrapThreadId = createdThreadId;
211 } else {
212 bootstrapProjectId = nextProjectId;
213 bootstrapThreadId = existingThreadId.value;
214 }
215 });
216 }
217​
218 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
219 const projectName = segments[segments.length - 1] ?? "project";
220​
221 return {
222 cwd: serverConfig.cwd,
223 projectName,
224 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
225 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
226 } as const;
227});
228​
229const maybeOpenBrowser = Effect.gen(function* () {
230 const serverConfig = yield* ServerConfig;
231 if (serverConfig.noBrowser) {
232 return;
233 }
234 const { openBrowser } = yield* Open;
235 const localUrl = `http://localhost:${serverConfig.port}`;
236 const bindUrl =
237 serverConfig.host && !isWildcardHost(serverConfig.host)
238 ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
239 : localUrl;
240 const target = serverConfig.devUrl?.toString() ?? bindUrl;
241​
242 yield* openBrowser(target).pipe(
243 Effect.catch(() =>
244 Effect.logInfo("browser auto-open unavailable", {
245 hint: `Open ${target} in your browser.`,
246 }),
247 ),
248 );
249});
250​
251const makeServerRuntimeStartup = Effect.gen(function* () {
252 const keybindings = yield* Keybindings;
253 const orchestrationReactor = yield* OrchestrationReactor;
254 const lifecycleEvents = yield* ServerLifecycleEvents;
255 const serverSettings = yield* ServerSettingsService;
256​
257 const commandGate = yield* makeCommandGate;
258 const httpListening = yield* Deferred.make<void>();
259 const reactorScope = yield* Scope.make("sequential");
260​
261 yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
262​
263 const startup = Effect.gen(function* () {
264 yield* Effect.logDebug("startup phase: starting keybindings runtime");
265 yield* keybindings.start.pipe(
266 Effect.catch((error) =>
267 Effect.logWarning("failed to start keybindings runtime", {
268 path: error.configPath,
269 detail: error.detail,
270 cause: error.cause,
271 }),
272 ),
273 Effect.forkScoped,
274 );
275​
276 yield* Effect.logDebug("startup phase: starting server settings runtime");
277 yield* serverSettings.start.pipe(
278 Effect.catch((error) =>
279 Effect.logWarning("failed to start server settings runtime", {
280 path: error.settingsPath,
281 detail: error.detail,
282 cause: error.cause,
283 }),
284 ),
285 Effect.forkScoped,
286 );
287​
288 yield* Effect.logDebug("startup phase: starting orchestration reactors");
289 yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
290​
291 yield* Effect.logDebug("startup phase: preparing welcome payload");
292 const welcome = yield* autoBootstrapWelcome;
293 yield* Effect.logDebug("startup phase: publishing welcome event", {
294 cwd: welcome.cwd,
295 projectName: welcome.projectName,
296 bootstrapProjectId: welcome.bootstrapProjectId,
297 bootstrapThreadId: welcome.bootstrapThreadId,
298 });
299 yield* lifecycleEvents.publish({
300 version: 1,
301 type: "welcome",
302 payload: welcome,
303 });
304 });
305​
306 yield* Effect.forkScoped(
307 Effect.gen(function* () {
308 const startupExit = yield* Effect.exit(startup);
309 if (Exit.isFailure(startupExit)) {
310 const error = new ServerRuntimeStartupError({
311 message: "Server runtime startup failed before command readiness.",
312 cause: startupExit.cause,
313 });
314 yield* Effect.logError("server runtime startup failed", { cause: startupExit.cause });
315 yield* commandGate.failCommandReady(error);
316 return;
317 }
318​
319 yield* Effect.logDebug("Accepting commands");
320 yield* commandGate.signalCommandReady;
321 yield* Effect.logDebug("startup phase: waiting for http listener");
322 yield* Deferred.await(httpListening);
323 yield* Effect.logDebug("startup phase: publishing ready event");
324 yield* lifecycleEvents.publish({
325 version: 1,
326 type: "ready",
327 payload: { at: new Date().toISOString() },
328 });
329​
330 yield* Effect.logDebug("startup phase: recording startup heartbeat");
331 yield* launchStartupHeartbeat;
332 yield* Effect.logDebug("startup phase: browser open check");
333 yield* maybeOpenBrowser;
334 yield* Effect.logDebug("startup phase: complete");
335 }),
336 );
337​
338 return {
339 awaitCommandReady: commandGate.awaitCommandReady,
340 markHttpListening: Deferred.succeed(httpListening, undefined),
341 enqueueCommand: commandGate.enqueueCommand,
342 } satisfies ServerRuntimeStartupShape;
343});
344​
345export const ServerRuntimeStartupLive = Layer.effect(
346 ServerRuntimeStartup,
347 makeServerRuntimeStartup,
348);