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