Open History to see the last commit
1import {
2 AuthOrchestrationReadScope,
3 EnvironmentHttpApi,
4 type OrchestrationProjectShell,
5} from "@t3tools/contracts";
6import * as DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8import * as Result from "effect/Result";
9import * as Predicate from "effect/Predicate";
10import * as Schema from "effect/Schema";
11import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
12import * as SqlClient from "effect/sql/SqlClient";
13
14import {
15 annotateEnvironmentRequest,
16 failEnvironmentInternal,
17 failEnvironmentInvalidRequest,
18 failEnvironmentNotFound,
19 requireEnvironmentScope,
20} from "../auth/http.ts";
21import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
22import { traceLocalHandlerWork } from "../cloud/traceRelayRequest.ts";
23import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
24import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
25import {
26 buildBoundedThreadProjection,
27 decodeThreadHistoryCursor,
28 InvalidThreadHistoryCursorError,
29 THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
30 THREAD_HISTORY_PAGE_POLICY,
31 OLDER_THREAD_USER_TURN_LIMIT,
32} from "./threadHistoryPaging.ts";
33import * as ThreadManagementService from "./ThreadManagementService.ts";
34import * as ProjectStore from "./ProjectStore.ts";
35import {
36 buildActiveShellSnapshot,
37 loadShellSnapshotParts,
38 shellSnapshotForSubscriber,
39} from "./ShellStream.ts";
40import { boundedSnapshotResponseFields } from "./ThreadStream.ts";
41import { projectThreadProjectionForWire } from "./WireProjection.ts";
42
43const isThreadTranscriptTooLargeError = Schema.is(
44 ThreadManagementService.ThreadTranscriptTooLargeError,
45);
46
47function isThreadNotFound(error: unknown): boolean {
48 return (
49 Predicate.hasProperty(error, "cause") &&
50 Predicate.hasProperty(error.cause, "_tag") &&
51 error.cause._tag === "ProjectionStoreThreadNotFoundError"
52 );
53}
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 available enrichment only; git probes can take a minute and exceed shell-snapshot budgets.
72 projectEnrichment.getAvailable(project.workspaceRoot).pipe(
73 Effect.map((enrichment) => ({
74 ...project,
75 repositoryIdentity: enrichment.repositoryIdentity,
76 })),
77 ),
78 { concurrency: 16 },
79 ),
80 );
81
82 const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")(
83 function* (options: {
84 readonly omitIdleSubagents: boolean;
85 readonly omitOlderSettled: boolean;
86 }) {
87 const base = buildActiveShellSnapshot(
88 yield* loadShellSnapshotParts({
89 sql,
90 readThreads: threadManagement.readShellSnapshot({ location: "active" }),
91 listProjects: projectStore.listShells(),
92 latestSequence: applicationEvents.latestApplicationSequence,
93 }),
94 );
95 const { snapshot } = shellSnapshotForSubscriber(base, {
96 ...options,
97 now: yield* DateTime.now,
98 });
99 const projects = yield* enrichProjectShells(base.projects);
100 return { ...snapshot, projects };
101 },
102 );
103
104 const loadThreadSnapshot = Effect.fn("http.orchestration.loadThreadSnapshot")(function* (
105 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
106 failureReason:
107 | "orchestration_thread_snapshot_failed"
108 | "orchestration_thread_bounded_snapshot_failed"
109 | "orchestration_thread_history_failed",
110 ) {
111 return yield* threadManagement.getThreadSnapshot(threadId).pipe(
112 Effect.map((snapshot) => ({
113 ...snapshot,
114 projection: projectThreadProjectionForWire(snapshot.projection),
115 })),
116 Effect.catch(
117 Effect.fnUntraced(function* (error) {
118 if (isThreadNotFound(error)) {
119 return yield* failEnvironmentNotFound("thread_not_found");
120 }
121 return yield* failEnvironmentInternal(failureReason, error);
122 }),
123 ),
124 );
125 });
126
127 const loadThreadSnapshotWindow = Effect.fn("http.orchestration.loadThreadSnapshotWindow")(
128 function* (
129 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
130 anchorItemId?: Parameters<
131 typeof threadManagement.getThreadSnapshotWindow
132 >[1]["anchorItemId"],
133 anchorThreadId?: Parameters<
134 typeof threadManagement.getThreadSnapshotWindow
135 >[1]["anchorThreadId"],
136 ) {
137 return yield* threadManagement
138 .getThreadSnapshotWindow(threadId, {
139 rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
140 userTurnLimit:
141 anchorItemId === undefined
142 ? THREAD_HISTORY_PAGE_POLICY.maxUserTurns
143 : OLDER_THREAD_USER_TURN_LIMIT,
144 ...(anchorItemId === undefined ? {} : { anchorItemId }),
145 ...(anchorThreadId === undefined ? {} : { anchorThreadId }),
146 })
147 .pipe(
148 Effect.map((snapshot) => ({
149 ...snapshot,
150 projection: projectThreadProjectionForWire(snapshot.projection),
151 })),
152 Effect.catch(
153 Effect.fnUntraced(function* (error) {
154 if (isThreadNotFound(error)) {
155 return yield* failEnvironmentNotFound("thread_not_found");
156 }
157 return yield* failEnvironmentInternal("orchestration_thread_history_failed", error);
158 }),
159 ),
160 );
161 },
162 );
163
164 return handlers
165 .handle(
166 "shellSnapshot",
167 Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
168 yield* annotateEnvironmentRequest(args.endpoint.name);
169 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
170 return yield* loadShellSnapshot({
171 omitIdleSubagents: args.query.omitIdleSubagents === "1",
172 omitOlderSettled: args.query.omitOlderSettled === "1",
173 }).pipe(
174 traceLocalHandlerWork,
175 Effect.catch((cause) =>
176 failEnvironmentInternal("orchestration_snapshot_failed", cause),
177 ),
178 );
179 }),
180 )
181 .handle(
182 "threadSnapshot",
183 Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {
184 yield* annotateEnvironmentRequest(args.endpoint.name);
185 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
186 const snapshot = yield* loadThreadSnapshot(
187 args.params.threadId,
188 "orchestration_thread_snapshot_failed",
189 ).pipe(traceLocalHandlerWork);
190 return {
191 snapshotSequence: snapshot.snapshotSequence,
192 projection: snapshot.projection,
193 };
194 }),
195 )
196 .handle(
197 "threadTranscript",
198 Effect.fn("environment.orchestration.threadTranscript")(function* (args) {
199 yield* annotateEnvironmentRequest(args.endpoint.name);
200 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
201 return yield* threadManagement.getThreadTranscript(args.params.threadId).pipe(
202 Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment),
203 traceLocalHandlerWork,
204 Effect.catch(
205 Effect.fnUntraced(function* (error) {
206 if (isThreadTranscriptTooLargeError(error)) {
207 return yield* failEnvironmentInvalidRequest("thread_transcript_too_large");
208 }
209 if (isThreadNotFound(error)) {
210 return yield* failEnvironmentNotFound("thread_not_found");
211 }
212 return yield* failEnvironmentInternal(
213 "orchestration_thread_snapshot_failed",
214 error,
215 );
216 }),
217 ),
218 );
219 }),
220 )
221 .handle(
222 "threadBoundedSnapshot",
223 Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) {
224 yield* annotateEnvironmentRequest(args.endpoint.name);
225 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
226 const snapshot = yield* loadThreadSnapshotWindow(args.params.threadId).pipe(
227 traceLocalHandlerWork,
228 );
229 const bounded = buildBoundedThreadProjection({
230 projection: snapshot.projection,
231 snapshotSequence: snapshot.snapshotSequence,
232 });
233 return {
234 snapshotSequence: snapshot.snapshotSequence,
235 ...boundedSnapshotResponseFields({
236 bounded,
237 compactTurnItems: args.query.compactTurnItems === "1",
238 dedupeBodies: args.query.dedupeBodies === "1",
239 compactIds: args.query.compactIds === "1",
240 }),
241 };
242 }),
243 )
244 .handle(
245 "threadHistoryPage",
246 Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) {
247 yield* annotateEnvironmentRequest(args.endpoint.name);
248 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
249 const decoded = yield* Effect.try(() =>
250 decodeThreadHistoryCursor(args.query.cursor),
251 ).pipe(Effect.result);
252 if (Result.isFailure(decoded)) {
253 const cause = decoded.failure.cause;
254 if (cause instanceof InvalidThreadHistoryCursorError)
255 return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
256 return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);
257 }
258 return yield* threadManagement
259 .getThreadHistoryPage(
260 args.params.threadId,
261 args.query.cursor,
262 args.query.throughEntryId,
263 args.query.view === "conversation",
264 )
265 .pipe(
266 Effect.map((page) =>
267 args.query.compactIds === "1" ? { ...page, idTable: true as const } : page,
268 ),
269 traceLocalHandlerWork,
270 Effect.catch(
271 Effect.fnUntraced(function* (cause) {
272 if (isThreadNotFound(cause))
273 return yield* failEnvironmentNotFound("thread_not_found");
274 return yield* failEnvironmentInternal(
275 "orchestration_thread_history_failed",
276 cause,
277 );
278 }),
279 ),
280 );
281 }),
282 );
283 }),
284);