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

http.ts

289 lines11.3 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 isInvalidThreadHistoryCursorError = Schema.is(InvalidThreadHistoryCursorError);
39​
40const isThreadTranscriptTooLargeError = Schema.is(
41 ThreadManagementService.ThreadTranscriptTooLargeError,
42);
43​
44function isThreadNotFound(error: unknown): boolean {
45 return (
46 Predicate.hasProperty(error, "cause") &&
47 Predicate.hasProperty(error.cause, "_tag") &&
48 error.cause._tag === "ProjectionStoreThreadNotFoundError"
49 );
51​
52export const layer = HttpApiBuilder.group(
53 EnvironmentHttpApi,
54 "orchestration",
55 Effect.fnUntraced(function* (handlers) {
56 const sql = yield* SqlClient.SqlClient;
57 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
58 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
59 const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore;
60 const projectStore = yield* ProjectStore.ProjectStoreV2;
61 const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
62​
63 const enrichProjectShells = Effect.fn("http.orchestration.enrichProjectShells")(
64 (projects: ReadonlyArray<OrchestrationProjectShell>) =>
65 Effect.forEach(
66 projects,
67 (project) =>
68 // Use available enrichment only; git probes can take a minute and exceed shell-snapshot budgets.
69 projectEnrichment.getAvailable(project.workspaceRoot).pipe(
70 Effect.map((enrichment) => ({
71 ...project,
72 repositoryIdentity: enrichment.repositoryIdentity,
73 })),
74 ),
75 { concurrency: 16 },
76 ),
77 );
78​
79 const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")(
80 function* (options: {
81 readonly omitIdleSubagents: boolean;
82 readonly omitOlderSettled: boolean;
83 }) {
84 const { snapshot } = yield* loadSubscriberShellSnapshot({
85 sql,
86 listShellIndex: threadManagement.listActiveShellIndex(),
87 readThreads: (threadIds) =>
88 threadManagement.readShellSnapshot({
89 location: "active",
90 ...(threadIds === undefined ? {} : { threadIds }),
91 }),
92 listProjects: projectStore.listShells(),
93 latestSequence: applicationEvents.latestApplicationSequence,
94 options,
95 });
96 const projects = yield* enrichProjectShells(snapshot.projects);
97 return { ...snapshot, projects };
98 },
99 );
100​
101 const loadThreadSnapshot = Effect.fn("http.orchestration.loadThreadSnapshot")(function* (
102 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
103 failureReason:
104 | "orchestration_thread_snapshot_failed"
105 | "orchestration_thread_bounded_snapshot_failed"
106 | "orchestration_thread_history_failed",
107 ) {
108 return yield* threadManagement.getThreadSnapshot(threadId).pipe(
109 Effect.map((snapshot) => ({
110 ...snapshot,
111 projection: projectThreadProjectionForWire(snapshot.projection),
112 })),
113 Effect.catch(
114 Effect.fnUntraced(function* (error) {
115 if (isThreadNotFound(error)) {
116 return yield* failEnvironmentNotFound("thread_not_found");
117 }
118 return yield* failEnvironmentInternal(failureReason, error);
119 }),
120 ),
121 );
122 });
123​
124 const loadThreadSnapshotWindow = Effect.fn("http.orchestration.loadThreadSnapshotWindow")(
125 function* (
126 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
127 anchorItemId?: Parameters<
128 typeof threadManagement.getThreadSnapshotWindow
129 >[1]["anchorItemId"],
130 anchorThreadId?: Parameters<
131 typeof threadManagement.getThreadSnapshotWindow
132 >[1]["anchorThreadId"],
133 deferWork = false,
134 ) {
135 return yield* threadManagement
136 .getThreadSnapshotWindow(threadId, {
137 rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
138 deferWork,
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(
226 args.params.threadId,
227 undefined,
228 undefined,
229 args.query.deferWork === "1",
230 ).pipe(traceLocalHandlerWork);
231 const bounded = buildBoundedThreadProjection({
232 projection: snapshot.projection,
233 snapshotSequence: snapshot.snapshotSequence,
234 });
235 return {
236 snapshotSequence: snapshot.snapshotSequence,
237 ...boundedSnapshotResponseFields({
238 bounded,
239 compactTurnItems: args.query.compactTurnItems === "1",
240 dedupeBodies: args.query.dedupeBodies === "1",
241 compactIds: args.query.compactIds === "1",
242 }),
243 };
244 }),
245 )
246 .handle(
247 "threadHistoryPage",
248 Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) {
249 yield* annotateEnvironmentRequest(args.endpoint.name);
250 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
251 const decoded = Result.try(() => decodeThreadHistoryCursor(args.query.cursor));
252 if (Result.isFailure(decoded)) {
253 const cause = decoded.failure;
254 if (isInvalidThreadHistoryCursorError(cause))
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);