Open History to see the last commit
1import {
2 AuthOrchestrationReadScope,
3 EnvironmentHttpApi,
4 type OrchestrationProjectShell,
5} from "@t3tools/contracts";
6import * as Effect from "effect/Effect";
7import * as Result from "effect/Result";
8import * as Predicate from "effect/Predicate";
9import * as Schema from "effect/Schema";
10import * as HttpServerResponse from "effect/http/HttpServerResponse";
11import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
12import { HttpApiSchemaError } from "effect/http-api/HttpApiError";
13import * as SqlClient from "effect/sql/SqlClient";
14
15import {
16 annotateEnvironmentRequest,
17 failEnvironmentInternal,
18 failEnvironmentInvalidRequest,
19 failEnvironmentNotFound,
20 requireEnvironmentScope,
21} from "../auth/http.ts";
22import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
23import { traceLocalHandlerWork } from "../cloud/traceRelayRequest.ts";
24import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
25import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
26import {
27 buildBoundedThreadProjection,
28 decodeThreadHistoryCursor,
29 InvalidThreadHistoryCursorError,
30 THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
31 THREAD_HISTORY_PAGE_POLICY,
32 OLDER_THREAD_USER_TURN_LIMIT,
33} from "./threadHistoryPaging.ts";
34import * as ThreadManagementService from "./ThreadManagementService.ts";
35import * as ProjectStore from "./ProjectStore.ts";
36import {
37 loadShellUnlessResumable,
38 loadSubscriberShellSnapshot,
39 projectIdentitiesDigest,
40} from "./ShellStream.ts";
41import { encodeThreadSnapshotBody } from "./threadSnapshotBody.ts";
42import { boundedSnapshotResponseFields } from "./ThreadStream.ts";
43import { projectThreadProjectionForWire } from "./WireProjection.ts";
44
45const isInvalidThreadHistoryCursorError = Schema.is(InvalidThreadHistoryCursorError);
46
47const isThreadTranscriptTooLargeError = Schema.is(
48 ThreadManagementService.ThreadTranscriptTooLargeError,
49);
50
51function isThreadNotFound(error: unknown): boolean {
52 return (
53 Predicate.hasProperty(error, "cause") &&
54 Predicate.hasProperty(error.cause, "_tag") &&
55 error.cause._tag === "ProjectionStoreThreadNotFoundError"
56 );
57}
58
59export const layer = HttpApiBuilder.group(
60 EnvironmentHttpApi,
61 "orchestration",
62 Effect.fnUntraced(function* (handlers) {
63 const sql = yield* SqlClient.SqlClient;
64 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
65 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
66 const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore;
67 const projectStore = yield* ProjectStore.ProjectStoreV2;
68 const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
69
70 const enrichProjectShells = Effect.fn("http.orchestration.enrichProjectShells")(
71 (projects: ReadonlyArray<OrchestrationProjectShell>) =>
72 Effect.forEach(
73 projects,
74 (project) =>
75 // Use available enrichment only; git probes can take a minute and exceed shell-snapshot budgets.
76 projectEnrichment.getAvailable(project.workspaceRoot).pipe(
77 Effect.map((enrichment) => ({
78 ...project,
79 repositoryIdentity: enrichment.repositoryIdentity,
80 })),
81 ),
82 { concurrency: 16 },
83 ),
84 );
85
86 const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")(
87 function* (options: {
88 readonly omitIdleSubagents: boolean;
89 readonly omitOlderSettled: boolean;
90 }) {
91 const { snapshot } = yield* loadSubscriberShellSnapshot({
92 sql,
93 listShellIndex: threadManagement.listActiveShellIndex(),
94 readThreads: (threadIds) =>
95 threadManagement.readShellSnapshot({
96 location: "active",
97 ...(threadIds === undefined ? {} : { threadIds }),
98 }),
99 listProjects: projectStore.listShells(),
100 latestSequence: applicationEvents.latestApplicationSequence,
101 options,
102 });
103 const projects = yield* enrichProjectShells(snapshot.projects);
104 return { ...snapshot, projects, projectIdentities: projectIdentitiesDigest(projects) };
105 },
106 );
107
108 // A client that holds rows names their cursor; a small answer tells it to keep them.
109 const answerShellSnapshot = Effect.fn("http.orchestration.answerShellSnapshot")((query: {
110 readonly omitIdleSubagents?: string;
111 readonly omitOlderSettled?: string;
112 readonly resumeFrom?: string;
113 }) => {
114 const resumeFrom = query.resumeFrom === undefined ? Number.NaN : Number(query.resumeFrom);
115 return loadShellUnlessResumable({
116 events: applicationEvents,
117 resumeFrom: Number.isSafeInteger(resumeFrom) && resumeFrom >= 0 ? resumeFrom : undefined,
118 loadSnapshot: loadShellSnapshot({
119 omitIdleSubagents: query.omitIdleSubagents === "1",
120 omitOlderSettled: query.omitOlderSettled === "1",
121 }),
122 });
123 });
124
125 const loadThreadSnapshot = Effect.fn("http.orchestration.loadThreadSnapshot")(function* (
126 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
127 failureReason:
128 | "orchestration_thread_snapshot_failed"
129 | "orchestration_thread_bounded_snapshot_failed"
130 | "orchestration_thread_history_failed",
131 ) {
132 return yield* threadManagement.getThreadSnapshot(threadId).pipe(
133 Effect.map((snapshot) => ({
134 ...snapshot,
135 projection: projectThreadProjectionForWire(snapshot.projection),
136 })),
137 Effect.catch(
138 Effect.fnUntraced(function* (error) {
139 if (isThreadNotFound(error)) {
140 return yield* failEnvironmentNotFound("thread_not_found");
141 }
142 return yield* failEnvironmentInternal(failureReason, error);
143 }),
144 ),
145 );
146 });
147
148 const loadThreadSnapshotWindow = Effect.fn("http.orchestration.loadThreadSnapshotWindow")(
149 function* (
150 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
151 anchorItemId?: Parameters<
152 typeof threadManagement.getThreadSnapshotWindow
153 >[1]["anchorItemId"],
154 anchorThreadId?: Parameters<
155 typeof threadManagement.getThreadSnapshotWindow
156 >[1]["anchorThreadId"],
157 deferWork = false,
158 ) {
159 return yield* threadManagement
160 .getThreadSnapshotWindow(threadId, {
161 rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
162 deferWork,
163 userTurnLimit:
164 anchorItemId === undefined
165 ? THREAD_HISTORY_PAGE_POLICY.maxUserTurns
166 : OLDER_THREAD_USER_TURN_LIMIT,
167 ...(anchorItemId === undefined ? {} : { anchorItemId }),
168 ...(anchorThreadId === undefined ? {} : { anchorThreadId }),
169 })
170 .pipe(
171 Effect.map((snapshot) => ({
172 ...snapshot,
173 projection: projectThreadProjectionForWire(snapshot.projection),
174 })),
175 Effect.catch(
176 Effect.fnUntraced(function* (error) {
177 if (isThreadNotFound(error)) {
178 return yield* failEnvironmentNotFound("thread_not_found");
179 }
180 return yield* failEnvironmentInternal("orchestration_thread_history_failed", error);
181 }),
182 ),
183 );
184 },
185 );
186
187 return handlers
188 .handle(
189 "shellSnapshot",
190 Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
191 yield* annotateEnvironmentRequest(args.endpoint.name);
192 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
193 return yield* answerShellSnapshot(args.query).pipe(
194 traceLocalHandlerWork,
195 Effect.catch((cause) =>
196 failEnvironmentInternal("orchestration_snapshot_failed", cause),
197 ),
198 );
199 }),
200 )
201 .handle(
202 "threadSnapshot",
203 Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {
204 yield* annotateEnvironmentRequest(args.endpoint.name);
205 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
206 const body = yield* loadThreadSnapshot(
207 args.params.threadId,
208 "orchestration_thread_snapshot_failed",
209 ).pipe(
210 Effect.flatMap((snapshot) =>
211 encodeThreadSnapshotBody({
212 snapshotSequence: snapshot.snapshotSequence,
213 projection: snapshot.projection,
214 }).pipe(
215 // The same defect, and the same empty 500, as a failed response encoding.
216 Effect.catch((cause) =>
217 Effect.die(new HttpApiSchemaError({ kind: "Body", cause })),
218 ),
219 ),
220 ),
221 traceLocalHandlerWork,
222 );
223 return HttpServerResponse.stream(body, { contentType: "application/json" });
224 }),
225 )
226 .handle(
227 "threadTranscript",
228 Effect.fn("environment.orchestration.threadTranscript")(function* (args) {
229 yield* annotateEnvironmentRequest(args.endpoint.name);
230 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
231 return yield* threadManagement.getThreadTranscript(args.params.threadId).pipe(
232 Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment),
233 traceLocalHandlerWork,
234 Effect.catch(
235 Effect.fnUntraced(function* (error) {
236 if (isThreadTranscriptTooLargeError(error)) {
237 return yield* failEnvironmentInvalidRequest("thread_transcript_too_large");
238 }
239 if (isThreadNotFound(error)) {
240 return yield* failEnvironmentNotFound("thread_not_found");
241 }
242 return yield* failEnvironmentInternal(
243 "orchestration_thread_snapshot_failed",
244 error,
245 );
246 }),
247 ),
248 );
249 }),
250 )
251 .handle(
252 "threadBoundedSnapshot",
253 Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) {
254 yield* annotateEnvironmentRequest(args.endpoint.name);
255 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
256 const snapshot = yield* loadThreadSnapshotWindow(
257 args.params.threadId,
258 undefined,
259 undefined,
260 args.query.deferWork === "1",
261 ).pipe(traceLocalHandlerWork);
262 const bounded = buildBoundedThreadProjection({
263 projection: snapshot.projection,
264 snapshotSequence: snapshot.snapshotSequence,
265 });
266 return {
267 snapshotSequence: snapshot.snapshotSequence,
268 ...boundedSnapshotResponseFields({
269 bounded,
270 compactTurnItems: args.query.compactTurnItems === "1",
271 dedupeBodies: args.query.dedupeBodies === "1",
272 compactIds: args.query.compactIds === "1",
273 }),
274 };
275 }),
276 )
277 .handle(
278 "threadHistoryPage",
279 Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) {
280 yield* annotateEnvironmentRequest(args.endpoint.name);
281 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
282 const decoded = Result.try(() => decodeThreadHistoryCursor(args.query.cursor));
283 if (Result.isFailure(decoded)) {
284 const cause = decoded.failure;
285 if (isInvalidThreadHistoryCursorError(cause))
286 return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
287 return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);
288 }
289 return yield* threadManagement
290 .getThreadHistoryPage(
291 args.params.threadId,
292 args.query.cursor,
293 args.query.throughEntryId,
294 args.query.view === "conversation",
295 args.query.view === "work"
296 ? "work"
297 : args.query.deferWork === "1"
298 ? "deferred"
299 : undefined,
300 )
301 .pipe(
302 Effect.map((page) =>
303 args.query.compactIds === "1" ? { ...page, idTable: true as const } : page,
304 ),
305 traceLocalHandlerWork,
306 Effect.catch(
307 Effect.fnUntraced(function* (cause) {
308 if (isThreadNotFound(cause))
309 return yield* failEnvironmentNotFound("thread_not_found");
310 return yield* failEnvironmentInternal(
311 "orchestration_thread_history_failed",
312 cause,
313 );
314 }),
315 ),
316 );
317 }),
318 );
319 }),
320);