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 compactPullRequests: boolean,
80 ) {
81 const base = buildActiveShellSnapshot(
82 yield* loadShellSnapshotParts({
83 sql,
84 readThreads: threadManagement.readShellSnapshot({
85 location: "active",
86 compactPullRequests,
87 }),
88 listProjects: projectStore.listShells(),
89 latestSequence: applicationEvents.latestApplicationSequence,
90 }),
91 );
92 const projects = yield* enrichProjectShells(base.projects);
93 return { ...base, projects };
94 });
95
96 const loadThreadSnapshot = Effect.fn("http.orchestration.loadThreadSnapshot")(function* (
97 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
98 failureReason:
99 | "orchestration_thread_snapshot_failed"
100 | "orchestration_thread_bounded_snapshot_failed"
101 | "orchestration_thread_history_failed",
102 ) {
103 return yield* threadManagement.getThreadSnapshot(threadId).pipe(
104 Effect.map((snapshot) => ({
105 ...snapshot,
106 projection: projectThreadProjectionForWire(snapshot.projection),
107 })),
108 Effect.catch(
109 Effect.fnUntraced(function* (error) {
110 if (isThreadNotFound(error)) {
111 return yield* failEnvironmentNotFound("thread_not_found");
112 }
113 return yield* failEnvironmentInternal(failureReason, error);
114 }),
115 ),
116 );
117 });
118
119 const loadThreadSnapshotWindow = Effect.fn("http.orchestration.loadThreadSnapshotWindow")(
120 function* (
121 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
122 anchorItemId?: Parameters<
123 typeof threadManagement.getThreadSnapshotWindow
124 >[1]["anchorItemId"],
125 anchorThreadId?: Parameters<
126 typeof threadManagement.getThreadSnapshotWindow
127 >[1]["anchorThreadId"],
128 ) {
129 return yield* threadManagement
130 .getThreadSnapshotWindow(threadId, {
131 rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
132 userTurnLimit:
133 anchorItemId === undefined
134 ? THREAD_HISTORY_PAGE_POLICY.maxUserTurns
135 : OLDER_THREAD_USER_TURN_LIMIT,
136 ...(anchorItemId === undefined ? {} : { anchorItemId }),
137 ...(anchorThreadId === undefined ? {} : { anchorThreadId }),
138 })
139 .pipe(
140 Effect.map((snapshot) => ({
141 ...snapshot,
142 projection: projectThreadProjectionForWire(snapshot.projection),
143 })),
144 Effect.catch(
145 Effect.fnUntraced(function* (error) {
146 if (isThreadNotFound(error)) {
147 return yield* failEnvironmentNotFound("thread_not_found");
148 }
149 return yield* failEnvironmentInternal("orchestration_thread_history_failed", error);
150 }),
151 ),
152 );
153 },
154 );
155
156 return handlers
157 .handle(
158 "shellSnapshot",
159 Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
160 yield* annotateEnvironmentRequest(args.endpoint.name);
161 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
162 return yield* loadShellSnapshot(args.query.compactPullRequests === "true").pipe(
163 traceLocalHandlerWork,
164 Effect.catch((cause) =>
165 failEnvironmentInternal("orchestration_snapshot_failed", cause),
166 ),
167 );
168 }),
169 )
170 .handle(
171 "threadSnapshot",
172 Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {
173 yield* annotateEnvironmentRequest(args.endpoint.name);
174 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
175 const snapshot = yield* loadThreadSnapshot(
176 args.params.threadId,
177 "orchestration_thread_snapshot_failed",
178 ).pipe(traceLocalHandlerWork);
179 return {
180 snapshotSequence: snapshot.snapshotSequence,
181 projection: snapshot.projection,
182 };
183 }),
184 )
185 .handle(
186 "threadTranscript",
187 Effect.fn("environment.orchestration.threadTranscript")(function* (args) {
188 yield* annotateEnvironmentRequest(args.endpoint.name);
189 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
190 return yield* threadManagement.getThreadTranscript(args.params.threadId).pipe(
191 Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment),
192 traceLocalHandlerWork,
193 Effect.catch(
194 Effect.fnUntraced(function* (error) {
195 if (isThreadTranscriptTooLargeError(error)) {
196 return yield* failEnvironmentInvalidRequest("thread_transcript_too_large");
197 }
198 if (isThreadNotFound(error)) {
199 return yield* failEnvironmentNotFound("thread_not_found");
200 }
201 return yield* failEnvironmentInternal(
202 "orchestration_thread_snapshot_failed",
203 error,
204 );
205 }),
206 ),
207 );
208 }),
209 )
210 .handle(
211 "threadBoundedSnapshot",
212 Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) {
213 yield* annotateEnvironmentRequest(args.endpoint.name);
214 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
215 const snapshot = yield* loadThreadSnapshotWindow(args.params.threadId).pipe(
216 traceLocalHandlerWork,
217 );
218 const bounded = buildBoundedThreadProjection({
219 projection: snapshot.projection,
220 snapshotSequence: snapshot.snapshotSequence,
221 });
222 return {
223 snapshotSequence: snapshot.snapshotSequence,
224 ...boundedSnapshotResponseFields({
225 bounded,
226 compactTurnItems: args.query.compactTurnItems === "1",
227 compactCheckpointItems: args.query.compactCheckpointItems === "1",
228 }),
229 };
230 }),
231 )
232 .handle(
233 "threadHistoryPage",
234 Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) {
235 yield* annotateEnvironmentRequest(args.endpoint.name);
236 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
237 try {
238 decodeThreadHistoryCursor(args.query.cursor);
239 } catch (cause) {
240 if (cause instanceof InvalidThreadHistoryCursorError)
241 return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
242 return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);
243 }
244 return yield* threadManagement
245 .getThreadHistoryPage(
246 args.params.threadId,
247 args.query.cursor,
248 args.query.throughEntryId,
249 args.query.view === "conversation",
250 )
251 .pipe(
252 traceLocalHandlerWork,
253 Effect.catch(
254 Effect.fnUntraced(function* (cause) {
255 if (isThreadNotFound(cause))
256 return yield* failEnvironmentNotFound("thread_not_found");
257 return yield* failEnvironmentInternal(
258 "orchestration_thread_history_failed",
259 cause,
260 );
261 }),
262 ),
263 );
264 }),
265 );
266 }),
267);