Open History to see the last commit
1import {
2 AuthOrchestrationReadScope,
3 EnvironmentHttpApi,
4 ThreadId,
5 TurnItemId,
6 type OrchestrationProjectShell,
7} from "@t3tools/contracts";
8import * as Effect from "effect/Effect";
9import * as Predicate from "effect/Predicate";
10import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
11import * as SqlClient from "effect/unstable/sql/SqlClient";
12
13import {
14 annotateEnvironmentRequest,
15 failEnvironmentInternal,
16 failEnvironmentInvalidRequest,
17 failEnvironmentNotFound,
18 requireEnvironmentScope,
19} from "../auth/http.ts";
20import * as OrchestrationEventStore from "../persistence/Services/OrchestrationEventStore.ts";
21import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
22import {
23 buildBoundedThreadProjection,
24 decodeThreadHistoryCursor,
25 InvalidThreadHistoryCursorError,
26 selectHistoryPageFromCursor,
27 THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
28 THREAD_HISTORY_PAGE_POLICY,
29 OLDER_THREAD_USER_TURN_LIMIT,
30} from "./threadHistoryPaging.ts";
31import * as ThreadManagementService from "./ThreadManagementService.ts";
32import * as ProjectStore from "./ProjectStore.ts";
33import { buildActiveShellSnapshot } from "./ShellStream.ts";
34import { projectThreadProjectionForWire } from "./WireProjection.ts";
35
36function isThreadNotFound(error: unknown): boolean {
37 return (
38 Predicate.hasProperty(error, "cause") &&
39 Predicate.hasProperty(error.cause, "_tag") &&
40 error.cause._tag === "ProjectionStoreThreadNotFoundError"
41 );
42}
43
44function selectHistoryPageFromCursorOrError(
45 input: Parameters<typeof selectHistoryPageFromCursor>[0],
46):
47 | { readonly _tag: "ok"; readonly page: ReturnType<typeof selectHistoryPageFromCursor> }
48 | { readonly _tag: "invalid_cursor" }
49 | { readonly _tag: "error"; readonly cause: unknown } {
50 try {
51 return { _tag: "ok", page: selectHistoryPageFromCursor(input) };
52 } catch (cause) {
53 if (cause instanceof InvalidThreadHistoryCursorError) {
54 return { _tag: "invalid_cursor" };
55 }
56 return { _tag: "error", cause };
57 }
58}
59
60/**
61 * Serves orchestration V2 snapshots over HTTP so clients can load the
62 * (potentially large) shell and thread projections off the socket; gzip
63 * compressible and cacheable — and then resume the WebSocket subscription via
64 * `afterSequence`.
65 */
66export const orchestrationHttpApiLayer = HttpApiBuilder.group(
67 EnvironmentHttpApi,
68 "orchestration",
69 Effect.fnUntraced(function* (handlers) {
70 const sql = yield* SqlClient.SqlClient;
71 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
72 const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore;
73 const projectStore = yield* ProjectStore.ProjectStoreV2;
74 const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
75
76 const enrichProjectShells = Effect.fn("http.orchestration.enrichProjectShells")(
77 (projects: ReadonlyArray<OrchestrationProjectShell>) =>
78 Effect.forEach(
79 projects,
80 (project) =>
81 // Use immediately available enrichment only. Awaiting git-backed
82 // identity resolution can exceed the client shell-snapshot budget
83 // (ProcessRunner allows probes up to one minute). Background workers
84 // plus the WS enrichment subscription fill in repositoryIdentity.
85 projectEnrichment.getAvailable(project.workspaceRoot).pipe(
86 Effect.map((enrichment) => ({
87 ...project,
88 repositoryIdentity: enrichment.repositoryIdentity,
89 })),
90 ),
91 { concurrency: 16 },
92 ),
93 );
94
95 const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")(function* () {
96 const base = yield* sql.withTransaction(
97 Effect.gen(function* () {
98 const threads = yield* threadManagement.getShellSnapshot({ location: "active" });
99 return buildActiveShellSnapshot({
100 projects: yield* projectStore.listShells(),
101 threads,
102 snapshotSequence: yield* applicationEvents.latestApplicationSequence,
103 });
104 }),
105 );
106 const projects = yield* enrichProjectShells(base.projects);
107 return { ...base, projects };
108 });
109
110 const loadThreadSnapshot = Effect.fn("http.orchestration.loadThreadSnapshot")(function* (
111 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
112 failureReason:
113 | "orchestration_thread_snapshot_failed"
114 | "orchestration_thread_bounded_snapshot_failed"
115 | "orchestration_thread_history_failed",
116 ) {
117 return yield* threadManagement.getThreadSnapshot(threadId).pipe(
118 Effect.map((snapshot) => ({
119 ...snapshot,
120 projection: projectThreadProjectionForWire(snapshot.projection),
121 })),
122 Effect.catch(
123 Effect.fnUntraced(function* (error) {
124 if (isThreadNotFound(error)) {
125 return yield* failEnvironmentNotFound("thread_not_found");
126 }
127 return yield* failEnvironmentInternal(failureReason, error);
128 }),
129 ),
130 );
131 });
132
133 const loadThreadSnapshotWindow = Effect.fn("http.orchestration.loadThreadSnapshotWindow")(
134 function* (
135 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
136 anchorItemId?: Parameters<
137 typeof threadManagement.getThreadSnapshotWindow
138 >[1]["anchorItemId"],
139 anchorThreadId?: Parameters<
140 typeof threadManagement.getThreadSnapshotWindow
141 >[1]["anchorThreadId"],
142 ) {
143 return yield* threadManagement
144 .getThreadSnapshotWindow(threadId, {
145 rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
146 userTurnLimit:
147 anchorItemId === undefined
148 ? THREAD_HISTORY_PAGE_POLICY.maxUserTurns
149 : OLDER_THREAD_USER_TURN_LIMIT,
150 ...(anchorItemId === undefined ? {} : { anchorItemId }),
151 ...(anchorThreadId === undefined ? {} : { anchorThreadId }),
152 })
153 .pipe(
154 Effect.map((snapshot) => ({
155 ...snapshot,
156 projection: projectThreadProjectionForWire(snapshot.projection),
157 })),
158 Effect.catch(
159 Effect.fnUntraced(function* (error) {
160 if (isThreadNotFound(error)) {
161 return yield* failEnvironmentNotFound("thread_not_found");
162 }
163 return yield* failEnvironmentInternal("orchestration_thread_history_failed", error);
164 }),
165 ),
166 );
167 },
168 );
169
170 return handlers
171 .handle(
172 "shellSnapshot",
173 Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
174 yield* annotateEnvironmentRequest(args.endpoint.name);
175 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
176 return yield* loadShellSnapshot().pipe(
177 Effect.catch((cause) =>
178 failEnvironmentInternal("orchestration_snapshot_failed", cause),
179 ),
180 );
181 }),
182 )
183 .handle(
184 "threadSnapshot",
185 Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {
186 yield* annotateEnvironmentRequest(args.endpoint.name);
187 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
188 const snapshot = yield* loadThreadSnapshot(
189 args.params.threadId,
190 "orchestration_thread_snapshot_failed",
191 );
192 return {
193 snapshotSequence: snapshot.snapshotSequence,
194 projection: snapshot.projection,
195 };
196 }),
197 )
198 .handle(
199 "threadBoundedSnapshot",
200 Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) {
201 yield* annotateEnvironmentRequest(args.endpoint.name);
202 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
203 const snapshot = yield* loadThreadSnapshotWindow(args.params.threadId);
204 const bounded = buildBoundedThreadProjection({
205 projection: snapshot.projection,
206 snapshotSequence: snapshot.snapshotSequence,
207 });
208 return {
209 snapshotSequence: snapshot.snapshotSequence,
210 projection: bounded.projection,
211 historyCursor: bounded.historyCursor,
212 hasMoreHistory: bounded.hasMoreHistory,
213 latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
214 payloadBudgetExceeded: bounded.payloadBudgetExceeded,
215 };
216 }),
217 )
218 .handle(
219 "threadHistoryPage",
220 Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) {
221 yield* annotateEnvironmentRequest(args.endpoint.name);
222 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
223 let anchorItemId;
224 try {
225 anchorItemId = TurnItemId.make(decodeThreadHistoryCursor(args.query.cursor).si);
226 } catch (cause) {
227 if (cause instanceof InvalidThreadHistoryCursorError) {
228 return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
229 }
230 return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);
231 }
232 const decodedCursor = decodeThreadHistoryCursor(args.query.cursor);
233 const snapshot = yield* loadThreadSnapshotWindow(
234 args.params.threadId,
235 anchorItemId,
236 ThreadId.make(decodedCursor.st),
237 );
238 const pageOrError = selectHistoryPageFromCursorOrError({
239 items: snapshot.projection.visibleTurnItems,
240 cursor: args.query.cursor,
241 snapshotSequence: snapshot.snapshotSequence,
242 });
243 if (pageOrError._tag === "invalid_cursor") {
244 return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
245 }
246 if (pageOrError._tag === "error") {
247 return yield* failEnvironmentInternal(
248 "orchestration_thread_history_failed",
249 pageOrError.cause,
250 );
251 }
252 return {
253 snapshotSequence: snapshot.snapshotSequence,
254 items: pageOrError.page.items,
255 nextCursor: pageOrError.page.nextCursor,
256 hasMoreHistory: pageOrError.page.hasMoreHistory,
257 };
258 }),
259 );
260 }),
261);