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