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