@sixb/pg 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/agents/agent-storage.d.ts +4 -0
  2. package/dist/agents/agent-storage.d.ts.map +1 -1
  3. package/dist/agents/approvals.d.ts +2 -1
  4. package/dist/agents/approvals.d.ts.map +1 -1
  5. package/dist/agents/checkpoints.d.ts +2 -1
  6. package/dist/agents/checkpoints.d.ts.map +1 -1
  7. package/dist/agents/inbox.d.ts +23 -0
  8. package/dist/agents/inbox.d.ts.map +1 -0
  9. package/dist/agents/messages.d.ts +2 -1
  10. package/dist/agents/messages.d.ts.map +1 -1
  11. package/dist/agents/reads.d.ts +9 -0
  12. package/dist/agents/reads.d.ts.map +1 -0
  13. package/dist/agents/runs.d.ts +2 -1
  14. package/dist/agents/runs.d.ts.map +1 -1
  15. package/dist/agents/threads.d.ts.map +1 -1
  16. package/dist/index.js +1212 -87
  17. package/dist/index.js.map +17 -15
  18. package/dist/latest-run-query.d.ts +3 -1
  19. package/dist/latest-run-query.d.ts.map +1 -1
  20. package/dist/migrations.d.ts.map +1 -1
  21. package/dist/ontology-storage/replacement-plans.d.ts.map +1 -1
  22. package/dist/pg-ai-cost-storage.d.ts.map +1 -1
  23. package/dist/pg-artifact-storage.d.ts +4 -1
  24. package/dist/pg-artifact-storage.d.ts.map +1 -1
  25. package/dist/pg-sync-run-storage.d.ts +2 -1
  26. package/dist/pg-sync-run-storage.d.ts.map +1 -1
  27. package/package.json +3 -3
  28. package/src/agents/agent-storage.ts +6 -0
  29. package/src/agents/approvals.ts +44 -0
  30. package/src/agents/checkpoints.ts +26 -0
  31. package/src/agents/inbox.ts +421 -0
  32. package/src/agents/messages.ts +81 -2
  33. package/src/agents/reads.ts +160 -0
  34. package/src/agents/runs.ts +25 -0
  35. package/src/agents/threads.ts +95 -11
  36. package/src/latest-run-query.ts +8 -1
  37. package/src/migrations/103-script-executions.sql +145 -0
  38. package/src/migrations/104-artifact-pdfs.sql +18 -0
  39. package/src/migrations/105-guest-comment-links.sql +17 -0
  40. package/src/migrations/106-agent-thread-inbox.sql +36 -0
  41. package/src/migrations/107-agent-inbox-edits.sql +3 -0
  42. package/src/migrations/108-agent-thread-reads.sql +73 -0
  43. package/src/migrations/109-sync-run-connections.sql +6 -0
  44. package/src/migrations.ts +14 -0
  45. package/src/ontology-storage/replacement-plans.ts +51 -1
  46. package/src/pg-ai-cost-storage.ts +35 -20
  47. package/src/pg-artifact-storage.ts +67 -9
  48. package/src/pg-sync-run-storage.ts +69 -0
@@ -0,0 +1,421 @@
1
+ import type { AgentMessagePart, Principal } from "@sixb/core"
2
+ import {
3
+ assertEnqueueAgentInboxItemInput,
4
+ assertInboxRunOwnership,
5
+ assertInboxThreadAcceptsItem,
6
+ assertTakeAgentInboxSteersInput,
7
+ assertUpdateAgentInboxItemInput,
8
+ newAgentInboxItemRecord,
9
+ updatedAgentInboxItemRecord,
10
+ } from "@sixb/core/internal/agent-run-storage-provider"
11
+ import {
12
+ type AgentInboxItemRecord,
13
+ type AgentInboxMode,
14
+ type AgentInboxSpec,
15
+ type AgentInboxStore,
16
+ AgentStorageError,
17
+ type AgentThreadRecord,
18
+ type ConsumeClaimedAgentInboxInput,
19
+ type EnqueueAgentInboxItemInput,
20
+ type EnqueueAgentInboxItemResult,
21
+ type ListAgentInboxItemsInput,
22
+ type ListWaitingAgentInboxThreadsInput,
23
+ type RemoveAgentInboxItemInput,
24
+ type TakeAgentInboxSteersInput,
25
+ type TakeNextQueuedAgentInboxInput,
26
+ type UpdateAgentInboxItemInput,
27
+ } from "@sixb/core/storage"
28
+ import type { SQLClient } from "../pg-client"
29
+ import { isUniqueViolation } from "../storage-errors"
30
+ import { type PgStoreClient, runPgTransaction } from "../transactions"
31
+ import { type AgentRunRow, rowToRunRecord } from "./rows"
32
+
33
+ interface AgentInboxRow {
34
+ readonly project_id: string
35
+ readonly id: string
36
+ readonly thread_id: string
37
+ readonly message_id: string
38
+ readonly seq: number | string
39
+ readonly author_principal_type: Principal["type"]
40
+ readonly author_principal_id: string
41
+ readonly mode: AgentInboxMode
42
+ readonly parts: readonly AgentMessagePart[] | string
43
+ readonly spec: AgentInboxSpec | string | null
44
+ readonly time_zone: string | null
45
+ readonly locale: string | null
46
+ readonly immediate: boolean
47
+ readonly replaces_message_id: string | null
48
+ readonly execution_id: string | null
49
+ readonly claimed_by_run_id: string | null
50
+ readonly claimed_by_token: string | null
51
+ readonly claimed_by_step: number | string | null
52
+ readonly claimed_after_answer: boolean | null
53
+ readonly created_at: Date | string
54
+ readonly updated_at: Date | string
55
+ }
56
+
57
+ interface ThreadSummaryRow {
58
+ readonly id: string
59
+ readonly kind: AgentThreadRecord["kind"]
60
+ readonly status: AgentThreadRecord["status"]
61
+ readonly active_run_id: string | null
62
+ }
63
+
64
+ export class PgAgentInboxStore implements AgentInboxStore {
65
+ constructor(private readonly sql: PgStoreClient) {}
66
+
67
+ async enqueue(input: EnqueueAgentInboxItemInput): Promise<EnqueueAgentInboxItemResult> {
68
+ assertEnqueueAgentInboxItemInput(input, "SixbPg")
69
+
70
+ try {
71
+ return await runPgTransaction(this.sql, async (tx) => {
72
+ const [existing] = await tx<AgentInboxRow[]>`
73
+ SELECT * FROM agent_thread_inbox
74
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
75
+ FOR UPDATE
76
+ `
77
+ if (existing) {
78
+ if (existing.thread_id === input.threadId) {
79
+ return { item: rowToInboxItem(existing), created: false }
80
+ }
81
+ throw new AgentStorageError(
82
+ "duplicate_id",
83
+ `[SixbPg] Agent inbox item '${input.id}' already exists on another thread in project '${input.projectId}'.`
84
+ )
85
+ }
86
+
87
+ const [thread] = await tx<ThreadSummaryRow[]>`
88
+ SELECT id, kind, status, active_run_id FROM agent_threads
89
+ WHERE project_id = ${input.projectId} AND id = ${input.threadId}
90
+ FOR UPDATE
91
+ `
92
+ const [counts] = await tx<{ count: number | string; max_seq: number | string }[]>`
93
+ SELECT COUNT(*) AS count, COALESCE(MAX(seq), 0) AS max_seq
94
+ FROM agent_thread_inbox
95
+ WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
96
+ `
97
+ assertInboxThreadAcceptsItem(
98
+ thread ?? null,
99
+ input.threadId,
100
+ input.projectId,
101
+ Number(counts?.count ?? 0),
102
+ "SixbPg"
103
+ )
104
+
105
+ const [existingMessage] = await tx<{ id: string }[]>`
106
+ SELECT id FROM agent_messages
107
+ WHERE project_id = ${input.projectId} AND id = ${input.messageId}
108
+ `
109
+ if (existingMessage) {
110
+ throw new AgentStorageError(
111
+ "duplicate_id",
112
+ `[SixbPg] Agent message '${input.messageId}' already exists for project '${input.projectId}'.`
113
+ )
114
+ }
115
+
116
+ const record = newAgentInboxItemRecord(input, Number(counts?.max_seq ?? 0) + 1)
117
+ const [inserted] = await tx<AgentInboxRow[]>`
118
+ INSERT INTO agent_thread_inbox (
119
+ project_id, id, thread_id, message_id, seq,
120
+ author_principal_type, author_principal_id, mode, parts, spec,
121
+ time_zone, locale, immediate, replaces_message_id, execution_id, created_at, updated_at
122
+ ) VALUES (
123
+ ${record.projectId},
124
+ ${record.id},
125
+ ${record.threadId},
126
+ ${record.messageId},
127
+ ${record.seq},
128
+ ${record.authorPrincipal.type},
129
+ ${record.authorPrincipal.id},
130
+ ${record.mode},
131
+ ${JSON.stringify(record.parts)}::text::jsonb,
132
+ ${record.spec === undefined ? null : JSON.stringify(record.spec)}::text::jsonb,
133
+ ${record.timeZone ?? null},
134
+ ${record.locale ?? null},
135
+ ${Boolean(record.immediate)},
136
+ ${record.replacesMessageId ?? null},
137
+ ${record.executionId ?? null},
138
+ ${record.createdAt},
139
+ ${record.updatedAt}
140
+ )
141
+ RETURNING *
142
+ `
143
+ return { item: rowToInboxItem(inserted!), created: true }
144
+ })
145
+ } catch (error) {
146
+ if (isUniqueViolation(error)) {
147
+ throw new AgentStorageError(
148
+ "duplicate_id",
149
+ `[SixbPg] Agent inbox item or message id already exists for project '${input.projectId}'.`
150
+ )
151
+ }
152
+ throw error
153
+ }
154
+ }
155
+
156
+ async getById(params: { projectId: string; id: string }): Promise<AgentInboxItemRecord | null> {
157
+ const [row] = await this.sql<AgentInboxRow[]>`
158
+ SELECT * FROM agent_thread_inbox
159
+ WHERE project_id = ${params.projectId} AND id = ${params.id}
160
+ `
161
+ return row ? rowToInboxItem(row) : null
162
+ }
163
+
164
+ async list(input: ListAgentInboxItemsInput): Promise<readonly AgentInboxItemRecord[]> {
165
+ const includeClaimed = input.includeClaimed ?? true
166
+ const rows = includeClaimed
167
+ ? await this.sql<AgentInboxRow[]>`
168
+ SELECT * FROM agent_thread_inbox
169
+ WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
170
+ ORDER BY seq ASC
171
+ `
172
+ : await this.sql<AgentInboxRow[]>`
173
+ SELECT * FROM agent_thread_inbox
174
+ WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
175
+ AND claimed_by_run_id IS NULL
176
+ ORDER BY seq ASC
177
+ `
178
+ return rows.map(rowToInboxItem)
179
+ }
180
+
181
+ async listWaitingThreads(input: ListWaitingAgentInboxThreadsInput): Promise<readonly string[]> {
182
+ const rows = await this.sql<{ thread_id: string }[]>`
183
+ SELECT DISTINCT inbox.thread_id
184
+ FROM agent_thread_inbox inbox
185
+ JOIN agent_threads thread
186
+ ON thread.project_id = inbox.project_id AND thread.id = inbox.thread_id
187
+ WHERE inbox.project_id = ${input.projectId}
188
+ AND inbox.created_at < ${input.createdBefore}
189
+ AND inbox.thread_id > ${input.afterThreadId ?? ""}
190
+ AND thread.active_run_id IS NULL
191
+ ORDER BY inbox.thread_id ASC
192
+ LIMIT ${input.limit}
193
+ `
194
+ return rows.map((row) => row.thread_id)
195
+ }
196
+
197
+ async update(input: UpdateAgentInboxItemInput): Promise<AgentInboxItemRecord | null> {
198
+ assertUpdateAgentInboxItemInput(input, "SixbPg")
199
+
200
+ return runPgTransaction(this.sql, async (tx) => {
201
+ const [current] = await tx<AgentInboxRow[]>`
202
+ SELECT * FROM agent_thread_inbox
203
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
204
+ FOR UPDATE
205
+ `
206
+ if (!current || current.thread_id !== input.threadId) return null
207
+
208
+ const next = updatedAgentInboxItemRecord(rowToInboxItem(current), input)
209
+ const [updated] = await tx<AgentInboxRow[]>`
210
+ UPDATE agent_thread_inbox
211
+ SET
212
+ mode = ${next.mode},
213
+ parts = ${JSON.stringify(next.parts)}::text::jsonb,
214
+ spec = ${next.spec === undefined ? null : JSON.stringify(next.spec)}::text::jsonb,
215
+ immediate = ${Boolean(next.immediate)},
216
+ updated_at = ${next.updatedAt}
217
+ WHERE project_id = ${next.projectId} AND id = ${next.id}
218
+ RETURNING *
219
+ `
220
+ return updated ? rowToInboxItem(updated) : null
221
+ })
222
+ }
223
+
224
+ async remove(input: RemoveAgentInboxItemInput): Promise<AgentInboxItemRecord | null> {
225
+ return runPgTransaction(this.sql, async (tx) => {
226
+ const [current] = await tx<AgentInboxRow[]>`
227
+ SELECT * FROM agent_thread_inbox
228
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
229
+ FOR UPDATE
230
+ `
231
+ if (!current || current.thread_id !== input.threadId) return null
232
+ if (current.claimed_by_run_id !== null) {
233
+ throw new AgentStorageError(
234
+ "invalid_state",
235
+ `[SixbPg] Agent inbox item '${current.id}' was already claimed by run '${current.claimed_by_run_id}'.`
236
+ )
237
+ }
238
+ await tx`
239
+ DELETE FROM agent_thread_inbox
240
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
241
+ `
242
+ return rowToInboxItem(current)
243
+ })
244
+ }
245
+
246
+ async takeSteers(input: TakeAgentInboxSteersInput): Promise<readonly AgentInboxItemRecord[]> {
247
+ assertTakeAgentInboxSteersInput(input, "SixbPg")
248
+
249
+ return runPgTransaction(this.sql, async (tx) => {
250
+ const run = await lockRun(tx, input.projectId, input.runId)
251
+ assertInboxRunOwnership(run, input, "SixbPg")
252
+
253
+ const updatedAt = new Date()
254
+ const rows = await tx<AgentInboxRow[]>`
255
+ UPDATE agent_thread_inbox
256
+ SET
257
+ claimed_by_run_id = ${input.runId},
258
+ claimed_by_token = ${input.executionToken},
259
+ claimed_by_step = ${input.stepIndex},
260
+ claimed_after_answer = ${input.afterAnswer ? true : null}::boolean,
261
+ updated_at = ${updatedAt}
262
+ WHERE project_id = ${input.projectId}
263
+ AND thread_id = ${input.threadId}
264
+ AND (
265
+ claimed_by_run_id IS NULL
266
+ OR claimed_by_run_id <> ${input.runId}
267
+ OR claimed_by_token <> ${input.executionToken}
268
+ )
269
+ AND mode = 'steer'
270
+ AND immediate = FALSE
271
+ AND author_principal_type = ${input.authorPrincipal.type}
272
+ AND author_principal_id = ${input.authorPrincipal.id}
273
+ RETURNING *
274
+ `
275
+ return rows.map(rowToInboxItem).sort((left, right) => left.seq - right.seq)
276
+ })
277
+ }
278
+
279
+ async consumeClaimed(
280
+ input: ConsumeClaimedAgentInboxInput
281
+ ): Promise<readonly AgentInboxItemRecord[]> {
282
+ return runPgTransaction(this.sql, async (tx) => {
283
+ const run = await lockRun(tx, input.projectId, input.runId)
284
+ assertInboxRunOwnership(run, input, "SixbPg")
285
+
286
+ const claimed = await tx<AgentInboxRow[]>`
287
+ SELECT * FROM agent_thread_inbox
288
+ WHERE project_id = ${input.projectId}
289
+ AND thread_id = ${input.threadId}
290
+ AND claimed_by_run_id = ${input.runId}
291
+ AND claimed_by_token = ${input.executionToken}
292
+ ORDER BY seq ASC
293
+ FOR UPDATE
294
+ `
295
+ if (claimed.length === 0) return []
296
+
297
+ const persisted = new Set(input.messageIds)
298
+ const updatedAt = new Date()
299
+ const consumed: AgentInboxItemRecord[] = []
300
+ for (const row of claimed) {
301
+ if (persisted.has(row.message_id)) {
302
+ await tx`
303
+ DELETE FROM agent_thread_inbox
304
+ WHERE project_id = ${row.project_id} AND id = ${row.id}
305
+ `
306
+ consumed.push(rowToInboxItem(row))
307
+ } else {
308
+ await tx`
309
+ UPDATE agent_thread_inbox
310
+ SET
311
+ claimed_by_run_id = NULL,
312
+ claimed_by_token = NULL,
313
+ claimed_by_step = NULL,
314
+ claimed_after_answer = NULL,
315
+ updated_at = ${updatedAt}
316
+ WHERE project_id = ${row.project_id} AND id = ${row.id}
317
+ `
318
+ }
319
+ }
320
+ return consumed
321
+ })
322
+ }
323
+
324
+ async releaseClaimed(input: { projectId: string; runId: string }): Promise<number> {
325
+ const updatedAt = new Date()
326
+ const rows = await this.sql<{ id: string }[]>`
327
+ UPDATE agent_thread_inbox
328
+ SET
329
+ claimed_by_run_id = NULL,
330
+ claimed_by_token = NULL,
331
+ claimed_by_step = NULL,
332
+ claimed_after_answer = NULL,
333
+ updated_at = ${updatedAt}
334
+ WHERE project_id = ${input.projectId} AND claimed_by_run_id = ${input.runId}
335
+ RETURNING id
336
+ `
337
+ return rows.length
338
+ }
339
+
340
+ async takeNextQueued(input: TakeNextQueuedAgentInboxInput): Promise<AgentInboxItemRecord | null> {
341
+ return runPgTransaction(this.sql, async (tx) => {
342
+ const [thread] = await tx<ThreadSummaryRow[]>`
343
+ SELECT id, kind, status, active_run_id FROM agent_threads
344
+ WHERE project_id = ${input.projectId} AND id = ${input.threadId}
345
+ FOR UPDATE
346
+ `
347
+ if (!thread || thread.status !== "active" || thread.active_run_id !== null) return null
348
+
349
+ const [winner] = await tx<AgentInboxRow[]>`
350
+ SELECT * FROM agent_thread_inbox
351
+ WHERE project_id = ${input.projectId}
352
+ AND thread_id = ${input.threadId}
353
+ AND claimed_by_run_id IS NULL
354
+ AND (${!input.onlyImmediate}::boolean OR immediate = TRUE)
355
+ AND (
356
+ ${input.authorPrincipal?.id ?? null}::text IS NULL
357
+ OR (author_principal_type = ${input.authorPrincipal?.type ?? null}
358
+ AND author_principal_id = ${input.authorPrincipal?.id ?? null})
359
+ )
360
+ ORDER BY
361
+ CASE WHEN immediate = TRUE THEN 0 WHEN mode = 'steer' THEN 1 ELSE 2 END ASC,
362
+ seq ASC
363
+ LIMIT 1
364
+ FOR UPDATE
365
+ `
366
+ if (!winner) return null
367
+
368
+ await tx`
369
+ DELETE FROM agent_thread_inbox
370
+ WHERE project_id = ${winner.project_id} AND id = ${winner.id}
371
+ `
372
+ return rowToInboxItem(winner)
373
+ })
374
+ }
375
+ }
376
+
377
+ async function lockRun(tx: SQLClient, projectId: string, id: string) {
378
+ const [row] = await tx<AgentRunRow[]>`
379
+ SELECT * FROM agent_runs WHERE project_id = ${projectId} AND id = ${id} FOR UPDATE
380
+ `
381
+ return row ? rowToRunRecord(row) : null
382
+ }
383
+
384
+ function parseJson<T>(value: T | string): T {
385
+ return typeof value === "string" ? (JSON.parse(value) as T) : value
386
+ }
387
+
388
+ function rowToInboxItem(row: AgentInboxRow): AgentInboxItemRecord {
389
+ const spec = row.spec === null ? undefined : parseJson<AgentInboxSpec>(row.spec)
390
+ const claimedBy =
391
+ row.claimed_by_run_id !== null && row.claimed_by_token !== null && row.claimed_by_step !== null
392
+ ? {
393
+ runId: row.claimed_by_run_id,
394
+ executionToken: row.claimed_by_token,
395
+ stepIndex: Number(row.claimed_by_step),
396
+ ...(row.claimed_after_answer === true ? { afterAnswer: true } : {}),
397
+ }
398
+ : undefined
399
+ return {
400
+ id: row.id,
401
+ projectId: row.project_id,
402
+ threadId: row.thread_id,
403
+ messageId: row.message_id,
404
+ seq: Number(row.seq),
405
+ authorPrincipal: {
406
+ type: row.author_principal_type,
407
+ id: row.author_principal_id,
408
+ },
409
+ mode: row.mode,
410
+ parts: parseJson<readonly AgentMessagePart[]>(row.parts),
411
+ ...(spec ? { spec } : {}),
412
+ ...(row.time_zone ? { timeZone: row.time_zone } : {}),
413
+ ...(row.locale ? { locale: row.locale } : {}),
414
+ ...(row.immediate ? { immediate: true } : {}),
415
+ ...(row.replaces_message_id ? { replacesMessageId: row.replaces_message_id } : {}),
416
+ ...(row.execution_id ? { executionId: row.execution_id } : {}),
417
+ ...(claimedBy ? { claimedBy } : {}),
418
+ createdAt: new Date(row.created_at),
419
+ updatedAt: new Date(row.updated_at),
420
+ }
421
+ }
@@ -1,4 +1,7 @@
1
- import { countsAsThreadMessage } from "@sixb/core/internal/agent-run-storage-provider"
1
+ import {
2
+ assertDeleteAgentMessagesFromSeqInput,
3
+ countsAsThreadMessage,
4
+ } from "@sixb/core/internal/agent-run-storage-provider"
2
5
  import { AGENT_MESSAGE_CONTENT_VERSION } from "@sixb/core/internal/agents"
3
6
  import {
4
7
  type AgentMessageRecord,
@@ -6,10 +9,11 @@ import {
6
9
  AgentStorageError,
7
10
  type AppendAgentMessageInput,
8
11
  type DeleteAgentMessagesByRunInput,
12
+ type DeleteAgentMessagesFromSeqInput,
9
13
  type ListAgentMessagesInput,
10
14
  type ListAgentMessagesResult,
11
15
  } from "@sixb/core/storage"
12
- import type { SqlParameter } from "../pg-client"
16
+ import type { SQLClient, SqlParameter } from "../pg-client"
13
17
  import { isUniqueViolation } from "../storage-errors"
14
18
  import { type PgStoreClient, runPgTransaction } from "../transactions"
15
19
  import { type AgentMessageRow, queryAgentList, rowToMessageRecord } from "./rows"
@@ -153,6 +157,7 @@ export class PgAgentMessageStore implements AgentMessageStore {
153
157
  if (deleted.length === 0) {
154
158
  return 0
155
159
  }
160
+ await clampReadsToHead(tx, input)
156
161
  // The thread counts only the messages the conversation shows: take back the ones it counted.
157
162
  const counted = deleted.filter((row) =>
158
163
  countsAsThreadMessage({
@@ -179,6 +184,58 @@ export class PgAgentMessageStore implements AgentMessageStore {
179
184
  })
180
185
  }
181
186
 
187
+ async deleteFromSeq(input: DeleteAgentMessagesFromSeqInput): Promise<number> {
188
+ assertDeleteAgentMessagesFromSeqInput(input, "SixbPg")
189
+
190
+ return runPgTransaction(this.sql, async (tx) => {
191
+ const [thread] = await tx<{ id: string }[]>`
192
+ SELECT id FROM agent_threads
193
+ WHERE project_id = ${input.projectId} AND id = ${input.threadId}
194
+ FOR UPDATE
195
+ `
196
+
197
+ if (!thread) {
198
+ throw new AgentStorageError(
199
+ "thread_not_found",
200
+ `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`
201
+ )
202
+ }
203
+
204
+ const deleted = await tx<{ id: string; parts: AgentMessageRecord["parts"] | string }[]>`
205
+ DELETE FROM agent_messages
206
+ WHERE project_id = ${input.projectId}
207
+ AND thread_id = ${input.threadId}
208
+ AND seq >= ${input.fromSeq}
209
+ RETURNING id, parts
210
+ `
211
+ if (deleted.length === 0) return 0
212
+ await clampReadsToHead(tx, input)
213
+
214
+ const counted = deleted.filter((row) =>
215
+ countsAsThreadMessage({
216
+ parts: typeof row.parts === "string" ? JSON.parse(row.parts) : row.parts,
217
+ })
218
+ ).length
219
+
220
+ const updatedAt = new Date()
221
+ await tx`
222
+ UPDATE agent_threads
223
+ SET
224
+ message_count = GREATEST(message_count - ${counted}, 0),
225
+ last_message_at = (
226
+ SELECT created_at FROM agent_messages
227
+ WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
228
+ ORDER BY seq DESC
229
+ LIMIT 1
230
+ ),
231
+ updated_at = ${updatedAt}
232
+ WHERE project_id = ${input.projectId} AND id = ${input.threadId}
233
+ `
234
+
235
+ return deleted.length
236
+ })
237
+ }
238
+
182
239
  async getById(params: { projectId: string; id: string }): Promise<AgentMessageRecord | null> {
183
240
  const [row] = await this.sql<AgentMessageRow[]>`
184
241
  SELECT * FROM agent_messages WHERE project_id = ${params.projectId} AND id = ${params.id}
@@ -222,3 +279,25 @@ export class PgAgentMessageStore implements AgentMessageStore {
222
279
  return { messages: rows.map(rowToMessageRecord), hasMore, total }
223
280
  }
224
281
  }
282
+
283
+ /**
284
+ * Bring every place past the thread's newest message back to it, after a deletion. The next
285
+ * message takes the number after the newest, so a place left past it would cover what a retry or
286
+ * an edit writes next. Messages up to the newest kept their numbers and stay read.
287
+ */
288
+ async function clampReadsToHead(
289
+ tx: SQLClient,
290
+ input: { readonly projectId: string; readonly threadId: string }
291
+ ): Promise<void> {
292
+ await tx`
293
+ UPDATE agent_thread_reads
294
+ SET through_seq = head.seq
295
+ FROM (
296
+ SELECT COALESCE(MAX(seq), 0) AS seq FROM agent_messages
297
+ WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
298
+ ) AS head
299
+ WHERE agent_thread_reads.project_id = ${input.projectId}
300
+ AND agent_thread_reads.thread_id = ${input.threadId}
301
+ AND agent_thread_reads.through_seq > head.seq
302
+ `
303
+ }
@@ -0,0 +1,160 @@
1
+ import {
2
+ AgentStorageError,
3
+ type AgentThreadReadState,
4
+ type AgentThreadReadStore,
5
+ type ListAgentThreadReadsInput,
6
+ type MarkAgentThreadReadInput,
7
+ } from "@sixb/core/storage"
8
+ import type { SQLClient } from "../pg-client"
9
+ import { type PgStoreClient, runPgTransaction } from "../transactions"
10
+
11
+ interface AgentThreadReadStateRow {
12
+ thread_id: string
13
+ head_seq: number | string
14
+ through_seq: number | string
15
+ read_at: Date | string | null
16
+ unread: number | string
17
+ }
18
+
19
+ export class PgAgentThreadReadStore implements AgentThreadReadStore {
20
+ constructor(private readonly sql: PgStoreClient) {}
21
+
22
+ async mark(input: MarkAgentThreadReadInput): Promise<AgentThreadReadState> {
23
+ return runPgTransaction(this.sql, async (tx) => {
24
+ // Appends and deletions hold the thread row FOR UPDATE: sharing it, the mark reads a
25
+ // thread no retry or edit is renumbering.
26
+ const [thread] = await tx<{ id: string }[]>`
27
+ SELECT id FROM agent_threads
28
+ WHERE project_id = ${input.projectId} AND id = ${input.threadId}
29
+ FOR SHARE
30
+ `
31
+ if (!thread) {
32
+ throw new AgentStorageError(
33
+ "thread_not_found",
34
+ `[SixbPg] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`
35
+ )
36
+ }
37
+
38
+ const reached = await reachedSeq(tx, input)
39
+ if (reached !== null) {
40
+ // Never backwards: another device that read further keeps its place. Looking always
41
+ // counts, so `read_at` moves even when the place does not.
42
+ await tx`
43
+ INSERT INTO agent_thread_reads (
44
+ project_id,
45
+ thread_id,
46
+ principal_type,
47
+ principal_id,
48
+ through_seq,
49
+ read_at
50
+ ) VALUES (
51
+ ${input.projectId},
52
+ ${input.threadId},
53
+ 'user',
54
+ ${input.principal.id},
55
+ ${reached},
56
+ ${input.readAt ?? new Date()}
57
+ )
58
+ ON CONFLICT (project_id, thread_id, principal_type, principal_id) DO UPDATE SET
59
+ through_seq = GREATEST(agent_thread_reads.through_seq, EXCLUDED.through_seq),
60
+ read_at = GREATEST(agent_thread_reads.read_at, EXCLUDED.read_at)
61
+ `
62
+ }
63
+
64
+ const [state] = await readStates(tx, input.projectId, input.principal.id, [input.threadId])
65
+ if (!state) {
66
+ throw new Error(`[SixbPg] Agent thread '${input.threadId}' lost its read state.`)
67
+ }
68
+ return state
69
+ })
70
+ }
71
+
72
+ async list(input: ListAgentThreadReadsInput): Promise<readonly AgentThreadReadState[]> {
73
+ if (input.threadIds.length === 0) return []
74
+
75
+ return readStates(this.sql, input.projectId, input.principal.id, [...new Set(input.threadIds)])
76
+ }
77
+ }
78
+
79
+ /** The seq a mark reaches: its message's, or the newest. `null` when the message is gone. */
80
+ async function reachedSeq(tx: SQLClient, input: MarkAgentThreadReadInput): Promise<number | null> {
81
+ if (input.throughMessageId === undefined) {
82
+ const [head] = await tx<{ seq: number | string }[]>`
83
+ SELECT COALESCE(MAX(seq), 0) AS seq FROM agent_messages
84
+ WHERE project_id = ${input.projectId} AND thread_id = ${input.threadId}
85
+ `
86
+ return Number(head?.seq ?? 0)
87
+ }
88
+
89
+ const [message] = await tx<{ seq: number | string }[]>`
90
+ SELECT seq FROM agent_messages
91
+ WHERE project_id = ${input.projectId}
92
+ AND thread_id = ${input.threadId}
93
+ AND id = ${input.throughMessageId}
94
+ `
95
+ return message ? Number(message.seq) : null
96
+ }
97
+
98
+ /**
99
+ * Each existing thread's place for one person, and the messages past it someone else wrote.
100
+ * No row reads as 0. A message counts unless it is their own user message or one that only
101
+ * reports approval outcomes (`countsAsThreadMessage`). Both reads walk the thread's
102
+ * `(project_id, thread_id, seq)` index: the count costs what is unread, not the thread's length.
103
+ */
104
+ async function readStates(
105
+ sql: PgStoreClient,
106
+ projectId: string,
107
+ principalId: string,
108
+ threadIds: readonly string[]
109
+ ): Promise<AgentThreadReadState[]> {
110
+ const rows = await sql<AgentThreadReadStateRow[]>`
111
+ SELECT
112
+ place.thread_id,
113
+ place.head_seq,
114
+ LEAST(COALESCE(place.through_seq, 0), place.head_seq) AS through_seq,
115
+ place.read_at,
116
+ (
117
+ SELECT COUNT(*) FROM agent_messages AS message
118
+ WHERE message.project_id = ${projectId}
119
+ AND message.thread_id = place.thread_id
120
+ AND message.seq > COALESCE(place.through_seq, 0)
121
+ AND (
122
+ message.role <> 'user'
123
+ OR message.author_principal_type IS DISTINCT FROM 'user'
124
+ OR message.author_principal_id IS DISTINCT FROM ${principalId}
125
+ )
126
+ AND NOT (
127
+ jsonb_array_length(message.parts) > 0 AND NOT EXISTS (
128
+ SELECT 1 FROM jsonb_array_elements(message.parts) AS part
129
+ WHERE part->>'type' <> 'approval-outcome'
130
+ )
131
+ )
132
+ ) AS unread
133
+ FROM (
134
+ SELECT
135
+ thread.id AS thread_id,
136
+ (
137
+ SELECT COALESCE(MAX(seq), 0) FROM agent_messages
138
+ WHERE project_id = thread.project_id AND thread_id = thread.id
139
+ ) AS head_seq,
140
+ reading.through_seq,
141
+ reading.read_at
142
+ FROM agent_threads AS thread
143
+ LEFT JOIN agent_thread_reads AS reading
144
+ ON reading.project_id = thread.project_id
145
+ AND reading.thread_id = thread.id
146
+ AND reading.principal_type = 'user'
147
+ AND reading.principal_id = ${principalId}
148
+ WHERE thread.project_id = ${projectId}
149
+ AND thread.id = ANY(${sql.array([...threadIds])}::text[])
150
+ ) AS place
151
+ `
152
+
153
+ return rows.map((row) => ({
154
+ threadId: row.thread_id,
155
+ throughSeq: Number(row.through_seq),
156
+ headSeq: Number(row.head_seq),
157
+ unread: Number(row.unread),
158
+ ...(row.read_at === null ? {} : { readAt: new Date(row.read_at) }),
159
+ }))
160
+ }