Open History to see the last commit
1import {
2 ChatAttachment,
3 IsoDateTime,
4 MessageId,
5 OrchestrationCheckpointFile,
6 OrchestrationReadModel,
7 ProjectScript,
8 TurnId,
9 type OrchestrationCheckpointSummary,
10 type OrchestrationLatestTurn,
11 type OrchestrationMessage,
12 type OrchestrationProject,
13 type OrchestrationSession,
14 type OrchestrationThread,
15 type OrchestrationThreadActivity,
16} from "@t3tools/contracts";
17import { Effect, Layer, Schema, Struct } from "effect";
18import * as SqlClient from "effect/unstable/sql/SqlClient";
19import * as SqlSchema from "effect/unstable/sql/SqlSchema";
20
21import {
22 isPersistenceError,
23 toPersistenceDecodeError,
24 toPersistenceSqlError,
25 type ProjectionRepositoryError,
26} from "../../persistence/Errors.ts";
27import { ProjectionCheckpoint } from "../../persistence/Services/ProjectionCheckpoints.ts";
28import { ProjectionProject } from "../../persistence/Services/ProjectionProjects.ts";
29import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
30import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
31import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts";
32import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
33import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
34import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
35import {
36 ProjectionSnapshotQuery,
37 type ProjectionSnapshotQueryShape,
38} from "../Services/ProjectionSnapshotQuery.ts";
39
40const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
41const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
42 Struct.assign({
43 scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
44 }),
45);
46const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
47 Struct.assign({
48 isStreaming: Schema.Number,
49 attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
50 }),
51);
52const ProjectionThreadDbRowSchema = ProjectionThread;
53const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
54 Struct.assign({
55 payload: Schema.fromJsonString(Schema.Unknown),
56 }),
57);
58const ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;
59const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
60 Struct.assign({
61 files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
62 }),
63);
64const ProjectionLatestTurnDbRowSchema = Schema.Struct({
65 threadId: ProjectionThread.fields.threadId,
66 turnId: TurnId,
67 state: Schema.String,
68 requestedAt: IsoDateTime,
69 startedAt: Schema.NullOr(IsoDateTime),
70 completedAt: Schema.NullOr(IsoDateTime),
71 assistantMessageId: Schema.NullOr(MessageId),
72});
73const ProjectionStateDbRowSchema = ProjectionState;
74
75const REQUIRED_SNAPSHOT_PROJECTORS = [
76 ORCHESTRATION_PROJECTOR_NAMES.projects,
77 ORCHESTRATION_PROJECTOR_NAMES.threads,
78 ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
79 ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
80 ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
81 ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
82] as const;
83
84function maxIso(left: string | null, right: string): string {
85 if (left === null) {
86 return right;
87 }
88 return left > right ? left : right;
89}
90
91function computeSnapshotSequence(
92 stateRows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionStateDbRowSchema>>,
93): number {
94 if (stateRows.length === 0) {
95 return 0;
96 }
97 const sequenceByProjector = new Map(
98 stateRows.map((row) => [row.projector, row.lastAppliedSequence] as const),
99 );
100
101 let minSequence = Number.POSITIVE_INFINITY;
102 for (const projector of REQUIRED_SNAPSHOT_PROJECTORS) {
103 const sequence = sequenceByProjector.get(projector);
104 if (sequence === undefined) {
105 return 0;
106 }
107 if (sequence < minSequence) {
108 minSequence = sequence;
109 }
110 }
111
112 return Number.isFinite(minSequence) ? minSequence : 0;
113}
114
115function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
116 return (cause: unknown): ProjectionRepositoryError =>
117 Schema.isSchemaError(cause)
118 ? toPersistenceDecodeError(decodeOperation)(cause)
119 : toPersistenceSqlError(sqlOperation)(cause);
120}
121
122const makeProjectionSnapshotQuery = Effect.gen(function* () {
123 const sql = yield* SqlClient.SqlClient;
124
125 const listProjectRows = SqlSchema.findAll({
126 Request: Schema.Void,
127 Result: ProjectionProjectDbRowSchema,
128 execute: () =>
129 sql`
130 SELECT
131 project_id AS "projectId",
132 title,
133 workspace_root AS "workspaceRoot",
134 default_model AS "defaultModel",
135 scripts_json AS "scripts",
136 created_at AS "createdAt",
137 updated_at AS "updatedAt",
138 deleted_at AS "deletedAt"
139 FROM projection_projects
140 ORDER BY created_at ASC, project_id ASC
141 `,
142 });
143
144 const listThreadRows = SqlSchema.findAll({
145 Request: Schema.Void,
146 Result: ProjectionThreadDbRowSchema,
147 execute: () =>
148 sql`
149 SELECT
150 thread_id AS "threadId",
151 project_id AS "projectId",
152 title,
153 model,
154 branch,
155 worktree_path AS "worktreePath",
156 latest_turn_id AS "latestTurnId",
157 created_at AS "createdAt",
158 updated_at AS "updatedAt",
159 deleted_at AS "deletedAt"
160 FROM projection_threads
161 ORDER BY created_at ASC, thread_id ASC
162 `,
163 });
164
165 const listThreadMessageRows = SqlSchema.findAll({
166 Request: Schema.Void,
167 Result: ProjectionThreadMessageDbRowSchema,
168 execute: () =>
169 sql`
170 SELECT
171 message_id AS "messageId",
172 thread_id AS "threadId",
173 turn_id AS "turnId",
174 role,
175 text,
176 attachments_json AS "attachments",
177 is_streaming AS "isStreaming",
178 created_at AS "createdAt",
179 updated_at AS "updatedAt"
180 FROM projection_thread_messages
181 ORDER BY thread_id ASC, created_at ASC, message_id ASC
182 `,
183 });
184
185 const listThreadActivityRows = SqlSchema.findAll({
186 Request: Schema.Void,
187 Result: ProjectionThreadActivityDbRowSchema,
188 execute: () =>
189 sql`
190 SELECT
191 activity_id AS "activityId",
192 thread_id AS "threadId",
193 turn_id AS "turnId",
194 tone,
195 kind,
196 summary,
197 payload_json AS "payload",
198 created_at AS "createdAt"
199 FROM projection_thread_activities
200 ORDER BY thread_id ASC, created_at ASC, activity_id ASC
201 `,
202 });
203
204 const listThreadSessionRows = SqlSchema.findAll({
205 Request: Schema.Void,
206 Result: ProjectionThreadSessionDbRowSchema,
207 execute: () =>
208 sql`
209 SELECT
210 thread_id AS "threadId",
211 status,
212 provider_name AS "providerName",
213 provider_session_id AS "providerSessionId",
214 provider_thread_id AS "providerThreadId",
215 approval_policy AS "approvalPolicy",
216 sandbox_mode AS "sandboxMode",
217 active_turn_id AS "activeTurnId",
218 last_error AS "lastError",
219 updated_at AS "updatedAt"
220 FROM projection_thread_sessions
221 ORDER BY thread_id ASC
222 `,
223 });
224
225 const listCheckpointRows = SqlSchema.findAll({
226 Request: Schema.Void,
227 Result: ProjectionCheckpointDbRowSchema,
228 execute: () =>
229 sql`
230 SELECT
231 thread_id AS "threadId",
232 turn_id AS "turnId",
233 checkpoint_turn_count AS "checkpointTurnCount",
234 checkpoint_ref AS "checkpointRef",
235 checkpoint_status AS "status",
236 checkpoint_files_json AS "files",
237 assistant_message_id AS "assistantMessageId",
238 completed_at AS "completedAt"
239 FROM projection_turns
240 WHERE checkpoint_turn_count IS NOT NULL
241 ORDER BY thread_id ASC, checkpoint_turn_count ASC
242 `,
243 });
244
245 const listLatestTurnRows = SqlSchema.findAll({
246 Request: Schema.Void,
247 Result: ProjectionLatestTurnDbRowSchema,
248 execute: () =>
249 sql`
250 SELECT
251 thread_id AS "threadId",
252 turn_id AS "turnId",
253 state,
254 requested_at AS "requestedAt",
255 started_at AS "startedAt",
256 completed_at AS "completedAt",
257 assistant_message_id AS "assistantMessageId"
258 FROM projection_turns
259 WHERE turn_id IS NOT NULL
260 ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
261 `,
262 });
263
264 const listProjectionStateRows = SqlSchema.findAll({
265 Request: Schema.Void,
266 Result: ProjectionStateDbRowSchema,
267 execute: () =>
268 sql`
269 SELECT
270 projector,
271 last_applied_sequence AS "lastAppliedSequence",
272 updated_at AS "updatedAt"
273 FROM projection_state
274 `,
275 });
276
277 const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>
278 sql
279 .withTransaction(
280 Effect.gen(function* () {
281 const [
282 projectRows,
283 threadRows,
284 messageRows,
285 activityRows,
286 sessionRows,
287 checkpointRows,
288 latestTurnRows,
289 stateRows,
290 ] = yield* Effect.all([
291 listProjectRows(undefined).pipe(
292 Effect.mapError(
293 toPersistenceSqlOrDecodeError(
294 "ProjectionSnapshotQuery.getSnapshot:listProjects:query",
295 "ProjectionSnapshotQuery.getSnapshot:listProjects:decodeRows",
296 ),
297 ),
298 ),
299 listThreadRows(undefined).pipe(
300 Effect.mapError(
301 toPersistenceSqlOrDecodeError(
302 "ProjectionSnapshotQuery.getSnapshot:listThreads:query",
303 "ProjectionSnapshotQuery.getSnapshot:listThreads:decodeRows",
304 ),
305 ),
306 ),
307 listThreadMessageRows(undefined).pipe(
308 Effect.mapError(
309 toPersistenceSqlOrDecodeError(
310 "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:query",
311 "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:decodeRows",
312 ),
313 ),
314 ),
315 listThreadActivityRows(undefined).pipe(
316 Effect.mapError(
317 toPersistenceSqlOrDecodeError(
318 "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:query",
319 "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:decodeRows",
320 ),
321 ),
322 ),
323 listThreadSessionRows(undefined).pipe(
324 Effect.mapError(
325 toPersistenceSqlOrDecodeError(
326 "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:query",
327 "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:decodeRows",
328 ),
329 ),
330 ),
331 listCheckpointRows(undefined).pipe(
332 Effect.mapError(
333 toPersistenceSqlOrDecodeError(
334 "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:query",
335 "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:decodeRows",
336 ),
337 ),
338 ),
339 listLatestTurnRows(undefined).pipe(
340 Effect.mapError(
341 toPersistenceSqlOrDecodeError(
342 "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query",
343 "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows",
344 ),
345 ),
346 ),
347 listProjectionStateRows(undefined).pipe(
348 Effect.mapError(
349 toPersistenceSqlOrDecodeError(
350 "ProjectionSnapshotQuery.getSnapshot:listProjectionState:query",
351 "ProjectionSnapshotQuery.getSnapshot:listProjectionState:decodeRows",
352 ),
353 ),
354 ),
355 ]);
356
357 const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
358 const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
359 const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
360 const sessionsByThread = new Map<string, OrchestrationSession>();
361 const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
362
363 let updatedAt: string | null = null;
364
365 for (const row of projectRows) {
366 updatedAt = maxIso(updatedAt, row.updatedAt);
367 }
368 for (const row of threadRows) {
369 updatedAt = maxIso(updatedAt, row.updatedAt);
370 }
371 for (const row of stateRows) {
372 updatedAt = maxIso(updatedAt, row.updatedAt);
373 }
374
375 for (const row of messageRows) {
376 updatedAt = maxIso(updatedAt, row.updatedAt);
377 const threadMessages = messagesByThread.get(row.threadId) ?? [];
378 threadMessages.push({
379 id: row.messageId,
380 role: row.role,
381 text: row.text,
382 ...(row.attachments !== null ? { attachments: row.attachments } : {}),
383 turnId: row.turnId,
384 streaming: row.isStreaming === 1,
385 createdAt: row.createdAt,
386 updatedAt: row.updatedAt,
387 });
388 messagesByThread.set(row.threadId, threadMessages);
389 }
390
391 for (const row of activityRows) {
392 updatedAt = maxIso(updatedAt, row.createdAt);
393 const threadActivities = activitiesByThread.get(row.threadId) ?? [];
394 threadActivities.push({
395 id: row.activityId,
396 tone: row.tone,
397 kind: row.kind,
398 summary: row.summary,
399 payload: row.payload,
400 turnId: row.turnId,
401 createdAt: row.createdAt,
402 });
403 activitiesByThread.set(row.threadId, threadActivities);
404 }
405
406 for (const row of checkpointRows) {
407 updatedAt = maxIso(updatedAt, row.completedAt);
408 const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];
409 threadCheckpoints.push({
410 turnId: row.turnId,
411 checkpointTurnCount: row.checkpointTurnCount,
412 checkpointRef: row.checkpointRef,
413 status: row.status,
414 files: row.files,
415 assistantMessageId: row.assistantMessageId,
416 completedAt: row.completedAt,
417 });
418 checkpointsByThread.set(row.threadId, threadCheckpoints);
419 }
420
421 for (const row of latestTurnRows) {
422 updatedAt = maxIso(updatedAt, row.requestedAt);
423 if (row.startedAt !== null) {
424 updatedAt = maxIso(updatedAt, row.startedAt);
425 }
426 if (row.completedAt !== null) {
427 updatedAt = maxIso(updatedAt, row.completedAt);
428 }
429 if (latestTurnByThread.has(row.threadId)) {
430 continue;
431 }
432 latestTurnByThread.set(row.threadId, {
433 turnId: row.turnId,
434 state:
435 row.state === "error"
436 ? "error"
437 : row.state === "interrupted"
438 ? "interrupted"
439 : row.state === "completed"
440 ? "completed"
441 : "running",
442 requestedAt: row.requestedAt,
443 startedAt: row.startedAt,
444 completedAt: row.completedAt,
445 assistantMessageId: row.assistantMessageId,
446 });
447 }
448
449 for (const row of sessionRows) {
450 updatedAt = maxIso(updatedAt, row.updatedAt);
451 sessionsByThread.set(row.threadId, {
452 threadId: row.threadId,
453 status: row.status,
454 providerName: row.providerName,
455 providerSessionId: row.providerSessionId,
456 providerThreadId: row.providerThreadId,
457 approvalPolicy: row.approvalPolicy,
458 sandboxMode: row.sandboxMode,
459 activeTurnId: row.activeTurnId,
460 lastError: row.lastError,
461 updatedAt: row.updatedAt,
462 });
463 }
464
465 const projects: Array<OrchestrationProject> = projectRows.map((row) => ({
466 id: row.projectId,
467 title: row.title,
468 workspaceRoot: row.workspaceRoot,
469 defaultModel: row.defaultModel,
470 scripts: row.scripts,
471 createdAt: row.createdAt,
472 updatedAt: row.updatedAt,
473 deletedAt: row.deletedAt,
474 }));
475
476 const threads: Array<OrchestrationThread> = threadRows.map((row) => ({
477 id: row.threadId,
478 projectId: row.projectId,
479 title: row.title,
480 model: row.model,
481 branch: row.branch,
482 worktreePath: row.worktreePath,
483 latestTurn: latestTurnByThread.get(row.threadId) ?? null,
484 createdAt: row.createdAt,
485 updatedAt: row.updatedAt,
486 deletedAt: row.deletedAt,
487 messages: messagesByThread.get(row.threadId) ?? [],
488 activities: activitiesByThread.get(row.threadId) ?? [],
489 checkpoints: checkpointsByThread.get(row.threadId) ?? [],
490 session: sessionsByThread.get(row.threadId) ?? null,
491 }));
492
493 const snapshot = {
494 snapshotSequence: computeSnapshotSequence(stateRows),
495 projects,
496 threads,
497 updatedAt: updatedAt ?? new Date(0).toISOString(),
498 };
499
500 return yield* decodeReadModel(snapshot).pipe(
501 Effect.mapError(
502 toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel"),
503 ),
504 );
505 }),
506 )
507 .pipe(
508 Effect.mapError((error) => {
509 if (isPersistenceError(error)) {
510 return error;
511 }
512 return toPersistenceSqlError("ProjectionSnapshotQuery.getSnapshot:query")(error);
513 }),
514 );
515
516 return {
517 getSnapshot,
518 } satisfies ProjectionSnapshotQueryShape;
519});
520
521export const OrchestrationProjectionSnapshotQueryLive = Layer.effect(
522 ProjectionSnapshotQuery,
523 makeProjectionSnapshotQuery,
524);