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 ProviderSessionRuntimeStatus,
17 RuntimeMode,
18 ThreadId,
19} from "@t3tools/contracts";
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
169export const make = Effect.gen(function* () {
170 const sql = yield* SqlClient.SqlClient;
171
172 // Runtime writes can carry stale payloads. Only recordImportedTranscript may
173 // change source records, so restore that field from the row being updated.
174 const upsertRuntimeRow = SqlSchema.void({
175 Request: ProviderSessionRuntimeDbRowSchema,
176 execute: (runtime) =>
177 sql`
178 INSERT INTO provider_session_runtime (
179 thread_id,
180 provider_name,
181 provider_instance_id,
182 adapter_key,
183 runtime_mode,
184 status,
185 last_seen_at,
186 resume_cursor_json,
187 runtime_payload_json
188 )
189 VALUES (
190 ${runtime.threadId},
191 ${runtime.providerName},
192 ${runtime.providerInstanceId},
193 ${runtime.adapterKey},
194 ${runtime.runtimeMode},
195 ${runtime.status},
196 ${runtime.lastSeenAt},
197 ${runtime.resumeCursor},
198 CASE
199 WHEN json_type(${runtime.runtimePayload}) = 'object'
200 THEN json_remove(${runtime.runtimePayload}, '$.importedTranscripts')
201 ELSE ${runtime.runtimePayload}
202 END
203 )
204 ON CONFLICT (thread_id)
205 DO UPDATE SET
206 provider_name = excluded.provider_name,
207 provider_instance_id = excluded.provider_instance_id,
208 adapter_key = excluded.adapter_key,
209 runtime_mode = excluded.runtime_mode,
210 status = excluded.status,
211 last_seen_at = excluded.last_seen_at,
212 resume_cursor_json = excluded.resume_cursor_json,
213 runtime_payload_json = CASE
214 WHEN json_type(
215 CASE
216 WHEN json_valid(provider_session_runtime.runtime_payload_json)
217 THEN provider_session_runtime.runtime_payload_json
218 ELSE '{}'
219 END,
220 '$.importedTranscripts'
221 ) IS NOT NULL
222 THEN json_set(
223 CASE
224 WHEN json_type(excluded.runtime_payload_json) = 'object'
225 THEN excluded.runtime_payload_json
226 ELSE '{}'
227 END,
228 '$.importedTranscripts',
229 json_extract(provider_session_runtime.runtime_payload_json, '$.importedTranscripts')
230 )
231 ELSE excluded.runtime_payload_json
232 END
233 `,
234 });
235
236 const insertRuntimeRow = SqlSchema.void({
237 Request: ProviderSessionRuntimeDbRowSchema,
238 execute: (runtime) =>
239 sql`
240 INSERT INTO provider_session_runtime (
241 thread_id,
242 provider_name,
243 provider_instance_id,
244 adapter_key,
245 runtime_mode,
246 status,
247 last_seen_at,
248 resume_cursor_json,
249 runtime_payload_json
250 )
251 VALUES (
252 ${runtime.threadId},
253 ${runtime.providerName},
254 ${runtime.providerInstanceId},
255 ${runtime.adapterKey},
256 ${runtime.runtimeMode},
257 ${runtime.status},
258 ${runtime.lastSeenAt},
259 ${runtime.resumeCursor},
260 CASE
261 WHEN json_type(${runtime.runtimePayload}) = 'object'
262 THEN json_remove(${runtime.runtimePayload}, '$.importedTranscripts')
263 ELSE ${runtime.runtimePayload}
264 END
265 )
266 ON CONFLICT (thread_id) DO NOTHING
267 `,
268 });
269
270 const recordImportedTranscriptRow = SqlSchema.void({
271 Request: RecordImportedTranscriptRequestSchema,
272 execute: ({ threadId, source }) =>
273 sql`
274 WITH current_runtime AS (
275 SELECT CASE
276 WHEN json_valid(runtime_payload_json) THEN CASE
277 WHEN json_type(runtime_payload_json) = 'object' THEN runtime_payload_json
278 ELSE '{}'
279 END
280 ELSE '{}'
281 END AS payload
282 FROM provider_session_runtime
283 WHERE thread_id = ${threadId}
284 )
285 UPDATE provider_session_runtime
286 SET runtime_payload_json = (
287 SELECT json_set(
288 payload,
289 '$.importedTranscripts',
290 json((
291 SELECT json_group_array(json(value))
292 FROM (
293 SELECT value
294 FROM json_each(CASE
295 WHEN json_type(payload, '$.importedTranscripts') = 'array'
296 THEN json_extract(payload, '$.importedTranscripts')
297 ELSE '[]'
298 END)
299 WHERE CASE
300 WHEN type = 'object' THEN
301 json_extract(value, '$.providerInstanceId')
302 IS NOT json_extract(${source}, '$.providerInstanceId')
303 OR json_extract(value, '$.filePath') IS NOT json_extract(${source}, '$.filePath')
304 ELSE 0
305 END
306 UNION ALL
307 SELECT ${source} AS value
308 )
309 ))
310 )
311 FROM current_runtime
312 )
313 WHERE thread_id = ${threadId}
314 `,
315 });
316
317 const getRuntimeRowByThreadId = SqlSchema.findOneOption({
318 Request: GetRuntimeRequestSchema,
319 Result: ProviderSessionRuntimeRawDbRowSchema,
320 execute: ({ threadId }) =>
321 sql`
322 SELECT
323 thread_id AS "threadId",
324 provider_name AS "providerName",
325 provider_instance_id AS "providerInstanceId",
326 adapter_key AS "adapterKey",
327 runtime_mode AS "runtimeMode",
328 status,
329 last_seen_at AS "lastSeenAt",
330 resume_cursor_json AS "resumeCursor",
331 runtime_payload_json AS "runtimePayload"
332 FROM provider_session_runtime
333 WHERE thread_id = ${threadId}
334 `,
335 });
336
337 const listRuntimeRows = SqlSchema.findAll({
338 Request: Schema.Void,
339 Result: ProviderSessionRuntimeRawDbRowSchema,
340 execute: () =>
341 sql`
342 SELECT
343 thread_id AS "threadId",
344 provider_name AS "providerName",
345 provider_instance_id AS "providerInstanceId",
346 adapter_key AS "adapterKey",
347 runtime_mode AS "runtimeMode",
348 status,
349 last_seen_at AS "lastSeenAt",
350 resume_cursor_json AS "resumeCursor",
351 runtime_payload_json AS "runtimePayload"
352 FROM provider_session_runtime
353 ORDER BY last_seen_at ASC, thread_id ASC
354 `,
355 });
356
357 const deleteRuntimeByThreadId = SqlSchema.void({
358 Request: DeleteRuntimeRequestSchema,
359 execute: ({ threadId }) =>
360 sql`
361 DELETE FROM provider_session_runtime
362 WHERE thread_id = ${threadId}
363 `,
364 });
365
366 const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime, options) =>
367 (options?.onConflict === "ignore" ? insertRuntimeRow(runtime) : upsertRuntimeRow(runtime)).pipe(
368 Effect.mapError(
369 toPersistenceSqlOrDecodeError(
370 "ProviderSessionRuntimeRepository.upsert:query",
371 "ProviderSessionRuntimeRepository.upsert:encodeRequest",
372 { threadId: runtime.threadId },
373 ),
374 ),
375 );
376
377 const recordImportedTranscript: ProviderSessionRuntimeRepository["Service"]["recordImportedTranscript"] =
378 (input) =>
379 recordImportedTranscriptRow(input).pipe(
380 Effect.mapError(
381 toPersistenceSqlOrDecodeError(
382 "ProviderSessionRuntimeRepository.recordImportedTranscript:query",
383 "ProviderSessionRuntimeRepository.recordImportedTranscript:encodeRequest",
384 { threadId: input.threadId },
385 ),
386 ),
387 );
388
389 const getByThreadId: ProviderSessionRuntimeRepository["Service"]["getByThreadId"] = (input) =>
390 getRuntimeRowByThreadId(input).pipe(
391 Effect.mapError(
392 toPersistenceSqlOrDecodeError(
393 "ProviderSessionRuntimeRepository.getByThreadId:query",
394 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
395 { threadId: input.threadId },
396 ),
397 ),
398 Effect.flatMap((runtimeRowOption) =>
399 Option.match(runtimeRowOption, {
400 onNone: () => Effect.succeed(Option.none()),
401 onSome: (row) =>
402 decodeRuntimeRow(row).pipe(
403 Effect.mapError((cause) =>
404 PersistenceDecodeError.fromSchemaError(
405 "ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
406 cause,
407 { threadId: input.threadId },
408 ),
409 ),
410 Effect.map((runtime) => Option.some(runtime)),
411 ),
412 }),
413 ),
414 );
415
416 const list: ProviderSessionRuntimeRepository["Service"]["list"] = () =>
417 listRuntimeRows(undefined).pipe(
418 Effect.mapError(
419 toPersistenceSqlOrDecodeError(
420 "ProviderSessionRuntimeRepository.list:query",
421 "ProviderSessionRuntimeRepository.list:decodeRows",
422 ),
423 ),
424 Effect.flatMap((rows) =>
425 // Skip rows that no longer decode (e.g. written by an older build)
426 // instead of failing the whole list — one stale row must not disable
427 // every consumer that enumerates sessions, such as the reaper.
428 Effect.forEach(rows, (row) =>
429 decodeRuntimeRow(row).pipe(
430 Effect.map(Option.some),
431 Effect.catch((cause) =>
432 Effect.logWarning("provider.session.runtime.row-skipped", {
433 threadId: row.threadId,
434 error: PersistenceDecodeError.fromSchemaError(
435 "ProviderSessionRuntimeRepository.list:decodeRows",
436 cause,
437 { threadId: row.threadId },
438 ).message,
439 }).pipe(Effect.as(Option.none<ProviderSessionRuntime>())),
440 ),
441 ),
442 ),
443 ),
444 Effect.map((decoded) =>
445 Arr.filterMap(decoded, (row) =>
446 Option.isSome(row) ? Result.succeed(row.value) : Result.failVoid,
447 ),
448 ),
449 );
450
451 const deleteByThreadId: ProviderSessionRuntimeRepository["Service"]["deleteByThreadId"] = (
452 input,
453 ) =>
454 deleteRuntimeByThreadId(input).pipe(
455 Effect.mapError(
456 (cause) =>
457 new PersistenceSqlError({
458 operation: "ProviderSessionRuntimeRepository.deleteByThreadId:query",
459 correlation: { threadId: input.threadId },
460 cause,
461 }),
462 ),
463 );
464
465 return {
466 upsert,
467 recordImportedTranscript,
468 getByThreadId,
469 list,
470 deleteByThreadId,
471 } satisfies ProviderSessionRuntimeRepository["Service"];
472});
473
474export const layer = Layer.effect(ProviderSessionRuntimeRepository, make);