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

http.ts

274 lines10.5 KB

1import {
2 AuthOrchestrationReadScope,
3 EnvironmentHttpApi,
4 type OrchestrationProjectShell,
5} from "@t3tools/contracts";
6import * as Effect from "effect/Effect";
7import * as Predicate from "effect/Predicate";
8import * as Schema from "effect/Schema";
9import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
10import * as SqlClient from "effect/sql/SqlClient";
11​
12import {
13 annotateEnvironmentRequest,
14 failEnvironmentInternal,
15 failEnvironmentInvalidRequest,
16 failEnvironmentNotFound,
17 requireEnvironmentScope,
18} from "../auth/http.ts";
19import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
20import { traceLocalHandlerWork } from "../cloud/traceRelayRequest.ts";
21import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
22import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
23import {
24 buildBoundedThreadProjection,
25 decodeThreadHistoryCursor,
26 InvalidThreadHistoryCursorError,
27 THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
28 THREAD_HISTORY_PAGE_POLICY,
29 OLDER_THREAD_USER_TURN_LIMIT,
30} from "./threadHistoryPaging.ts";
31import * as ThreadManagementService from "./ThreadManagementService.ts";
32import * as ProjectStore from "./ProjectStore.ts";
33import {
34 buildActiveShellSnapshot,
35 loadShellSnapshotParts,
36 omitIdleSubagentShells,
37} from "./ShellStream.ts";
38import { boundedSnapshotResponseFields } from "./ThreadStream.ts";
39import { projectThreadProjectionForWire } from "./WireProjection.ts";
40​
41const isThreadTranscriptTooLargeError = Schema.is(
42 ThreadManagementService.ThreadTranscriptTooLargeError,
43);
44​
45function isThreadNotFound(error: unknown): boolean {
46 return (
47 Predicate.hasProperty(error, "cause") &&
48 Predicate.hasProperty(error.cause, "_tag") &&
49 error.cause._tag === "ProjectionStoreThreadNotFoundError"
50 );
52​
53export const layer = HttpApiBuilder.group(
54 EnvironmentHttpApi,
55 "orchestration",
56 Effect.fnUntraced(function* (handlers) {
57 const sql = yield* SqlClient.SqlClient;
58 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
59 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
60 const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore;
61 const projectStore = yield* ProjectStore.ProjectStoreV2;
62 const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
63​
64 const enrichProjectShells = Effect.fn("http.orchestration.enrichProjectShells")(
65 (projects: ReadonlyArray<OrchestrationProjectShell>) =>
66 Effect.forEach(
67 projects,
68 (project) =>
69 // Use available enrichment only; git probes can take a minute and exceed shell-snapshot budgets.
70 projectEnrichment.getAvailable(project.workspaceRoot).pipe(
71 Effect.map((enrichment) => ({
72 ...project,
73 repositoryIdentity: enrichment.repositoryIdentity,
74 })),
75 ),
76 { concurrency: 16 },
77 ),
78 );
79​
80 const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")(function* (
81 omitIdleSubagents: boolean,
82 ) {
83 const base = buildActiveShellSnapshot(
84 yield* loadShellSnapshotParts({
85 sql,
86 readThreads: threadManagement.readShellSnapshot({ location: "active" }),
87 listProjects: projectStore.listShells(),
88 latestSequence: applicationEvents.latestApplicationSequence,
89 }),
90 );
91 const projects = yield* enrichProjectShells(base.projects);
92 return {
93 ...base,
94 threads: omitIdleSubagents ? omitIdleSubagentShells(base.threads) : base.threads,
95 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 ) {
132 return yield* threadManagement
133 .getThreadSnapshotWindow(threadId, {
134 rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
135 userTurnLimit:
136 anchorItemId === undefined
137 ? THREAD_HISTORY_PAGE_POLICY.maxUserTurns
138 : OLDER_THREAD_USER_TURN_LIMIT,
139 ...(anchorItemId === undefined ? {} : { anchorItemId }),
140 ...(anchorThreadId === undefined ? {} : { anchorThreadId }),
141 })
142 .pipe(
143 Effect.map((snapshot) => ({
144 ...snapshot,
145 projection: projectThreadProjectionForWire(snapshot.projection),
146 })),
147 Effect.catch(
148 Effect.fnUntraced(function* (error) {
149 if (isThreadNotFound(error)) {
150 return yield* failEnvironmentNotFound("thread_not_found");
151 }
152 return yield* failEnvironmentInternal("orchestration_thread_history_failed", error);
153 }),
154 ),
155 );
156 },
157 );
158​
159 return handlers
160 .handle(
161 "shellSnapshot",
162 Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
163 yield* annotateEnvironmentRequest(args.endpoint.name);
164 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
165 return yield* loadShellSnapshot(args.query.omitIdleSubagents === "1").pipe(
166 traceLocalHandlerWork,
167 Effect.catch((cause) =>
168 failEnvironmentInternal("orchestration_snapshot_failed", cause),
169 ),
170 );
171 }),
172 )
173 .handle(
174 "threadSnapshot",
175 Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {
176 yield* annotateEnvironmentRequest(args.endpoint.name);
177 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
178 const snapshot = yield* loadThreadSnapshot(
179 args.params.threadId,
180 "orchestration_thread_snapshot_failed",
181 ).pipe(traceLocalHandlerWork);
182 return {
183 snapshotSequence: snapshot.snapshotSequence,
184 projection: snapshot.projection,
185 };
186 }),
187 )
188 .handle(
189 "threadTranscript",
190 Effect.fn("environment.orchestration.threadTranscript")(function* (args) {
191 yield* annotateEnvironmentRequest(args.endpoint.name);
192 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
193 return yield* threadManagement.getThreadTranscript(args.params.threadId).pipe(
194 Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment),
195 traceLocalHandlerWork,
196 Effect.catch(
197 Effect.fnUntraced(function* (error) {
198 if (isThreadTranscriptTooLargeError(error)) {
199 return yield* failEnvironmentInvalidRequest("thread_transcript_too_large");
200 }
201 if (isThreadNotFound(error)) {
202 return yield* failEnvironmentNotFound("thread_not_found");
203 }
204 return yield* failEnvironmentInternal(
205 "orchestration_thread_snapshot_failed",
206 error,
207 );
208 }),
209 ),
210 );
211 }),
212 )
213 .handle(
214 "threadBoundedSnapshot",
215 Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) {
216 yield* annotateEnvironmentRequest(args.endpoint.name);
217 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
218 const snapshot = yield* loadThreadSnapshotWindow(args.params.threadId).pipe(
219 traceLocalHandlerWork,
220 );
221 const bounded = buildBoundedThreadProjection({
222 projection: snapshot.projection,
223 snapshotSequence: snapshot.snapshotSequence,
224 });
225 return {
226 snapshotSequence: snapshot.snapshotSequence,
227 ...boundedSnapshotResponseFields({
228 bounded,
229 compactTurnItems: args.query.compactTurnItems === "1",
230 dedupeBodies: args.query.dedupeBodies === "1",
231 compactIds: args.query.compactIds === "1",
232 }),
233 };
234 }),
235 )
236 .handle(
237 "threadHistoryPage",
238 Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) {
239 yield* annotateEnvironmentRequest(args.endpoint.name);
240 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
241 try {
242 decodeThreadHistoryCursor(args.query.cursor);
243 } catch (cause) {
244 if (cause instanceof InvalidThreadHistoryCursorError)
245 return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
246 return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);
247 }
248 return yield* threadManagement
249 .getThreadHistoryPage(
250 args.params.threadId,
251 args.query.cursor,
252 args.query.throughEntryId,
253 args.query.view === "conversation",
254 )
255 .pipe(
256 Effect.map((page) =>
257 args.query.compactIds === "1" ? { ...page, idTable: true as const } : page,
258 ),
259 traceLocalHandlerWork,
260 Effect.catch(
261 Effect.fnUntraced(function* (cause) {
262 if (isThreadNotFound(cause))
263 return yield* failEnvironmentNotFound("thread_not_found");
264 return yield* failEnvironmentInternal(
265 "orchestration_thread_history_failed",
266 cause,
267 );
268 }),
269 ),
270 );
271 }),
272 );
273 }),
274);