Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

http.ts

289 lines11.2 KB

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 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 { loadSubscriberShellSnapshot } from "./ShellStream.ts";
35import { boundedSnapshotResponseFields } from "./ThreadStream.ts";
36import { projectThreadProjectionForWire } from "./WireProjection.ts";
37​
38const isThreadTranscriptTooLargeError = Schema.is(
39 ThreadManagementService.ThreadTranscriptTooLargeError,
40);
41​
42function isThreadNotFound(error: unknown): boolean {
43 return (
44 Predicate.hasProperty(error, "cause") &&
45 Predicate.hasProperty(error.cause, "_tag") &&
46 error.cause._tag === "ProjectionStoreThreadNotFoundError"
47 );
49​
50export const layer = HttpApiBuilder.group(
51 EnvironmentHttpApi,
52 "orchestration",
53 Effect.fnUntraced(function* (handlers) {
54 const sql = yield* SqlClient.SqlClient;
55 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
56 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
57 const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore;
58 const projectStore = yield* ProjectStore.ProjectStoreV2;
59 const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
60​
61 const enrichProjectShells = Effect.fn("http.orchestration.enrichProjectShells")(
62 (projects: ReadonlyArray<OrchestrationProjectShell>) =>
63 Effect.forEach(
64 projects,
65 (project) =>
66 // Use available enrichment only; git probes can take a minute and exceed shell-snapshot budgets.
67 projectEnrichment.getAvailable(project.workspaceRoot).pipe(
68 Effect.map((enrichment) => ({
69 ...project,
70 repositoryIdentity: enrichment.repositoryIdentity,
71 })),
72 ),
73 { concurrency: 16 },
74 ),
75 );
76​
77 const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")(
78 function* (options: {
79 readonly omitIdleSubagents: boolean;
80 readonly omitOlderSettled: boolean;
81 }) {
82 const { snapshot } = yield* loadSubscriberShellSnapshot({
83 sql,
84 listShellIndex: threadManagement.listActiveShellIndex(),
85 readThreads: (threadIds) =>
86 threadManagement.readShellSnapshot({
87 location: "active",
88 ...(threadIds === undefined ? {} : { threadIds }),
89 }),
90 listProjects: projectStore.listShells(),
91 latestSequence: applicationEvents.latestApplicationSequence,
92 options,
93 });
94 const projects = yield* enrichProjectShells(snapshot.projects);
95 return { ...snapshot, projects };
96 },
97 );
98​
99 const loadThreadSnapshot = Effect.fn("http.orchestration.loadThreadSnapshot")(function* (
100 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
101 failureReason:
102 | "orchestration_thread_snapshot_failed"
103 | "orchestration_thread_bounded_snapshot_failed"
104 | "orchestration_thread_history_failed",
105 ) {
106 return yield* threadManagement.getThreadSnapshot(threadId).pipe(
107 Effect.map((snapshot) => ({
108 ...snapshot,
109 projection: projectThreadProjectionForWire(snapshot.projection),
110 })),
111 Effect.catch(
112 Effect.fnUntraced(function* (error) {
113 if (isThreadNotFound(error)) {
114 return yield* failEnvironmentNotFound("thread_not_found");
115 }
116 return yield* failEnvironmentInternal(failureReason, error);
117 }),
118 ),
119 );
120 });
121​
122 const loadThreadSnapshotWindow = Effect.fn("http.orchestration.loadThreadSnapshotWindow")(
123 function* (
124 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
125 anchorItemId?: Parameters<
126 typeof threadManagement.getThreadSnapshotWindow
127 >[1]["anchorItemId"],
128 anchorThreadId?: Parameters<
129 typeof threadManagement.getThreadSnapshotWindow
130 >[1]["anchorThreadId"],
131 deferWork = false,
132 ) {
133 return yield* threadManagement
134 .getThreadSnapshotWindow(threadId, {
135 rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
136 deferWork,
137 userTurnLimit:
138 anchorItemId === undefined
139 ? THREAD_HISTORY_PAGE_POLICY.maxUserTurns
140 : OLDER_THREAD_USER_TURN_LIMIT,
141 ...(anchorItemId === undefined ? {} : { anchorItemId }),
142 ...(anchorThreadId === undefined ? {} : { anchorThreadId }),
143 })
144 .pipe(
145 Effect.map((snapshot) => ({
146 ...snapshot,
147 projection: projectThreadProjectionForWire(snapshot.projection),
148 })),
149 Effect.catch(
150 Effect.fnUntraced(function* (error) {
151 if (isThreadNotFound(error)) {
152 return yield* failEnvironmentNotFound("thread_not_found");
153 }
154 return yield* failEnvironmentInternal("orchestration_thread_history_failed", error);
155 }),
156 ),
157 );
158 },
159 );
160​
161 return handlers
162 .handle(
163 "shellSnapshot",
164 Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
165 yield* annotateEnvironmentRequest(args.endpoint.name);
166 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
167 return yield* loadShellSnapshot({
168 omitIdleSubagents: args.query.omitIdleSubagents === "1",
169 omitOlderSettled: args.query.omitOlderSettled === "1",
170 }).pipe(
171 traceLocalHandlerWork,
172 Effect.catch((cause) =>
173 failEnvironmentInternal("orchestration_snapshot_failed", cause),
174 ),
175 );
176 }),
177 )
178 .handle(
179 "threadSnapshot",
180 Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {
181 yield* annotateEnvironmentRequest(args.endpoint.name);
182 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
183 const snapshot = yield* loadThreadSnapshot(
184 args.params.threadId,
185 "orchestration_thread_snapshot_failed",
186 ).pipe(traceLocalHandlerWork);
187 return {
188 snapshotSequence: snapshot.snapshotSequence,
189 projection: snapshot.projection,
190 };
191 }),
192 )
193 .handle(
194 "threadTranscript",
195 Effect.fn("environment.orchestration.threadTranscript")(function* (args) {
196 yield* annotateEnvironmentRequest(args.endpoint.name);
197 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
198 return yield* threadManagement.getThreadTranscript(args.params.threadId).pipe(
199 Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment),
200 traceLocalHandlerWork,
201 Effect.catch(
202 Effect.fnUntraced(function* (error) {
203 if (isThreadTranscriptTooLargeError(error)) {
204 return yield* failEnvironmentInvalidRequest("thread_transcript_too_large");
205 }
206 if (isThreadNotFound(error)) {
207 return yield* failEnvironmentNotFound("thread_not_found");
208 }
209 return yield* failEnvironmentInternal(
210 "orchestration_thread_snapshot_failed",
211 error,
212 );
213 }),
214 ),
215 );
216 }),
217 )
218 .handle(
219 "threadBoundedSnapshot",
220 Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) {
221 yield* annotateEnvironmentRequest(args.endpoint.name);
222 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
223 const snapshot = yield* loadThreadSnapshotWindow(
224 args.params.threadId,
225 undefined,
226 undefined,
227 args.query.deferWork === "1",
228 ).pipe(traceLocalHandlerWork);
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 args.query.view === "work"
265 ? "work"
266 : args.query.deferWork === "1"
267 ? "deferred"
268 : undefined,
269 )
270 .pipe(
271 Effect.map((page) =>
272 args.query.compactIds === "1" ? { ...page, idTable: true as const } : page,
273 ),
274 traceLocalHandlerWork,
275 Effect.catch(
276 Effect.fnUntraced(function* (cause) {
277 if (isThreadNotFound(cause))
278 return yield* failEnvironmentNotFound("thread_not_found");
279 return yield* failEnvironmentInternal(
280 "orchestration_thread_history_failed",
281 cause,
282 );
283 }),
284 ),
285 );
286 }),
287 );
288 }),
289);