@sixb/pg 0.2.5 → 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 (40) hide show
  1. package/dist/agents/agent-storage.d.ts +2 -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.map +1 -1
  8. package/dist/agents/messages.d.ts +2 -1
  9. package/dist/agents/messages.d.ts.map +1 -1
  10. package/dist/agents/reads.d.ts +9 -0
  11. package/dist/agents/reads.d.ts.map +1 -0
  12. package/dist/agents/runs.d.ts +2 -1
  13. package/dist/agents/runs.d.ts.map +1 -1
  14. package/dist/agents/threads.d.ts.map +1 -1
  15. package/dist/index.js +560 -67
  16. package/dist/index.js.map +16 -15
  17. package/dist/latest-run-query.d.ts +3 -1
  18. package/dist/latest-run-query.d.ts.map +1 -1
  19. package/dist/migrations.d.ts.map +1 -1
  20. package/dist/pg-ai-cost-storage.d.ts.map +1 -1
  21. package/dist/pg-artifact-storage.d.ts.map +1 -1
  22. package/dist/pg-sync-run-storage.d.ts +2 -1
  23. package/dist/pg-sync-run-storage.d.ts.map +1 -1
  24. package/package.json +3 -3
  25. package/src/agents/agent-storage.ts +3 -0
  26. package/src/agents/approvals.ts +44 -0
  27. package/src/agents/checkpoints.ts +26 -0
  28. package/src/agents/inbox.ts +4 -1
  29. package/src/agents/messages.ts +81 -2
  30. package/src/agents/reads.ts +160 -0
  31. package/src/agents/runs.ts +25 -0
  32. package/src/agents/threads.ts +94 -10
  33. package/src/latest-run-query.ts +8 -1
  34. package/src/migrations/107-agent-inbox-edits.sql +3 -0
  35. package/src/migrations/108-agent-thread-reads.sql +73 -0
  36. package/src/migrations/109-sync-run-connections.sql +6 -0
  37. package/src/migrations.ts +6 -0
  38. package/src/pg-ai-cost-storage.ts +35 -20
  39. package/src/pg-artifact-storage.ts +21 -6
  40. package/src/pg-sync-run-storage.ts +69 -0
@@ -1,4 +1,4 @@
1
- import type { SQLClient } from "./pg-client";
1
+ import type { SQLClient, SqlParameter } from "./pg-client";
2
2
  type PgLatestRunTarget = {
3
3
  readonly tableName: "pipeline_runs";
4
4
  readonly ownerColumn: "pipeline_id";
@@ -21,6 +21,8 @@ export declare function queryLatestRunsByOwnerId<TRow>(input: {
21
21
  readonly selectList?: PgLatestRunSelectList;
22
22
  /** A status that never counts as the latest run, such as a run made stale by a newer one. */
23
23
  readonly excludedStatus?: string;
24
+ /** One more condition a row must meet to count. `bind` adds a parameter, named as it returns. */
25
+ readonly filter?: (bind: (value: SqlParameter) => string) => string;
24
26
  } & PgLatestRunTarget): Promise<readonly TRow[]>;
25
27
  export {};
26
28
  //# sourceMappingURL=latest-run-query.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"latest-run-query.d.ts","sourceRoot":"","sources":["../src/latest-run-query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAgB,MAAM,aAAa,CAAA;AAE1D,KAAK,iBAAiB,GAClB;IAAE,QAAQ,CAAC,SAAS,EAAE,eAAe,CAAC;IAAC,QAAQ,CAAC,WAAW,EAAE,aAAa,CAAA;CAAE,GAC5E;IAAE,QAAQ,CAAC,SAAS,EAAE,iBAAiB,CAAC;IAAC,QAAQ,CAAC,WAAW,EAAE,eAAe,CAAA;CAAE,GAChF;IAAE,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC;IAAC,QAAQ,CAAC,WAAW,EAAE,SAAS,CAAA;CAAE,GACpE;IAAE,QAAQ,CAAC,SAAS,EAAE,eAAe,CAAC;IAAC,QAAQ,CAAC,WAAW,EAAE,aAAa,CAAA;CAAE,CAAA;AAEhF,KAAK,qBAAqB,GAAG,GAAG,GAAG,iDAAiD,CAAA;AAEpF,wBAAsB,wBAAwB,CAAC,IAAI,E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C;IAYlC,gBAAgB,CAAC,KAAK,EAAE,6BAA6B,GAAG,OAAO,CAAC,IAAI,CAAC;IAkBrE,MAAM,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;IAQrE,MAAM,CAAC,KAAK,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;IAgB/C,eAAe,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ1D,aAAa,CAAC,KAAK,EAAE,0BAA0B,GAAG,OAAO,CAAC,qBAAqB,CAAC;IAiDhF,UAAU,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC;IAS5E,YAAY,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,qBAAqB,EAAE,CAAC;IASvE,cAAc,CAAC,KAAK,EAAE,2BAA2B,GAAG,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC;IAazF,aAAa,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,OAAO,CAAC;IAW1D,MAAM,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,OAAO,CAAC;CAS3D"}
@@ -1,4 +1,4 @@
1
- import type { ClaimRunInput, ConfirmRunExecutionInput, ExecutionStorage, FinishSyncRunInput, ListLatestSyncRunsInput, ListLatestSyncRunsResult, ListLostRunsInput, ListSyncRunsInput, ListSyncRunsResult, PrepareSyncRunCommitInput, QueueSyncRunInput, ReleaseRunExecutionInput, RunClaim, SyncRunRecord, SyncRunStorage } from "@sixb/core/storage";
1
+ import type { ClaimRunInput, ConfirmRunExecutionInput, ExecutionStorage, FinishSyncRunInput, ListLatestSyncConnectionRunsInput, ListLatestSyncRunsInput, ListLatestSyncRunsResult, ListLostRunsInput, ListSyncRunsInput, ListSyncRunsResult, PrepareSyncRunCommitInput, QueueSyncRunInput, ReleaseRunExecutionInput, RunClaim, SyncRunRecord, SyncRunStorage } from "@sixb/core/storage";
2
2
  import { type PgStoreClient } from "./transactions";
3
3
  export declare class PgSyncRunStorage implements SyncRunStorage {
4
4
  private readonly sql;
@@ -18,5 +18,6 @@ export declare class PgSyncRunStorage implements SyncRunStorage {
18
18
  }): Promise<SyncRunRecord | null>;
19
19
  list(input: ListSyncRunsInput): Promise<ListSyncRunsResult>;
20
20
  listLatestBySyncIds(input: ListLatestSyncRunsInput): Promise<ListLatestSyncRunsResult>;
21
+ listLatestByConnection(input: ListLatestSyncConnectionRunsInput): Promise<ListLatestSyncRunsResult>;
21
22
  }
22
23
  //# sourceMappingURL=pg-sync-run-storage.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"pg-sync-run-storage.d.ts","sourceRoot":"","sources":["../src/pg-sync-run-storage.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,aAAa,EACb,wBAAwB,EACxB,gBAAgB,EAChB,kBAAkB,EAClB,uBAAuB,EACvB,wBAAwB,EACxB,iBAAiB,EACjB,iBAAiB,EACjB,kBAAkB,EAClB,yBAAyB,EACzB,iBAAiB,EACjB,wBAAwB,EACxB,QAAQ,EACR,aAAa,EACb,cAAc,EACf,MAAM,oBAAoB,CAAA;AAiB3B,OAAO,EAAoB,KAAK,aAAa,EAAoB,MAAM,gBAAgB,CAAA;AAWvF,qBAAa,gBAAiB,YAAW,cAAc;IAEnD,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,OAAO,CAAC,QAAQ,CAAC,UAAU;gBADV,GAAG,EAAE,aAAa,EAClB,UAAU,EAAE,gBAAgB;IAGzC,KAAK,CAAC,KAAK,EAAE,iBAAiB,GAAG,OAAO,CAAC,aAAa,CAAC;YAgD/C,0BAA0B;IA2BlC,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;IAiBtE,yBAAyB,CAAC,KAAK,EAAE,wBAAwB,GAAG,OAAO,CAAC,aAAa,CAAC;IAIlF,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C,0BAA0B;IA2BlC,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;IAiBtE,yBAAyB,CAAC,KAAK,EAAE,wBAAwB,GAAG,OAAO,CAAC,aAAa,CAAC;IAIlF,QAAQ,CAAC,KAAK,EAAE,iBAAiB,GAAG,OAAO,CAAC,SAAS,aAAa,EAAE,CAAC;IAIrE,gBAAgB,CAAC,KAAK,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;IAIhE,aAAa,CAAC,KAAK,EAAE,yBAAyB,GAAG,OAAO,CAAC,aAAa,CAAC;IAgBvE,MAAM,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,aAAa,CAAC;IA4DzD,OAAO,CAAC,MAAM,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;IASjF,IAAI,CAAC,KAAK,EAAE,iBAAiB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAwE3D,mBAAmB,CAAC,KAAK,EAAE,uBAAuB,GAAG,OAAO,CAAC,wBAAwB,CAAC;IAoBtF,sBAAsB,CAC1B,KAAK,EAAE,iCAAiC,GACvC,OAAO,CAAC,wBAAwB,CAAC;CA8BrC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sixb/pg",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "PostgreSQL storage provider for Sixb",
5
5
  "keywords": [
6
6
  "sixb",
@@ -40,10 +40,10 @@
40
40
  "postgres": "^3.4.5"
41
41
  },
42
42
  "peerDependencies": {
43
- "@sixb/core": "0.2.5"
43
+ "@sixb/core": "0.2.6"
44
44
  },
45
45
  "devDependencies": {
46
- "@sixb/core": "0.2.5",
46
+ "@sixb/core": "0.2.6",
47
47
  "@types/bun": "latest",
48
48
  "typescript": "^5.7.0"
49
49
  },
@@ -6,6 +6,7 @@ import { PgAgentComputerSessionStore } from "./computers"
6
6
  import { PgAgentInboxStore } from "./inbox"
7
7
  import { PgAgentMemoryStore } from "./memory"
8
8
  import { PgAgentMessageStore } from "./messages"
9
+ import { PgAgentThreadReadStore } from "./reads"
9
10
  import { PgAgentRunStore } from "./runs"
10
11
  import { PgAgentApprovalModeStore } from "./settings"
11
12
  import { PgAgentThreadStore } from "./threads"
@@ -24,6 +25,7 @@ export interface PgAgentStorageOptions {
24
25
  */
25
26
  export class PgAgentStorage implements AgentStorage {
26
27
  readonly threads: PgAgentThreadStore
28
+ readonly reads: PgAgentThreadReadStore
27
29
  readonly runs: PgAgentRunStore
28
30
  readonly messages: PgAgentMessageStore
29
31
  readonly checkpoints: PgAgentContextCheckpointStore
@@ -36,6 +38,7 @@ export class PgAgentStorage implements AgentStorage {
36
38
 
37
39
  constructor(options: PgAgentStorageOptions) {
38
40
  this.threads = new PgAgentThreadStore(options.sql)
41
+ this.reads = new PgAgentThreadReadStore(options.sql)
39
42
  this.runs = new PgAgentRunStore(options.sql, options.executions)
40
43
  this.messages = new PgAgentMessageStore(options.sql)
41
44
  this.checkpoints = new PgAgentContextCheckpointStore(options.sql)
@@ -20,6 +20,8 @@ import {
20
20
  type MarkAgentApprovalsReportedInput,
21
21
  type RequestAgentApprovalInput,
22
22
  type RequestAgentApprovalResult,
23
+ type RewindAgentApprovalsInput,
24
+ type RewindAgentApprovalsResult,
23
25
  type SettleAgentApprovalsInput,
24
26
  type StopAgentApprovalsInput,
25
27
  type StopAgentApprovalsResult,
@@ -187,6 +189,48 @@ export class PgAgentApprovalStore implements AgentApprovalStore {
187
189
  return { cancelled: cancelled.sort(compareApprovals), stopped }
188
190
  }
189
191
 
192
+ async rewind(input: RewindAgentApprovalsInput): Promise<RewindAgentApprovalsResult> {
193
+ const runIds = [...new Set(input.runIds)]
194
+ const clearedIds = [...new Set(input.clearedMessageIds ?? [])]
195
+ const cancelledAt = new Date(input.cancelledAt ?? new Date())
196
+
197
+ return runPgTransaction(this.sql, async (tx) => {
198
+ if (clearedIds.length > 0) {
199
+ await tx`
200
+ UPDATE agent_approvals
201
+ SET reported_in_message_id = NULL
202
+ WHERE project_id = ${input.projectId}
203
+ AND thread_id = ${input.threadId}
204
+ AND reported_in_message_id = ANY(${tx.array(clearedIds)}::text[])
205
+ `
206
+ }
207
+
208
+ if (runIds.length === 0) return { cancelled: [], deleted: 0 }
209
+
210
+ const removed = await tx<AgentApprovalRow[]>`
211
+ DELETE FROM agent_approvals
212
+ WHERE project_id = ${input.projectId}
213
+ AND thread_id = ${input.threadId}
214
+ AND run_id = ANY(${tx.array(runIds)}::text[])
215
+ RETURNING *
216
+ `
217
+
218
+ const cancelled = removed
219
+ .filter((row) => row.status === "pending")
220
+ .map((row): AgentApprovalRecord => {
221
+ const parsed = rowToApproval(row)
222
+ return {
223
+ ...parsed,
224
+ status: "cancelled",
225
+ turnStoppedAt: parsed.turnStoppedAt ?? cancelledAt,
226
+ }
227
+ })
228
+ .sort(compareApprovals)
229
+
230
+ return { cancelled, deleted: removed.length }
231
+ })
232
+ }
233
+
190
234
  async holdsRun(input: { readonly projectId: string; readonly runId: string }): Promise<boolean> {
191
235
  return pgHoldsRun(this.sql, input.projectId, input.runId)
192
236
  }
@@ -4,12 +4,14 @@ import {
4
4
  assertAgentContextCheckpointAuthority,
5
5
  assertAgentContextCheckpointReplayState,
6
6
  assertCreateAgentContextCheckpointInput,
7
+ assertDeleteAgentContextCheckpointsAfterSeqInput,
7
8
  } from "@sixb/core/internal/agent-run-storage-provider"
8
9
  import {
9
10
  type AgentContextCheckpointRecord,
10
11
  type AgentContextCheckpointStore,
11
12
  AgentStorageError,
12
13
  type CreateAgentContextCheckpointInput,
14
+ type DeleteAgentContextCheckpointsAfterSeqInput,
13
15
  } from "@sixb/core/storage"
14
16
  import { isUniqueViolation } from "../storage-errors"
15
17
  import { type PgStoreClient, runPgTransaction } from "../transactions"
@@ -178,6 +180,30 @@ export class PgAgentContextCheckpointStore implements AgentContextCheckpointStor
178
180
  return row ? rowToContextCheckpointRecord(row) : null
179
181
  }
180
182
 
183
+ async deleteAfterSeq(input: DeleteAgentContextCheckpointsAfterSeqInput): Promise<number> {
184
+ assertDeleteAgentContextCheckpointsAfterSeqInput(input, "SixbPg")
185
+
186
+ return runPgTransaction(this.sql, async (tx) => {
187
+ const rows = await tx<{ id: string }[]>`
188
+ SELECT id FROM agent_context_checkpoints
189
+ WHERE project_id = ${input.projectId}
190
+ AND thread_id = ${input.threadId}
191
+ AND observed_head_seq > ${input.afterSeq}
192
+ ORDER BY summarized_through_seq DESC, created_at DESC, id DESC
193
+ FOR UPDATE
194
+ `
195
+ if (rows.length === 0) return 0
196
+
197
+ for (const row of rows) {
198
+ await tx`
199
+ DELETE FROM agent_context_checkpoints
200
+ WHERE project_id = ${input.projectId} AND id = ${row.id}
201
+ `
202
+ }
203
+ return rows.length
204
+ })
205
+ }
206
+
181
207
  async getByRunIds(input: {
182
208
  readonly projectId: string
183
209
  readonly threadId: string
@@ -44,6 +44,7 @@ interface AgentInboxRow {
44
44
  readonly time_zone: string | null
45
45
  readonly locale: string | null
46
46
  readonly immediate: boolean
47
+ readonly replaces_message_id: string | null
47
48
  readonly execution_id: string | null
48
49
  readonly claimed_by_run_id: string | null
49
50
  readonly claimed_by_token: string | null
@@ -117,7 +118,7 @@ export class PgAgentInboxStore implements AgentInboxStore {
117
118
  INSERT INTO agent_thread_inbox (
118
119
  project_id, id, thread_id, message_id, seq,
119
120
  author_principal_type, author_principal_id, mode, parts, spec,
120
- time_zone, locale, immediate, execution_id, created_at, updated_at
121
+ time_zone, locale, immediate, replaces_message_id, execution_id, created_at, updated_at
121
122
  ) VALUES (
122
123
  ${record.projectId},
123
124
  ${record.id},
@@ -132,6 +133,7 @@ export class PgAgentInboxStore implements AgentInboxStore {
132
133
  ${record.timeZone ?? null},
133
134
  ${record.locale ?? null},
134
135
  ${Boolean(record.immediate)},
136
+ ${record.replacesMessageId ?? null},
135
137
  ${record.executionId ?? null},
136
138
  ${record.createdAt},
137
139
  ${record.updatedAt}
@@ -410,6 +412,7 @@ function rowToInboxItem(row: AgentInboxRow): AgentInboxItemRecord {
410
412
  ...(row.time_zone ? { timeZone: row.time_zone } : {}),
411
413
  ...(row.locale ? { locale: row.locale } : {}),
412
414
  ...(row.immediate ? { immediate: true } : {}),
415
+ ...(row.replaces_message_id ? { replacesMessageId: row.replaces_message_id } : {}),
413
416
  ...(row.execution_id ? { executionId: row.execution_id } : {}),
414
417
  ...(claimedBy ? { claimedBy } : {}),
415
418
  createdAt: new Date(row.created_at),
@@ -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
+ }
@@ -28,6 +28,7 @@ import {
28
28
  type FinishQueuedAgentRunInput,
29
29
  type ListAgentRunsInput,
30
30
  type ListAgentRunsResult,
31
+ type ListLatestAgentRunsInput,
31
32
  type ListThreadSubagentsInput,
32
33
  type ReclaimAgentRunInput,
33
34
  type RequestAgentRunCancelInput,
@@ -472,6 +473,16 @@ export class PgAgentRunStore implements AgentRunStore {
472
473
  AND child.kind = 'subagent'
473
474
  ${input.spawnKey === undefined ? this.sql`` : this.sql`AND child.spawn_key = ${input.spawnKey}`}
474
475
  ${input.finishReason === undefined ? this.sql`` : this.sql`AND child.finish_reason = ${input.finishReason}`}
476
+ ${
477
+ input.retainedTurnsOnly
478
+ ? this.sql`AND EXISTS (
479
+ SELECT 1 FROM agent_messages m
480
+ WHERE m.project_id = turn.project_id
481
+ AND m.thread_id = turn.thread_id
482
+ AND m.id = turn.trigger_message_id
483
+ )`
484
+ : this.sql``
485
+ }
475
486
  ORDER BY COALESCE(turn.started_at, turn.created_at) DESC, turn.id DESC,
476
487
  child.created_at DESC, child.id DESC
477
488
  LIMIT ${input.limit ?? 100}
@@ -482,6 +493,20 @@ export class PgAgentRunStore implements AgentRunStore {
482
493
  })
483
494
  }
484
495
 
496
+ async latestByThread(input: ListLatestAgentRunsInput): Promise<readonly AgentRunRecord[]> {
497
+ if (input.threadIds.length === 0) return []
498
+
499
+ const rows = await this.sql<AgentRunRow[]>`
500
+ SELECT DISTINCT ON (thread_id) *
501
+ FROM agent_runs
502
+ WHERE project_id = ${input.projectId}
503
+ AND thread_id = ANY(${this.sql.array([...input.threadIds])}::text[])
504
+ ORDER BY thread_id, created_at DESC, id DESC
505
+ `
506
+
507
+ return rows.map(rowToRunRecord)
508
+ }
509
+
485
510
  async list(input: ListAgentRunsInput): Promise<ListAgentRunsResult> {
486
511
  if (hasEmptyStatuses(input) || input.kinds?.length === 0) {
487
512
  return { runs: [], hasMore: false, total: 0 }