Open History to see the last commit
1import * as Arr from "effect/Array";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Result from "effect/Result";
7import * as Schema from "effect/Schema";
8import * as Struct from "effect/Struct";
9import * as SqlClient from "effect/unstable/sql/SqlClient";
10import * as SqlSchema from "effect/unstable/sql/SqlSchema";
11
12import {
13 AgentSessionImportSource,
14 IsoDateTime,
15 ProviderInstanceId,
16 RuntimeMode,
17 ThreadId,
18} from "@t3tools/contracts";
19import { ProviderSessionRuntimeStatus } from "@t3tools/contracts/legacy-orchestration";
20
21import {
22 PersistenceDecodeError,
23 type PersistenceErrorCorrelation,
24 PersistenceSqlError,
25 type ProviderSessionRuntimeRepositoryError,
26} from "./Errors.ts";
27
28/**
29 * ProviderSessionRuntimeRepository - Repository interface for provider runtime sessions.
30 *
31 * Owns persistence operations for provider runtime metadata and resume cursors.
32 *
33 * @module ProviderSessionRuntimeRepository
34 */
35
36export const ProviderSessionRuntime = Schema.Struct({
37 threadId: ThreadId,
38 providerName: Schema.String,
39 /**
40 * User-defined routing key for the configured provider instance that
41 * owns this session. Nullable only at the storage/migration boundary:
42 * rows persisted before the driver/instance split carry only
43 * `providerName`. Repository consumers must materialize a concrete
44 * instance id before routing.
45 */
46 providerInstanceId: Schema.NullOr(ProviderInstanceId),
47 adapterKey: Schema.String,
48 runtimeMode: RuntimeMode,
49 status: ProviderSessionRuntimeStatus,
50 lastSeenAt: IsoDateTime,
51 resumeCursor: Schema.NullOr(Schema.Unknown),
52 runtimePayload: Schema.NullOr(Schema.Unknown),
53});
54export type ProviderSessionRuntime = typeof ProviderSessionRuntime.Type;
55
56export const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
57export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type;
58
59export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
60export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;
61
62export const RecordImportedTranscriptInput = Schema.Struct({
63 threadId: ThreadId,
64 source: AgentSessionImportSource,
65});
66export type RecordImportedTranscriptInput = typeof RecordImportedTranscriptInput.Type;
67
68export interface ProviderSessionRuntimeUpsertOptions {
69 readonly onConflict?: "update" | "ignore";
70}
71
72/**
73 * ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.
74 */
75export class ProviderSessionRuntimeRepository extends Context.Service<
76 ProviderSessionRuntimeRepository,
77 {
78 /**
79 * Insert or replace a provider runtime row.
80 *
81 * Upserts by canonical `threadId`, retaining imported transcript records
82 * from the current database row.
83 */
84 readonly upsert: (
85 runtime: ProviderSessionRuntime,
86 options?: ProviderSessionRuntimeUpsertOptions,
87 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
88
89 /** Record one source file without replacing the current session state. */
90 readonly recordImportedTranscript: (
91 input: RecordImportedTranscriptInput,
92 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
93
94 /**
95 * Read provider runtime state by canonical thread id.
96 */
97 readonly getByThreadId: (
98 input: GetProviderSessionRuntimeInput,
99 ) => Effect.Effect<
100 Option.Option<ProviderSessionRuntime>,
101 ProviderSessionRuntimeRepositoryError
102 >;
103
104 /**
105 * List all provider runtime rows.
106 *
107 * Returned in ascending last-seen order.
108 */
109 readonly list: () => Effect.Effect<
110 ReadonlyArray<ProviderSessionRuntime>,
111 ProviderSessionRuntimeRepositoryError
112 >;
113
114 /**
115 * Delete provider runtime state by canonical thread id.
116 */
117 readonly deleteByThreadId: (
118 input: DeleteProviderSessionRuntimeInput,
119 ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
120 }
121>()("t3/persistence/ProviderSessionRuntime/ProviderSessionRuntimeRepository") {}
122
123const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
124 Struct.assign({
125 resumeCursor: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
126 runtimePayload: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
127 }),
128);
129
130const ProviderSessionRuntimeRawDbRowSchema = Schema.Struct({
131 threadId: Schema.String,
132 providerName: Schema.Unknown,
133 providerInstanceId: Schema.Unknown,
134 adapterKey: Schema.Unknown,
135 runtimeMode: Schema.Unknown,
136 status: Schema.Unknown,
137 lastSeenAt: Schema.Unknown,
138 resumeCursor: Schema.Unknown,
139 runtimePayload: Schema.Unknown,
140});
141
142const decodeRuntimeRow = Schema.decodeUnknownEffect(ProviderSessionRuntimeDbRowSchema);
143
144const GetRuntimeRequestSchema = Schema.Struct({
145 threadId: ThreadId,
146});
147
148const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
149
150const RecordImportedTranscriptRequestSchema = RecordImportedTranscriptInput.mapFields(
151 Struct.assign({ source: Schema.fromJsonString(AgentSessionImportSource) }),
152);
153
154function toPersistenceSqlOrDecodeError(
155 sqlOperation: string,
156 decodeOperation: string,
157 correlation?: PersistenceErrorCorrelation,
158) {
159 return (cause: unknown): ProviderSessionRuntimeRepositoryError =>
160 Schema.isSchemaError(cause)
161 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
162 : new PersistenceSqlError({
163 operation: sqlOperation,
164 ...(correlation === undefined ? {} : { correlation }),
165 cause,
166 });
167}
168
169/** @public Service construction is part of the canonical Effect module API. */
170export const make = Effect.gen(function* () {
171 const sql = yield* SqlClient.SqlClient;
172
173 // Runtime writes can carry stale payloads. Only recordImportedTranscript may
174 // change source records, so restore that field from the row being updated.
175 const upsertRuntimeRow = SqlSchema.void({
176 Request: ProviderSessionRuntimeDbRowSchema,
177 execute: (runtime) =>
178 sql`
179 INSERT INTO provider_session_runtime (
180 thread_id,
181 provider_name,
182 provider_instance_id,
183 adapter_key,
184 runtime_mode,
185 status,
186 last_seen_at,
187 resume_cursor_json,
188 runtime_payload_json
189 )
190 VALUES (
191 ${runtime.threadId},
192 ${runtime.providerName},
193 ${runtime.providerInstanceId},
194 ${runtime.adapterKey},
195 ${runtime.runtimeMode},
196 ${runtime.status},
197 ${runtime.lastSeenAt},
198 ${runtime.resumeCursor},
199 CASE
200 WHEN json_type(${runtime.runtimePayload}) = 'object'
201 THEN json_remove(${runtime.runtimePayload}, '$.importedTranscripts')
202 ELSE ${runtime.runtimePayload}
203 END
204 )
205 ON CONFLICT (thread_id)
206 DO UPDATE SET
207 provider_name = excluded.provider_name,
208 provider_instance_id = excluded.provider_instance_id,
209 adapter_key = excluded.adapter_key,
210 runtime_mode = excluded.runtime_mode,
211 status = excluded.status,
212 last_seen_at = excluded.last_seen_at,
213 resume_cursor_json = excluded.resume_cursor_json,
214 runtime_payload_json = CASE
215 WHEN json_type(
216 CASE
217 WHEN json_valid(provider_session_runtime.runtime_payload_json)
218 THEN provider_session_runtime.runtime_payload_json
219 ELSE '{}'
220 END,
221 '$.importedTranscripts'
222 ) IS NOT NULL
223 THEN json_set(
224 CASE
225 WHEN json_type(excluded.runtime_payload_json) = 'object'
226 THEN excluded.runtime_payload_json
227 ELSE '{}'
228 END,
229 '$.importedTranscripts',
230 json_extract(provider_session_runtime.runtime_payload_json, '$.importedTranscripts')
231 )
232 ELSE excluded.runtime_payload_json
233 END
234 `,
235 });
236
237 const insertRuntimeRow = SqlSchema.void({
238 Request: ProviderSessionRuntimeDbRowSchema,
239 execute: (runtime) =>
240 sql`
241 INSERT INTO provider_session_runtime (
242 thread_id,
243 provider_name,
244 provider_instance_id,
245 adapter_key,
246 runtime_mode,
247 status,
248 last_seen_at,
249 resume_cursor_json,
250 runtime_payload_json
251 )
252 VALUES (
253 ${runtime.threadId},
254 ${runtime.providerName},
255 ${runtime.providerInstanceId},
256 ${runtime.adapterKey},
257 ${runtime.runtimeMode},
258 ${runtime.status},
259 ${runtime.lastSeenAt},
260 ${runtime.resumeCursor},
261 CASE
262 WHEN json_type(${runtime.runtimePayload}) = 'object'
263 THEN json_remove(${runtime.runtimePayload}, '$.importedTranscripts')
264 ELSE ${runtime.runtimePayload}
265 END
266 )
267 ON CONFLICT (thread_id) DO NOTHING
268 `,
269 });
270
271 const recordImportedTranscriptRow = SqlSchema.void({
272 Request: RecordImportedTranscriptRequestSchema,
273 execute: ({ threadId, source }) =>
274 sql`
275 WITH current_runtime AS (
276 SELECT CASE
277 WHEN json_valid(runtime_payload_json) THEN CASE
278 WHEN json_type(runtime_payload_json) = 'object' THEN runtime_payload_json
279 ELSE '{}'
280 END
281 ELSE '{}'
282 END AS payload
283 FROM provider_session_runtime
284 WHERE thread_id = ${threadId}
285 )
286 UPDATE provider_session_runtime
287 SET runtime_payload_json = (
288 SELECT json_set(
289 payload,
290 '$.importedTranscripts',
291 json((
292 SELECT json_group_array(json(value))
293 FROM (
294 SELECT value
295 FROM json_each(CASE
296 WHEN json_type(payload, '$.importedTranscripts') = 'array'
297 THEN json_extract(payload, '$.importedTranscripts')
298 ELSE '[]'
299 END)
300 WHERE CASE
301 WHEN type = 'object' THEN
302 json_extract(value, '$.providerInstanceId')
303 IS NOT json_extract(${source}, '$.providerInstanceId')
304 OR json_extract(value, '$.filePath') IS NOT json_extract(${source}, '$.filePath')
305 ELSE 0
306 END
307 UNION ALL
308 SELECT ${source} AS value
309 )
310 ))
311 )
312 FROM current_runtime
313 )
314 WHERE thread_id = ${threadId}
315 `,
316 });
317
318 const getRuntimeRowByThreadId = SqlSchema.findOneOption({
319 Request: GetRuntimeRequestSchema,
320 Result: ProviderSessionRuntimeRawDbRowSchema,
321 execute: ({ threadId }) =>
322 sql`
323 SELECT
324 thread_id AS "threadId",
325 provider_name AS "providerName",
326 provider_instance_id AS "providerInstanceId",
327 adapter_key AS "adapterKey",
328 runtime_mode AS "runtimeMode",
329 status,
330 last_seen_at AS "lastSeenAt",
331 resume_cursor_json AS "resumeCursor",
332 runtime_payload_json AS "runtimePayload"
333 FROM provider_session_runtime
334 WHERE thread_id = ${threadId}
335 `,
336 });
337
338 const listRuntimeRows = SqlSchema.findAll({
339 Request: Schema.Void,
340 Result: ProviderSessionRuntimeRawDbRowSchema,
341 execute: () =>
342 sql`
343 SELECT
344 thread_id AS "threadId",
345 provider_name AS "providerName",
346 provider_instance_id AS "providerInstanceId",
347 adapter_key AS "adapterKey",
348 runtime_mode AS "runtimeMode",
349 status,
350 last_seen_at AS "lastSeenAt",
351 resume_cursor_json AS "resumeCursor",
352 runtime_payload_json AS "runtimePayload"
353 FROM provider_session_runtime
354 ORDER BY last_seen_at ASC, thread_id ASC
355 `,
356 });
357
358 const deleteRuntimeByThreadId = SqlSchema.void({
359 Request: DeleteRuntimeRequestSchema,
360 execute: ({ threadId }) =>
361 sql`
362 DELETE FROM provider_session_runtime
363 WHERE thread_id = ${threadId}
364 `,
365 });
366
367 const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime, options) =>
368 (options?.onConflict === "ignore" ? insertRuntimeRow(runtime) : upsertRuntimeRow(runtime)).pipe(
369 Effect.mapError(
370 toPersistenceSqlOrDecodeError(
371 "ProviderSessionRuntimeRepository.upsert:query",
372 "ProviderSessionRuntimeRepository.upsert:encodeRequest",
373 { threadId: runtime.threadId },
374 ),
375 ),
376 );
377
378 const recordImportedTranscript: ProviderSessionRuntimeRepository["Service"]["recordImportedTranscript"] =
379 (input) =>
380 recordImportedTranscriptRow(input).pipe(
381 Effect.mapError(
382 toPersistenceSqlOrDecodeError(
383 "ProviderSessionRuntimeRepository.recordImportedTranscript:query",
384 "ProviderSessionRuntimeRepository.recordImportedTranscript:encodeRequest",
385 { threadId: input.threadId },
386 ),
387 ),
388 );
389
390 const getByThreadId: ProviderSessionRuntimeRepository["Service"]["getByThreadId"] = (input) =>
391 getRuntimeRowByThreadId(input).pipe(
392 Effect.mapError(
393 toPersistenceSqlOrDecodeError(
394 "ProviderSessionRuntimeRepository.getByThreadId:query",
395 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
396 { threadId: input.threadId },
397 ),
398 ),
399 Effect.flatMap((runtimeRowOption) =>
400 Option.match(runtimeRowOption, {
401 onNone: () => Effect.succeed(Option.none()),
402 onSome: (row) =>
403 decodeRuntimeRow(row).pipe(
404 Effect.mapError((cause) =>
405 PersistenceDecodeError.fromSchemaError(
406 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
407 cause,
408 { threadId: input.threadId },
409 ),
410 ),
411 Effect.map((runtime) => Option.some(runtime)),
412 ),
413 }),
414 ),
415 );
416
417 const list: ProviderSessionRuntimeRepository["Service"]["list"] = () =>
418 listRuntimeRows(undefined).pipe(
419 Effect.mapError(
420 toPersistenceSqlOrDecodeError(
421 "ProviderSessionRuntimeRepository.list:query",
422 "ProviderSessionRuntimeRepository.list:decodeRows",
423 ),
424 ),
425 Effect.flatMap((rows) =>
426 // Skip rows that no longer decode (e.g. written by an older build)
427 // instead of failing the whole list — one stale row must not disable
428 // every consumer that enumerates sessions, such as the reaper.
429 Effect.forEach(rows, (row) =>
430 decodeRuntimeRow(row).pipe(
431 Effect.map(Option.some),
432 Effect.catch((cause) =>
433 Effect.logWarning("provider.session.runtime.row-skipped", {
434 threadId: row.threadId,
435 error: PersistenceDecodeError.fromSchemaError(
436 "ProviderSessionRuntimeRepository.list:decodeRows",
437 cause,
438 { threadId: row.threadId },
439 ).message,
440 }).pipe(Effect.as(Option.none<ProviderSessionRuntime>())),
441 ),
442 ),
443 ),
444 ),
445 Effect.map((decoded) =>
446 Arr.filterMap(decoded, (row) =>
447 Option.isSome(row) ? Result.succeed(row.value) : Result.failVoid,
448 ),
449 ),
450 );
451
452 const deleteByThreadId: ProviderSessionRuntimeRepository["Service"]["deleteByThreadId"] = (
453 input,
454 ) =>
455 deleteRuntimeByThreadId(input).pipe(
456 Effect.mapError(
457 (cause) =>
458 new PersistenceSqlError({
459 operation: "ProviderSessionRuntimeRepository.deleteByThreadId:query",
460 correlation: { threadId: input.threadId },
461 cause,
462 }),
463 ),
464 );
465
466 return {
467 upsert,
468 recordImportedTranscript,
469 getByThreadId,
470 list,
471 deleteByThreadId,
472 } satisfies ProviderSessionRuntimeRepository["Service"];
473});
474
475export const layer = Layer.effect(ProviderSessionRuntimeRepository, make);