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

serverRuntimeStartup.ts

930 lines33.2 KB

1import {
2 CommandId,
3 DEFAULT_MODEL,
4 DEFAULT_PROVIDER_INTERACTION_MODE,
5 type ModelSelection,
6 type OrchestrationProjectShell,
7 ProjectId,
8 ProviderInstanceId,
9 ThreadId,
10 TurnId,
11} from "@t3tools/contracts";
12import * as Cause from "effect/Cause";
13import * as Console from "effect/Console";
14import * as Context from "effect/Context";
15import * as Crypto from "effect/Crypto";
16import * as DateTime from "effect/DateTime";
17import * as Deferred from "effect/Deferred";
18import * as Effect from "effect/Effect";
19import * as Exit from "effect/Exit";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Path from "effect/Path";
23import * as Queue from "effect/Queue";
24import * as Ref from "effect/Ref";
25import * as Schema from "effect/Schema";
26import * as Scope from "effect/Scope";
27​
28import * as ServerConfig from "./config.ts";
29import * as Keybindings from "./keybindings.ts";
30import * as ExternalLauncher from "./process/externalLauncher.ts";
31import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
32import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
33import * as OrchestrationReactor from "./orchestration/Services/OrchestrationReactor.ts";
34import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
35import * as ServerSettings from "./serverSettings.ts";
36import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
37import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
38import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
39import * as ProviderService from "./provider/Services/ProviderService.ts";
40import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
41import * as ProviderSessionReaper from "./provider/Services/ProviderSessionReaper.ts";
42import { forkParked } from "./serverActivation.ts";
43import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
44import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
45import {
46 formatHeadlessServeOutput,
47 formatHostForUrl,
48 isWildcardHost,
49 issueHeadlessServeAccessInfo,
50} from "./startupAccess.ts";
51​
52export class ServerRuntimeStartupError extends Schema.TaggedErrorClass<ServerRuntimeStartupError>()(
53 "ServerRuntimeStartupError",
54 {
55 mode: ServerConfig.RuntimeMode,
56 host: Schema.NullOr(Schema.String),
57 port: Schema.Number,
58 cause: Schema.Defect(),
59 },
60) {
61 override get message(): string {
62 return "Server runtime startup failed before command readiness.";
63 }
65​
66export class ServerRuntimeStartup extends Context.Service<
67 ServerRuntimeStartup,
68 {
69 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
70 readonly markHttpListening: Effect.Effect<void>;
71 readonly markRunningProviderSessionsForContinuation: Effect.Effect<
72 ReadonlyArray<ThreadId>,
73 ServerUpdateThreadContinuationError
74 >;
75 readonly clearProviderSessionContinuationMarkers: (
76 threadIds: ReadonlyArray<ThreadId>,
77 ) => Effect.Effect<void, ServerUpdateThreadContinuationError>;
78 readonly enqueueCommand: <A, E>(
79 effect: Effect.Effect<A, E>,
80 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
81 }
82>()("t3/serverRuntimeStartup") {}
83​
84interface QueuedCommand {
85 readonly run: Effect.Effect<void, never>;
87​
88type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError;
89​
90interface CommandGate {
91 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
92 readonly signalCommandReady: Effect.Effect<void>;
93 readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
94 readonly enqueueCommand: <A, E>(
95 effect: Effect.Effect<A, E>,
96 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
98​
99const settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>
100 Exit.isSuccess(exit)
101 ? Deferred.succeed(deferred, exit.value)
102 : Deferred.failCause(deferred, exit.cause);
103​
104export const makeCommandGate = Effect.gen(function* () {
105 const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
106 const commandQueue = yield* Queue.unbounded<QueuedCommand>();
107 const commandReadinessState = yield* Ref.make<CommandReadinessState>("pending");
108​
109 const commandWorker = Effect.forever(
110 Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),
111 );
112 yield* Effect.forkScoped(commandWorker);
113​
114 return {
115 awaitCommandReady: Deferred.await(commandReady),
116 signalCommandReady: Effect.gen(function* () {
117 yield* Ref.set(commandReadinessState, "ready");
118 yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
119 }),
120 failCommandReady: (error) =>
121 Effect.gen(function* () {
122 yield* Ref.set(commandReadinessState, error);
123 yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
124 }),
125 enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>
126 Effect.gen(function* () {
127 const readinessState = yield* Ref.get(commandReadinessState);
128 if (readinessState === "ready") {
129 return yield* effect;
130 }
131 if (readinessState !== "pending") {
132 return yield* readinessState;
133 }
134​
135 const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
136 yield* Queue.offer(commandQueue, {
137 run: Deferred.await(commandReady).pipe(
138 Effect.flatMap(() => effect),
139 Effect.exit,
140 Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
141 ),
142 });
143 return yield* Deferred.await(result);
144 }),
145 } satisfies CommandGate;
146});
147​
148export const recordStartupHeartbeat = Effect.gen(function* () {
149 const analytics = yield* AnalyticsService.AnalyticsService;
150 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
151​
152 const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe(
153 Effect.catch((cause) =>
154 Effect.logWarning("failed to gather startup projection counts for telemetry", {
155 cause,
156 }).pipe(
157 Effect.as({
158 threadCount: 0,
159 projectCount: 0,
160 }),
161 ),
162 ),
163 );
164​
165 yield* analytics.record("server.boot.heartbeat", {
166 threadCount,
167 projectCount,
168 });
169});
170​
171export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(
172 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
173 Effect.withSpan("server.startup.heartbeat.record"),
174 Effect.ignoreCause({ log: true }),
175 Effect.forkScoped,
176 Effect.asVoid,
177);
178​
179export const getAutoBootstrapThreadModelSelection = (): ModelSelection => ({
180 instanceId: ProviderInstanceId.make("codex"),
181 model: DEFAULT_MODEL,
182});
183​
184export const resolveWelcomeBase = Effect.gen(function* () {
185 const serverConfig = yield* ServerConfig.ServerConfig;
186 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
187 const projectName = segments[segments.length - 1] ?? "project";
188​
189 return {
190 cwd: serverConfig.cwd,
191 projectName,
192 } as const;
193});
194​
195export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
196 const crypto = yield* Crypto.Crypto;
197 const randomUUID = crypto.randomUUIDv4;
198 const serverConfig = yield* ServerConfig.ServerConfig;
199 const projectionReadModelQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
200 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
201 const path = yield* Path.Path;
202​
203 let bootstrapProjectId: ProjectId | undefined;
204 let bootstrapThreadId: ThreadId | undefined;
205​
206 if (serverConfig.autoBootstrapProjectFromCwd) {
207 yield* Effect.gen(function* () {
208 const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot(
209 serverConfig.cwd,
210 );
211 let nextProjectId: ProjectId;
212 let nextThreadModelSelection: ModelSelection;
213​
214 if (Option.isNone(existingProject)) {
215 const createdAt = DateTime.formatIso(yield* DateTime.now);
216 nextProjectId = ProjectId.make(yield* randomUUID);
217 const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
218 nextThreadModelSelection = getAutoBootstrapThreadModelSelection();
219 yield* orchestrationEngine.dispatch({
220 type: "project.create",
221 commandId: CommandId.make(yield* randomUUID),
222 projectId: nextProjectId,
223 title: bootstrapProjectTitle,
224 workspaceRoot: serverConfig.cwd,
225 createdAt,
226 });
227 } else {
228 nextProjectId = existingProject.value.id;
229 nextThreadModelSelection =
230 existingProject.value.defaultModelSelection ?? getAutoBootstrapThreadModelSelection();
231 }
232​
233 const existingThreadId =
234 yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
235 if (Option.isNone(existingThreadId)) {
236 const createdAt = DateTime.formatIso(yield* DateTime.now);
237 const createdThreadId = ThreadId.make(yield* randomUUID);
238 yield* orchestrationEngine.dispatch({
239 type: "thread.create",
240 commandId: CommandId.make(yield* randomUUID),
241 threadId: createdThreadId,
242 projectId: nextProjectId,
243 title: "New thread",
244 modelSelection: nextThreadModelSelection,
245 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
246 runtimeMode: "full-access",
247 branch: null,
248 worktreePath: null,
249 createdAt,
250 });
251 bootstrapProjectId = nextProjectId;
252 bootstrapThreadId = createdThreadId;
253 } else {
254 bootstrapProjectId = nextProjectId;
255 bootstrapThreadId = existingThreadId.value;
256 }
257 });
258 }
259​
260 return {
261 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
262 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
263 } as const;
264});
265​
266const resolveStartupBrowserTarget = Effect.gen(function* () {
267 const serverConfig = yield* ServerConfig.ServerConfig;
268 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
269 const localUrl = `http://localhost:${serverConfig.port}`;
270 const bindUrl =
271 serverConfig.host && !isWildcardHost(serverConfig.host)
272 ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
273 : localUrl;
274 const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
275 return yield* Effect.succeed(serverConfig.mode === "desktop" ? baseTarget : undefined).pipe(
276 Effect.flatMap((target) =>
277 target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget),
278 ),
279 );
280});
281​
282const maybeOpenBrowser = (target: string) =>
283 Effect.gen(function* () {
284 const serverConfig = yield* ServerConfig.ServerConfig;
285 if (serverConfig.noBrowser) {
286 return;
287 }
288 const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
289​
290 yield* externalLauncher.launchBrowser(target).pipe(
291 Effect.catch(() =>
292 Effect.logInfo("browser auto-open unavailable", {
293 hint: `Open ${target} in your browser.`,
294 }),
295 ),
296 );
297 });
298​
299const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
300 effect.pipe(
301 Effect.annotateSpans({ "startup.phase": phase }),
302 Effect.withSpan(`server.startup.${phase}`),
303 );
304​
305const ORPHANED_PROVIDER_SESSION_ERROR =
306 "Provider session did not survive a server restart. Send a new message to continue.";
307const SERVER_UPDATE_CONTINUATION_KEY = "continueAfterServerUpdate";
308const SERVER_UPDATE_CONTINUATION_PROMPT = "Continue where you left off.";
309​
310class ProviderSessionContinuationError extends Schema.TaggedErrorClass<ProviderSessionContinuationError>()(
311 "ProviderSessionContinuationError",
312 {
313 threadId: ThreadId,
314 },
315) {
316 override get message(): string {
317 return `Could not continue thread '${this.threadId}': the provider instance is missing.`;
318 }
320​
321export class ServerUpdateThreadContinuationError extends Schema.TaggedErrorClass<ServerUpdateThreadContinuationError>()(
322 "ServerUpdateThreadContinuationError",
323 {
324 cause: Schema.Defect(),
325 },
326) {
327 override get message(): string {
328 return "Could not prepare running threads to continue after the update.";
329 }
331​
332function hasServerUpdateContinuationMarker(
333 runtimePayload: unknown,
334): runtimePayload is Record<string, unknown> {
335 return (
336 runtimePayload !== null &&
337 typeof runtimePayload === "object" &&
338 !Array.isArray(runtimePayload) &&
339 SERVER_UPDATE_CONTINUATION_KEY in runtimePayload
340 );
342​
343function readRuntimePayload(runtimePayload: unknown): Record<string, unknown> {
344 return runtimePayload !== null &&
345 typeof runtimePayload === "object" &&
346 !Array.isArray(runtimePayload)
347 ? (runtimePayload as Record<string, unknown>)
348 : {};
350​
351const isServerUpdateThreadContinuationError = Schema.is(ServerUpdateThreadContinuationError);
352​
353function readServerUpdateContinuationTurnId(runtimePayload: unknown): TurnId | null {
354 if (!hasServerUpdateContinuationMarker(runtimePayload)) {
355 return null;
356 }
357 const value = runtimePayload[SERVER_UPDATE_CONTINUATION_KEY];
358 return typeof value === "string" && value.length > 0 ? TurnId.make(value) : null;
360​
361const toServerUpdateThreadContinuationError = (cause: unknown) =>
362 isServerUpdateThreadContinuationError(cause)
363 ? cause
364 : new ServerUpdateThreadContinuationError({ cause });
365​
366export const markRunningProviderSessionsForContinuation = Effect.gen(function* () {
367 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
368 const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
369 const { threads } = yield* query.getCommandReadModel();
370 const running = threads.filter(
371 (thread) =>
372 thread.archivedAt === null &&
373 thread.deletedAt === null &&
374 thread.session?.status === "running" &&
375 thread.session.activeTurnId !== null,
376 );
377​
378 const marked: ThreadId[] = [];
379 return yield* Effect.gen(function* () {
380 for (const thread of running) {
381 const activeTurnId = thread.session?.activeTurnId;
382 if (activeTurnId === null || activeTurnId === undefined) {
383 continue;
384 }
385 const binding = yield* directory.getBinding(thread.id);
386 if (Option.isNone(binding)) {
387 continue;
388 }
389 if (binding.value.resumeCursor === null || binding.value.resumeCursor === undefined) {
390 continue;
391 }
392 yield* directory.upsert({
393 ...binding.value,
394 runtimePayload: {
395 ...readRuntimePayload(binding.value.runtimePayload),
396 [SERVER_UPDATE_CONTINUATION_KEY]: activeTurnId,
397 },
398 });
399 marked.push(thread.id);
400 }
401 return marked;
402 }).pipe(
403 Effect.catchCause((cause) =>
404 clearProviderSessionContinuationMarkers(marked).pipe(Effect.andThen(Effect.failCause(cause))),
405 ),
406 );
407}).pipe(Effect.mapError(toServerUpdateThreadContinuationError));
408​
409const clearContinuationMarkers = (
410 directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"],
411 threadIds: ReadonlyArray<ThreadId>,
412) =>
413 Effect.forEach(
414 threadIds,
415 (threadId) =>
416 directory.getBinding(threadId).pipe(
417 Effect.flatMap(
418 Option.match({
419 onNone: () => Effect.void,
420 onSome: (binding) =>
421 directory.upsert({
422 ...binding,
423 runtimePayload: {
424 ...readRuntimePayload(binding.runtimePayload),
425 [SERVER_UPDATE_CONTINUATION_KEY]: null,
426 },
427 }),
428 }),
429 ),
430 ),
431 { concurrency: "unbounded", discard: true },
432 );
433​
434export const clearProviderSessionContinuationMarkers = (threadIds: ReadonlyArray<ThreadId>) =>
435 Effect.gen(function* () {
436 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
437 yield* clearContinuationMarkers(directory, threadIds);
438 }).pipe(Effect.mapError(toServerUpdateThreadContinuationError));
439​
440export const reconcileProviderSessions = Effect.gen(function* () {
441 const crypto = yield* Crypto.Crypto;
442 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
443 const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
444 const providerService = yield* ProviderService.ProviderService;
445 const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
446​
447 const liveThreadIds = new Set(
448 (yield* providerService.listSessions()).map((session) => session.threadId),
449 );
450 const { threads } = yield* query.getCommandReadModel();
451 const orphanedThreads = threads.filter(
452 (thread) =>
453 thread.session !== null &&
454 (thread.session.status === "starting" ||
455 thread.session.status === "running" ||
456 thread.session.activeTurnId !== null) &&
457 !liveThreadIds.has(thread.id),
458 );
459​
460 for (const thread of orphanedThreads) {
461 const session = thread.session;
462 if (session === null) {
463 continue;
464 }
465 const binding = yield* directory.getBinding(thread.id).pipe(
466 Effect.catchCause((cause) =>
467 Cause.hasInterrupts(cause)
468 ? Effect.failCause(cause)
469 : Effect.logWarning("failed to read orphaned provider session directory binding", {
470 threadId: thread.id,
471 cause,
472 }).pipe(Effect.as(Option.none())),
473 ),
474 );
475 const continuationMarkerPresent =
476 Option.isSome(binding) && hasServerUpdateContinuationMarker(binding.value.runtimePayload);
477 const continuationTurnId = Option.isSome(binding)
478 ? readServerUpdateContinuationTurnId(binding.value.runtimePayload)
479 : null;
480 const continuationMarked =
481 continuationTurnId !== null &&
482 (session.activeTurnId === null || continuationTurnId === session.activeTurnId);
483 const settleAsError = (lastError: string) =>
484 Effect.gen(function* () {
485 yield* Effect.gen(function* () {
486 if (Option.isSome(binding)) {
487 yield* directory.upsert({
488 ...binding.value,
489 status: "stopped",
490 runtimePayload: {
491 ...readRuntimePayload(binding.value.runtimePayload),
492 activeTurnId: null,
493 ...(continuationMarkerPresent ? { [SERVER_UPDATE_CONTINUATION_KEY]: null } : {}),
494 },
495 });
496 }
497 }).pipe(
498 Effect.catchCause((cause) =>
499 Cause.hasInterrupts(cause)
500 ? Effect.failCause(cause)
501 : Effect.logWarning(
502 "failed to reconcile orphaned provider session directory binding",
503 { threadId: thread.id, cause },
504 ),
505 ),
506 );
507​
508 yield* Effect.gen(function* () {
509 const reconciledAt = DateTime.formatIso(yield* DateTime.now);
510 yield* orchestrationEngine.dispatch({
511 type: "thread.session.set",
512 commandId: CommandId.make(yield* crypto.randomUUIDv4),
513 threadId: thread.id,
514 session: {
515 ...session,
516 status: "error",
517 activeTurnId: null,
518 lastError,
519 updatedAt: reconciledAt,
520 },
521 createdAt: reconciledAt,
522 });
523 }).pipe(
524 Effect.retry({ times: 1 }),
525 Effect.catchCause((cause) =>
526 Cause.hasInterrupts(cause)
527 ? Effect.failCause(cause)
528 : Effect.logWarning("failed to settle orphaned provider session projection", {
529 threadId: thread.id,
530 cause,
531 }),
532 ),
533 );
534 });
535​
536 if (
537 Option.isSome(binding) &&
538 continuationMarked &&
539 thread.archivedAt === null &&
540 thread.deletedAt === null
541 ) {
542 const prepared = yield* Effect.gen(function* () {
543 yield* directory.upsert({
544 ...binding.value,
545 status: "starting",
546 runtimePayload: {
547 ...readRuntimePayload(binding.value.runtimePayload),
548 activeTurnId: null,
549 },
550 });
551 const resumedAt = DateTime.formatIso(yield* DateTime.now);
552 yield* orchestrationEngine.dispatch({
553 type: "thread.session.set",
554 commandId: CommandId.make(yield* crypto.randomUUIDv4),
555 threadId: thread.id,
556 session: {
557 ...session,
558 status: "starting",
559 activeTurnId: null,
560 lastError: null,
561 updatedAt: resumedAt,
562 },
563 createdAt: resumedAt,
564 });
565 }).pipe(Effect.retry({ times: 1 }), Effect.exit);
566 if (Exit.isFailure(prepared)) {
567 if (Cause.hasInterrupts(prepared.cause)) {
568 return yield* Effect.failCause(prepared.cause);
569 }
570 yield* Effect.logWarning("failed to prepare provider session continuation", {
571 threadId: thread.id,
572 cause: prepared.cause,
573 });
574 yield* settleAsError(ORPHANED_PROVIDER_SESSION_ERROR);
575 continue;
576 }
577​
578 yield* forkParked(
579 Effect.gen(function* () {
580 const continuation = Effect.gen(function* () {
581 const providerInstanceId = binding.value.providerInstanceId;
582 if (providerInstanceId === undefined) {
583 return yield* new ProviderSessionContinuationError({
584 threadId: thread.id,
585 });
586 }
587 const capabilities = yield* providerService.getCapabilities(providerInstanceId);
588 yield* providerService.sendTurn({
589 threadId: thread.id,
590 ...(capabilities.promptlessTurnContinuation === true
591 ? { continuation: true }
592 : { input: SERVER_UPDATE_CONTINUATION_PROMPT }),
593 interactionMode: thread.interactionMode,
594 });
595 });
596 const continuationExit = yield* Effect.exit(continuation);
597 if (Exit.isSuccess(continuationExit) || Cause.hasInterrupts(continuationExit.cause)) {
598 if (Exit.isSuccess(continuationExit)) {
599 yield* clearContinuationMarkers(directory, [thread.id]).pipe(
600 Effect.uninterruptible,
601 Effect.catchCause((cause) =>
602 Effect.logWarning("failed to clear completed provider session continuation", {
603 threadId: thread.id,
604 cause,
605 }),
606 ),
607 );
608 }
609 return;
610 }
611 yield* Effect.logWarning("failed to continue provider session after server update", {
612 threadId: thread.id,
613 cause: continuationExit.cause,
614 });
615 yield* settleAsError(
616 "Could not continue this thread after the server update. Send a new message to continue.",
617 ).pipe(Effect.ignoreCause);
618 }),
619 );
620 continue;
621 }
622​
623 yield* settleAsError(ORPHANED_PROVIDER_SESSION_ERROR);
624 }
625}).pipe(
626 Effect.catchCause((cause) =>
627 Cause.hasInterrupts(cause)
628 ? Effect.failCause(cause)
629 : Effect.logWarning("provider session startup reconciliation failed", { cause }),
630 ),
631);
632​
633interface StartupOptions {
634 readonly activate?: Effect.Effect<void>;
635 readonly awaitAuxiliaryParked?: Effect.Effect<void>;
636 readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
638​
639export const autoPullProjects = Effect.fn("autoPullProjects")(function* (
640 projects: ReadonlyArray<OrchestrationProjectShell>,
641) {
642 const git = yield* GitVcsDriver.GitVcsDriver;
643 const workspaceRoots = [
644 ...new Set(
645 projects
646 .filter((project) => project.autoPull === true)
647 .map((project) => project.workspaceRoot),
648 ),
649 ];
650​
651 yield* Effect.forEach(
652 workspaceRoots,
653 (cwd) =>
654 Effect.gen(function* () {
655 const status = yield* git.statusDetails(cwd);
656 if (
657 !status.isRepo ||
658 !status.isDefaultBranch ||
659 !status.hasUpstream ||
660 status.hasWorkingTreeChanges ||
661 status.aheadCount > 0
662 ) {
663 yield* Effect.logDebug("Skipped automatic project pull", {
664 cwd,
665 reason: !status.isRepo
666 ? "not-a-repository"
667 : !status.isDefaultBranch
668 ? "not-on-default-branch"
669 : !status.hasUpstream
670 ? "no-upstream"
671 : status.hasWorkingTreeChanges
672 ? "working-tree-changes"
673 : "local-commits",
674 });
675 return;
676 }
677​
678 if (status.behindCount <= 0) return;
679​
680 const result = yield* git.pullCurrentBranch(cwd);
681 yield* Effect.logDebug("Automatic project pull completed", {
682 cwd,
683 status: result.status,
684 refName: result.refName,
685 });
686 }).pipe(
687 Effect.catch((cause) =>
688 Effect.logWarning("Automatic project pull failed", {
689 cwd,
690 cause,
691 }),
692 ),
693 ),
694 { concurrency: 4, discard: true },
695 );
696});
697​
698export const make = (options?: StartupOptions) =>
699 Effect.gen(function* () {
700 const serverConfig = yield* ServerConfig.ServerConfig;
701 const keybindings = yield* Keybindings.Keybindings;
702 const orchestrationReactor = yield* OrchestrationReactor.OrchestrationReactor;
703 const providerSessionReaper = yield* ProviderSessionReaper.ProviderSessionReaper;
704 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
705 const serverSettings = yield* ServerSettings.ServerSettingsService;
706 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
707 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
708 const providerSessionDirectory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
709 const crypto = yield* Crypto.Crypto;
710 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
711​
712 const commandGate = yield* makeCommandGate;
713 const httpListening = yield* Deferred.make<void>();
714 const reactorScope = yield* Scope.make("sequential");
715​
716 const syncAutoPullProjects = projectionSnapshotQuery.getShellSnapshot().pipe(
717 Effect.flatMap((snapshot) => autoPullProjects(snapshot.projects)),
718 Effect.catch((cause) =>
719 Effect.logWarning("Failed to load projects for automatic pull", { cause }),
720 ),
721 );
722​
723 yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
724​
725 const startup = Effect.gen(function* () {
726 yield* Effect.logDebug("startup phase: starting keybindings runtime");
727 yield* runStartupPhase(
728 "keybindings.start",
729 keybindings.start.pipe(
730 Effect.catch((error) =>
731 Effect.logWarning("failed to start keybindings runtime", {
732 path: error.configPath,
733 detail: error.detail,
734 cause: error.cause,
735 }),
736 ),
737 ),
738 );
739​
740 yield* Effect.logDebug("startup phase: starting server settings runtime");
741 yield* runStartupPhase(
742 "settings.start",
743 serverSettings.start.pipe(
744 Effect.catch((error) =>
745 Effect.logWarning("failed to start server settings runtime", {
746 path: error.settingsPath,
747 operation: error.operation,
748 providerInstanceId: error.providerInstanceId,
749 environmentVariable: error.environmentVariable,
750 cause: error.cause,
751 }),
752 ),
753 ),
754 );
755​
756 yield* Effect.logDebug("startup phase: parking orchestration roots at activation");
757 yield* runStartupPhase(
758 "reactors.start",
759 Effect.gen(function* () {
760 yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
761 yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));
762 }),
763 );
764​
765 yield* runStartupPhase("provider-sessions.reconcile", reconcileProviderSessions);
766​
767 yield* Effect.logDebug("startup phase: syncing clean projects");
768 yield* runStartupPhase("projects.auto-pull", syncAutoPullProjects);
769​
770 const welcomeBase = yield* resolveWelcomeBase;
771 const environment = yield* serverEnvironment.getDescriptor;
772 yield* Effect.logDebug("startup phase: preparing welcome payload");
773​
774 if (serverConfig.autoBootstrapProjectFromCwd) {
775 yield* forkParked(
776 runStartupPhase(
777 "welcome.autobootstrap",
778 Effect.gen(function* () {
779 const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets.pipe(
780 Effect.provideService(Crypto.Crypto, crypto),
781 );
782 if (!bootstrapTargets.bootstrapProjectId && !bootstrapTargets.bootstrapThreadId) {
783 return;
784 }
785​
786 yield* Effect.logDebug("startup phase: publishing bootstrapped welcome event", {
787 environmentId: environment.environmentId,
788 cwd: welcomeBase.cwd,
789 projectName: welcomeBase.projectName,
790 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
791 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
792 });
793 yield* lifecycleEvents.publish({
794 version: 1,
795 type: "welcome",
796 payload: {
797 environment,
798 ...welcomeBase,
799 ...bootstrapTargets,
800 },
801 });
802 }).pipe(
803 Effect.catch((cause) =>
804 Effect.logWarning("startup auto-bootstrap welcome failed", {
805 cause,
806 }),
807 ),
808 ),
809 ),
810 );
811 }
812​
813 yield* forkParked(
814 Effect.gen(function* () {
815 yield* Effect.logDebug("startup phase: recording startup heartbeat");
816 yield* recordStartupHeartbeat.pipe(
817 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
818 Effect.withSpan("server.startup.heartbeat.record"),
819 Effect.ignoreCause({ log: true }),
820 );
821 if (serverConfig.startupPresentation === "headless") {
822 const accessInfo = yield* issueHeadlessServeAccessInfo();
823 yield* runStartupPhase(
824 "headless.output",
825 Console.log(formatHeadlessServeOutput(accessInfo)),
826 );
827 } else {
828 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
829 if (serverConfig.mode !== "desktop") {
830 yield* Effect.logInfo(
831 "Authentication required. Open T3 Code using the pairing URL.",
832 ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
833 }
834 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
835 }
836 }),
837 );
838​
839 yield* Effect.logDebug("startup phase: waiting for http listener");
840 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
841 yield* runStartupPhase(
842 "auxiliary-roots.parked",
843 options?.awaitAuxiliaryParked ?? Effect.void,
844 );
845​
846 // This is the prepared boundary. Every dependency has been acquired and
847 // every runtime root has confirmed that it is parked before this request.
848 const updateOutcome = yield* launcher.prepareTrial;
849 yield* runStartupPhase(
850 "welcome.publish",
851 lifecycleEvents.publish({
852 version: 1,
853 type: "welcome",
854 payload: { environment, ...welcomeBase },
855 }),
856 );
857 yield* options?.activate ?? Effect.void;
858​
859 yield* Effect.logDebug("Accepting commands");
860 yield* commandGate.signalCommandReady;
861 yield* runStartupPhase(
862 "ready.publish",
863 lifecycleEvents.publish({
864 version: 1,
865 type: "ready",
866 payload: {
867 at: DateTime.formatIso(yield* DateTime.now),
868 environment,
869 ...(updateOutcome === undefined ? {} : { updateOutcome }),
870 },
871 }),
872 );
873 yield* Effect.logDebug("startup phase: complete");
874 }).pipe(
875 Effect.annotateSpans({
876 "server.mode": serverConfig.mode,
877 "server.port": serverConfig.port,
878 "server.host": serverConfig.host ?? "default",
879 }),
880 Effect.withSpan("server.startup", { kind: "server", root: true }),
881 );
882​
883 yield* Effect.forkScoped(
884 Effect.exit(startup).pipe(
885 Effect.flatMap((startupExit) => {
886 if (Exit.isSuccess(startupExit)) return Effect.void;
887 const error = new ServerRuntimeStartupError({
888 mode: serverConfig.mode,
889 host: serverConfig.host ?? null,
890 port: serverConfig.port,
891 cause: startupExit.cause,
892 });
893 return Effect.logError("server runtime startup failed", {
894 cause: startupExit.cause,
895 }).pipe(
896 Effect.andThen(commandGate.failCommandReady(error)),
897 Effect.andThen(options?.abort?.(error) ?? Effect.void),
898 );
899 }),
900 ),
901 );
902​
903 return {
904 awaitCommandReady: commandGate.awaitCommandReady,
905 markHttpListening: Deferred.succeed(httpListening, undefined),
906 markRunningProviderSessionsForContinuation: markRunningProviderSessionsForContinuation.pipe(
907 Effect.provideService(
908 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
909 projectionSnapshotQuery,
910 ),
911 Effect.provideService(
912 ProviderSessionDirectory.ProviderSessionDirectory,
913 providerSessionDirectory,
914 ),
915 ),
916 clearProviderSessionContinuationMarkers: (threadIds) =>
917 clearProviderSessionContinuationMarkers(threadIds).pipe(
918 Effect.provideService(
919 ProviderSessionDirectory.ProviderSessionDirectory,
920 providerSessionDirectory,
921 ),
922 ),
923 enqueueCommand: commandGate.enqueueCommand,
924 } satisfies ServerRuntimeStartup["Service"];
925 });
926​
927export const layerWithOptions = (options?: StartupOptions) =>
928 Layer.effect(ServerRuntimeStartup, make(options));
929​
930export const layer = layerWithOptions();