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

http.ts

294 lines11.3 KB

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 );
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 deferWork = false,
137 ) {
138 return yield* threadManagement
139 .getThreadSnapshotWindow(threadId, {
140 rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
141 deferWork,
142 userTurnLimit:
143 anchorItemId === undefined
144 ? THREAD_HISTORY_PAGE_POLICY.maxUserTurns
145 : OLDER_THREAD_USER_TURN_LIMIT,
146 ...(anchorItemId === undefined ? {} : { anchorItemId }),
147 ...(anchorThreadId === undefined ? {} : { anchorThreadId }),
148 })
149 .pipe(
150 Effect.map((snapshot) => ({
151 ...snapshot,
152 projection: projectThreadProjectionForWire(snapshot.projection),
153 })),
154 Effect.catch(
155 Effect.fnUntraced(function* (error) {
156 if (isThreadNotFound(error)) {
157 return yield* failEnvironmentNotFound("thread_not_found");
158 }
159 return yield* failEnvironmentInternal("orchestration_thread_history_failed", error);
160 }),
161 ),
162 );
163 },
164 );
165​
166 return handlers
167 .handle(
168 "shellSnapshot",
169 Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
170 yield* annotateEnvironmentRequest(args.endpoint.name);
171 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
172 return yield* loadShellSnapshot({
173 omitIdleSubagents: args.query.omitIdleSubagents === "1",
174 omitOlderSettled: args.query.omitOlderSettled === "1",
175 }).pipe(
176 traceLocalHandlerWork,
177 Effect.catch((cause) =>
178 failEnvironmentInternal("orchestration_snapshot_failed", cause),
179 ),
180 );
181 }),
182 )
183 .handle(
184 "threadSnapshot",
185 Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {
186 yield* annotateEnvironmentRequest(args.endpoint.name);
187 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
188 const snapshot = yield* loadThreadSnapshot(
189 args.params.threadId,
190 "orchestration_thread_snapshot_failed",
191 ).pipe(traceLocalHandlerWork);
192 return {
193 snapshotSequence: snapshot.snapshotSequence,
194 projection: snapshot.projection,
195 };
196 }),
197 )
198 .handle(
199 "threadTranscript",
200 Effect.fn("environment.orchestration.threadTranscript")(function* (args) {
201 yield* annotateEnvironmentRequest(args.endpoint.name);
202 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
203 return yield* threadManagement.getThreadTranscript(args.params.threadId).pipe(
204 Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment),
205 traceLocalHandlerWork,
206 Effect.catch(
207 Effect.fnUntraced(function* (error) {
208 if (isThreadTranscriptTooLargeError(error)) {
209 return yield* failEnvironmentInvalidRequest("thread_transcript_too_large");
210 }
211 if (isThreadNotFound(error)) {
212 return yield* failEnvironmentNotFound("thread_not_found");
213 }
214 return yield* failEnvironmentInternal(
215 "orchestration_thread_snapshot_failed",
216 error,
217 );
218 }),
219 ),
220 );
221 }),
222 )
223 .handle(
224 "threadBoundedSnapshot",
225 Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) {
226 yield* annotateEnvironmentRequest(args.endpoint.name);
227 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
228 const snapshot = yield* loadThreadSnapshotWindow(
229 args.params.threadId,
230 undefined,
231 undefined,
232 args.query.deferWork === "1",
233 ).pipe(traceLocalHandlerWork);
234 const bounded = buildBoundedThreadProjection({
235 projection: snapshot.projection,
236 snapshotSequence: snapshot.snapshotSequence,
237 });
238 return {
239 snapshotSequence: snapshot.snapshotSequence,
240 ...boundedSnapshotResponseFields({
241 bounded,
242 compactTurnItems: args.query.compactTurnItems === "1",
243 dedupeBodies: args.query.dedupeBodies === "1",
244 compactIds: args.query.compactIds === "1",
245 }),
246 };
247 }),
248 )
249 .handle(
250 "threadHistoryPage",
251 Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) {
252 yield* annotateEnvironmentRequest(args.endpoint.name);
253 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
254 const decoded = yield* Effect.try(() =>
255 decodeThreadHistoryCursor(args.query.cursor),
256 ).pipe(Effect.result);
257 if (Result.isFailure(decoded)) {
258 const cause = decoded.failure.cause;
259 if (cause instanceof InvalidThreadHistoryCursorError)
260 return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
261 return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);
262 }
263 return yield* threadManagement
264 .getThreadHistoryPage(
265 args.params.threadId,
266 args.query.cursor,
267 args.query.throughEntryId,
268 args.query.view === "conversation",
269 args.query.view === "work"
270 ? "work"
271 : args.query.deferWork === "1"
272 ? "deferred"
273 : undefined,
274 )
275 .pipe(
276 Effect.map((page) =>
277 args.query.compactIds === "1" ? { ...page, idTable: true as const } : page,
278 ),
279 traceLocalHandlerWork,
280 Effect.catch(
281 Effect.fnUntraced(function* (cause) {
282 if (isThreadNotFound(cause))
283 return yield* failEnvironmentNotFound("thread_not_found");
284 return yield* failEnvironmentInternal(
285 "orchestration_thread_history_failed",
286 cause,
287 );
288 }),
289 ),
290 );
291 }),
292 );
293 }),
294);