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