@sixb/pg 0.1.25 → 0.2.0

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 (84) hide show
  1. package/README.md +25 -1
  2. package/dist/agents/agent-storage.d.ts +8 -3
  3. package/dist/agents/agent-storage.d.ts.map +1 -1
  4. package/dist/agents/computers.d.ts +22 -0
  5. package/dist/agents/computers.d.ts.map +1 -0
  6. package/dist/agents/messages.d.ts.map +1 -1
  7. package/dist/agents/rows.d.ts +6 -0
  8. package/dist/agents/rows.d.ts.map +1 -1
  9. package/dist/agents/runs.d.ts +2 -1
  10. package/dist/agents/runs.d.ts.map +1 -1
  11. package/dist/agents/threads.d.ts +3 -1
  12. package/dist/agents/threads.d.ts.map +1 -1
  13. package/dist/agents/token-rates.d.ts +13 -0
  14. package/dist/agents/token-rates.d.ts.map +1 -0
  15. package/dist/ai-accounting-filters.d.ts +12 -0
  16. package/dist/ai-accounting-filters.d.ts.map +1 -0
  17. package/dist/ai-cost-groups.d.ts +1 -1
  18. package/dist/ai-cost-groups.d.ts.map +1 -1
  19. package/dist/index.d.ts +5 -4
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +1446 -588
  22. package/dist/index.js.map +30 -25
  23. package/dist/migrations.d.ts.map +1 -1
  24. package/dist/objects/index.d.ts +1 -0
  25. package/dist/objects/index.d.ts.map +1 -1
  26. package/dist/objects/partitions.d.ts +10 -0
  27. package/dist/objects/partitions.d.ts.map +1 -0
  28. package/dist/objects/prepare-queries.d.ts.map +1 -1
  29. package/dist/objects/query-compiler.d.ts +5 -0
  30. package/dist/objects/query-compiler.d.ts.map +1 -1
  31. package/dist/objects/query-indexes.d.ts +19 -1
  32. package/dist/objects/query-indexes.d.ts.map +1 -1
  33. package/dist/objects/reader.d.ts +3 -1
  34. package/dist/objects/reader.d.ts.map +1 -1
  35. package/dist/objects/sql-text.d.ts +3 -0
  36. package/dist/objects/sql-text.d.ts.map +1 -0
  37. package/dist/objects/storage.d.ts +3 -1
  38. package/dist/objects/storage.d.ts.map +1 -1
  39. package/dist/objects/text-count-index.d.ts.map +1 -1
  40. package/dist/ontology-storage/commits.d.ts.map +1 -1
  41. package/dist/ontology-storage/materialization-session.d.ts +7 -1
  42. package/dist/ontology-storage/materialization-session.d.ts.map +1 -1
  43. package/dist/ontology-storage/materialization-writer.d.ts +2 -0
  44. package/dist/ontology-storage/materialization-writer.d.ts.map +1 -1
  45. package/dist/ontology-storage/materializations.d.ts +2 -1
  46. package/dist/ontology-storage/materializations.d.ts.map +1 -1
  47. package/dist/pg-ai-cost-storage.d.ts.map +1 -1
  48. package/dist/pg-client.d.ts +1 -1
  49. package/dist/pg-client.d.ts.map +1 -1
  50. package/dist/storage-errors.d.ts +4 -1
  51. package/dist/storage-errors.d.ts.map +1 -1
  52. package/package.json +3 -3
  53. package/src/agents/agent-storage.ts +10 -3
  54. package/src/agents/computers.ts +95 -0
  55. package/src/agents/messages.ts +15 -0
  56. package/src/agents/rows.ts +14 -0
  57. package/src/agents/runs.ts +56 -4
  58. package/src/agents/threads.ts +123 -2
  59. package/src/agents/token-rates.ts +76 -0
  60. package/src/ai-accounting-filters.ts +48 -0
  61. package/src/ai-cost-groups.ts +37 -12
  62. package/src/index.ts +21 -8
  63. package/src/migrations/082-agent-run-cancel-requests.sql +3 -0
  64. package/src/migrations/083-agent-thread-runs-on.sql +4 -0
  65. package/src/migrations/084-agent-token-rates.sql +16 -0
  66. package/src/migrations/085-agent-computer-sessions.sql +27 -0
  67. package/src/migrations/086-partition-objects.sql +93 -0
  68. package/src/migrations.ts +14 -0
  69. package/src/objects/index.ts +1 -0
  70. package/src/objects/partitions.ts +163 -0
  71. package/src/objects/prepare-queries.ts +50 -2
  72. package/src/objects/query-compiler.ts +136 -96
  73. package/src/objects/query-indexes.ts +120 -63
  74. package/src/objects/reader.ts +5 -4
  75. package/src/objects/sql-text.ts +8 -0
  76. package/src/objects/storage.ts +14 -2
  77. package/src/objects/text-count-index.ts +17 -12
  78. package/src/ontology-storage/commits.ts +11 -2
  79. package/src/ontology-storage/materialization-session.ts +10 -1
  80. package/src/ontology-storage/materialization-writer.ts +14 -0
  81. package/src/ontology-storage/materializations.ts +81 -7
  82. package/src/pg-ai-cost-storage.ts +119 -15
  83. package/src/pg-client.ts +13 -6
  84. package/src/storage-errors.ts +28 -1
@@ -6,7 +6,9 @@ import {
6
6
  assertConversationAgentRunSpec,
7
7
  assertConversationThreadRow,
8
8
  assertCreateSubagentRunInput,
9
+ assertStartsOnComputer,
9
10
  assertSubagentThreadTakesRun,
11
+ assertTurnInThreadPlace,
10
12
  newSubagentThreadRecord,
11
13
  subagentRunMatchesCreateInput,
12
14
  } from "@sixb/core/internal/agent-run-storage-provider"
@@ -28,6 +30,7 @@ import {
28
30
  type ListAgentRunsResult,
29
31
  type ListThreadSubagentsInput,
30
32
  type ReclaimAgentRunInput,
33
+ type RequestAgentRunCancelInput,
31
34
  type StartAgentRunInput,
32
35
  type SubagentRunRecord,
33
36
  } from "@sixb/core/storage"
@@ -58,8 +61,10 @@ export class PgAgentRunStore implements AgentRunStore {
58
61
 
59
62
  try {
60
63
  return await runPgTransaction(this.sql, async (tx) => {
61
- const [thread] = await tx<Pick<AgentThreadRow, "id" | "kind" | "active_run_id">[]>`
62
- SELECT id, kind, active_run_id FROM agent_threads
64
+ const [thread] = await tx<
65
+ Pick<AgentThreadRow, "id" | "kind" | "active_run_id" | "runs_on">[]
66
+ >`
67
+ SELECT id, kind, active_run_id, runs_on FROM agent_threads
63
68
  WHERE project_id = ${input.projectId} AND id = ${input.threadId}
64
69
  FOR UPDATE
65
70
  `
@@ -77,6 +82,7 @@ export class PgAgentRunStore implements AgentRunStore {
77
82
  `[SixbPg] Agent thread '${input.threadId}' already has an active run '${thread.active_run_id}'.`
78
83
  )
79
84
  }
85
+ assertTurnInThreadPlace(thread.runs_on, input.spec, input.threadId, "SixbPg")
80
86
 
81
87
  const [row] = await tx<AgentRunRow[]>`
82
88
  INSERT INTO agent_runs (
@@ -246,7 +252,20 @@ export class PgAgentRunStore implements AgentRunStore {
246
252
  async start(input: StartAgentRunInput): Promise<AgentRunRecord> {
247
253
  const startedAt = input.startedAt ?? new Date()
248
254
  return runPgTransaction(this.sql, async (tx) => {
249
- await this.lockStatus(tx, input.projectId, input.id, "queued")
255
+ const run = await this.lockStatus(tx, input.projectId, input.id, "queued")
256
+ if (input.onComputer) {
257
+ // A move locks this run first, so it landed already or waits for this start.
258
+ const [thread] = await tx<{ id: string | null; folder: string }[]>`
259
+ SELECT computer_id AS id, computer_folder AS folder FROM agent_threads
260
+ WHERE project_id = ${input.projectId} AND id = ${run.thread_id}
261
+ `
262
+ assertStartsOnComputer(
263
+ rowToRunRecord(run),
264
+ thread?.id ? { id: thread.id, folder: thread.folder } : undefined,
265
+ input.onComputer,
266
+ "SixbPg"
267
+ )
268
+ }
250
269
  const [row] = await tx<AgentRunRow[]>`
251
270
  UPDATE agent_runs
252
271
  SET
@@ -283,7 +302,17 @@ export class PgAgentRunStore implements AgentRunStore {
283
302
 
284
303
  async reclaim(input: ReclaimAgentRunInput): Promise<AgentRunRecord> {
285
304
  return runPgTransaction(this.sql, async (tx) => {
286
- await this.lockRunning(tx, input.projectId, input.id)
305
+ const run = await this.lockRunning(tx, input.projectId, input.id)
306
+ if (
307
+ input.ifLapsedBy &&
308
+ run.execution_queue_lease_expires_at !== null &&
309
+ new Date(run.execution_queue_lease_expires_at).getTime() > input.ifLapsedBy.getTime()
310
+ ) {
311
+ throw new AgentStorageError(
312
+ "invalid_state",
313
+ `[SixbPg] Agent run '${input.id}' is still held by its runner, whose lease has not lapsed.`
314
+ )
315
+ }
287
316
  const [row] = await tx<AgentRunRow[]>`
288
317
  UPDATE agent_runs
289
318
  SET
@@ -323,6 +352,25 @@ export class PgAgentRunStore implements AgentRunStore {
323
352
  })
324
353
  }
325
354
 
355
+ async requestCancel(input: RequestAgentRunCancelInput): Promise<AgentRunRecord> {
356
+ const [updated] = await this.sql<AgentRunRow[]>`
357
+ UPDATE agent_runs
358
+ SET cancel_requested_at = ${input.at ?? new Date()}
359
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
360
+ AND status = 'running' AND cancel_requested_at IS NULL
361
+ RETURNING *
362
+ `
363
+ if (updated) return rowToRunRecord(updated)
364
+ const current = await this.getById(input)
365
+ if (!current) {
366
+ throw new AgentStorageError(
367
+ "run_not_found",
368
+ `[SixbPg] Agent run '${input.id}' not found for project '${input.projectId}'.`
369
+ )
370
+ }
371
+ return current
372
+ }
373
+
326
374
  async finish(input: FinishAgentRunInput): Promise<AgentRunRecord> {
327
375
  const completedAt = input.completedAt ?? new Date()
328
376
  const errorValue =
@@ -458,6 +506,10 @@ export class PgAgentRunStore implements AgentRunStore {
458
506
  params.push(input.parentRunId)
459
507
  }
460
508
 
509
+ if (input.excludeComputerTurns) {
510
+ whereClauses.push("spec->>'runsOn' IS DISTINCT FROM 'computer'")
511
+ }
512
+
461
513
  index = appendRunListFilters(
462
514
  whereClauses,
463
515
  params,
@@ -1,7 +1,13 @@
1
1
  import {
2
+ assertAgentThreadComputer,
3
+ assertAssignableComputer,
4
+ assertComputerPlace,
2
5
  assertConversationThreadRow,
6
+ assertMovableToCloud,
7
+ movesComputerPlace,
3
8
  participantsToAdd,
4
9
  planAgentThreadFork,
10
+ queuedTurnInCloud,
5
11
  remapArtifactIds,
6
12
  snapshotAgentThreadSandboxParams,
7
13
  transitionAgentThreadSandbox,
@@ -9,17 +15,21 @@ import {
9
15
  import {
10
16
  type AddAgentThreadParticipantsInput,
11
17
  type AgentContextCheckpointRecord,
18
+ type AgentRunRecord,
12
19
  AgentStorageError,
13
20
  type AgentThreadParticipantRecord,
14
21
  type AgentThreadRecord,
15
22
  type AgentThreadSandboxState,
16
23
  type AgentThreadStore,
24
+ type AssignAgentThreadComputerInput,
17
25
  type CreateAgentThreadInput,
18
26
  type ForkAgentThreadInput,
19
27
  type ListAgentThreadChildrenInput,
20
28
  type ListAgentThreadParticipantsInput,
21
29
  type ListAgentThreadsInput,
22
30
  type ListAgentThreadsResult,
31
+ type MoveAgentThreadToCloudInput,
32
+ type MoveAgentThreadToCloudResult,
23
33
  type RemoveAgentThreadParticipantInput,
24
34
  type TransitionAgentThreadSandboxInput,
25
35
  } from "@sixb/core/storage"
@@ -70,12 +80,22 @@ export class PgAgentThreadStore implements AgentThreadStore {
70
80
  }
71
81
 
72
82
  async create(input: CreateAgentThreadInput): Promise<AgentThreadRecord> {
83
+ assertComputerPlace(input.runsOn, input.computer, "SixbPg")
73
84
  const sandboxParams =
74
85
  input.sandboxParams === undefined
75
86
  ? null
76
87
  : JSON.stringify(snapshotAgentThreadSandboxParams(input.sandboxParams))
77
88
  const createdAt = input.createdAt ?? new Date()
78
89
  const updatedAt = input.updatedAt ?? createdAt
90
+ // A cloud thread leaves the column to its default, as it did before the column existed.
91
+ const runsOn =
92
+ input.runsOn === undefined
93
+ ? { column: this.sql``, value: this.sql`` }
94
+ : {
95
+ column: this.sql`runs_on, computer_id, computer_name, computer_folder,`,
96
+ value: this
97
+ .sql`${input.runsOn}, ${input.computer?.id ?? null}, ${input.computer?.name ?? null}, ${input.computer?.folder ?? null},`,
98
+ }
79
99
 
80
100
  try {
81
101
  const [row] = await this.sql<AgentThreadRow[]>`
@@ -86,6 +106,7 @@ export class PgAgentThreadStore implements AgentThreadStore {
86
106
  owner_principal_id,
87
107
  title,
88
108
  sandbox_params,
109
+ ${runsOn.column}
89
110
  status,
90
111
  created_at,
91
112
  updated_at
@@ -96,6 +117,7 @@ export class PgAgentThreadStore implements AgentThreadStore {
96
117
  ${input.ownerPrincipal.id},
97
118
  ${input.title ?? null},
98
119
  ${sandboxParams}::text::jsonb,
120
+ ${runsOn.value}
99
121
  ${input.status ?? "active"},
100
122
  ${createdAt},
101
123
  ${updatedAt}
@@ -121,8 +143,10 @@ export class PgAgentThreadStore implements AgentThreadStore {
121
143
  return await runPgTransaction(this.sql, async (tx) => {
122
144
  // A share lock holds back the writes that take the thread for update: an admitted request
123
145
  // or a finalized answer lands before the copy or after it, never inside it.
124
- const [source] = await tx<Pick<AgentThreadRow, "id" | "kind" | "active_run_id">[]>`
125
- SELECT id, kind, active_run_id FROM agent_threads
146
+ const [source] = await tx<
147
+ Pick<AgentThreadRow, "id" | "kind" | "active_run_id" | "runs_on" | "moved_at">[]
148
+ >`
149
+ SELECT id, kind, active_run_id, runs_on, moved_at FROM agent_threads
126
150
  WHERE project_id = ${input.projectId} AND id = ${input.sourceThreadId}
127
151
  FOR SHARE
128
152
  `
@@ -166,6 +190,7 @@ export class PgAgentThreadStore implements AgentThreadStore {
166
190
  const plan = planAgentThreadFork(
167
191
  input,
168
192
  {
193
+ workspace: { runsOn: source.runs_on, movedAt: source.moved_at },
169
194
  ...(activeRun?.trigger_message_id
170
195
  ? { triggerMessageId: activeRun.trigger_message_id }
171
196
  : {}),
@@ -192,6 +217,7 @@ export class PgAgentThreadStore implements AgentThreadStore {
192
217
  status,
193
218
  last_message_at,
194
219
  message_count,
220
+ moved_at,
195
221
  created_at,
196
222
  updated_at
197
223
  ) VALUES (
@@ -205,6 +231,7 @@ export class PgAgentThreadStore implements AgentThreadStore {
205
231
  ${thread.status},
206
232
  ${thread.lastMessageAt ?? null},
207
233
  ${thread.messageCount},
234
+ ${thread.movedAt ?? null},
208
235
  ${thread.createdAt},
209
236
  ${thread.updatedAt}
210
237
  )
@@ -354,6 +381,13 @@ export class PgAgentThreadStore implements AgentThreadStore {
354
381
  params.push(input.participantPrincipal.type, input.participantPrincipal.id)
355
382
  }
356
383
 
384
+ if (input.activeOnComputer) {
385
+ whereClauses.push(
386
+ `computer_id = $${index++} AND computer_folder = $${index++} AND active_run_id IS NOT NULL`
387
+ )
388
+ params.push(input.activeOnComputer.id, input.activeOnComputer.folder)
389
+ }
390
+
357
391
  const dir = input.order === "asc" ? "ASC" : "DESC"
358
392
  const { rows, total, hasMore } = await queryAgentList<AgentThreadRow>({
359
393
  sql: this.sql,
@@ -432,6 +466,53 @@ export class PgAgentThreadStore implements AgentThreadStore {
432
466
  return rows.length > 0
433
467
  }
434
468
 
469
+ async assignComputer(input: AssignAgentThreadComputerInput): Promise<AgentThreadRecord> {
470
+ assertAgentThreadComputer(input.computer, "SixbPg")
471
+ return runPgTransaction(this.sql, async (tx) => {
472
+ const { thread, active } = await lockThreadAndActiveRun(tx, input)
473
+ assertAssignableComputer(thread, active, input.computer, input.id, "SixbPg")
474
+ const movedAt = movesComputerPlace(thread, input.computer)
475
+ ? (input.movedAt ?? new Date())
476
+ : null
477
+ const [assigned] = await tx<AgentThreadRow[]>`
478
+ UPDATE agent_threads
479
+ SET computer_id = ${input.computer.id},
480
+ computer_name = ${input.computer.name},
481
+ computer_folder = ${input.computer.folder},
482
+ moved_at = COALESCE(${movedAt}::timestamptz, moved_at)
483
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
484
+ RETURNING *
485
+ `
486
+ return rowToThreadRecord(assigned as AgentThreadRow)
487
+ })
488
+ }
489
+
490
+ async moveToCloud(input: MoveAgentThreadToCloudInput): Promise<MoveAgentThreadToCloudResult> {
491
+ return runPgTransaction(this.sql, async (tx) => {
492
+ const { thread, active } = await lockThreadAndActiveRun(tx, input)
493
+ assertMovableToCloud(thread, active, input.id, "SixbPg")
494
+
495
+ const queued = queuedTurnInCloud(active)
496
+ if (queued) {
497
+ await tx`
498
+ UPDATE agent_runs SET spec = ${JSON.stringify(queued.spec)}::text::jsonb
499
+ WHERE project_id = ${input.projectId} AND id = ${queued.id}
500
+ `
501
+ }
502
+ const [movedThread] = await tx<AgentThreadRow[]>`
503
+ UPDATE agent_threads
504
+ SET runs_on = NULL, computer_id = NULL, computer_name = NULL, computer_folder = NULL,
505
+ moved_at = ${input.movedAt ?? new Date()}
506
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
507
+ RETURNING *
508
+ `
509
+ return {
510
+ thread: rowToThreadRecord(movedThread as AgentThreadRow),
511
+ ...(queued ? { queued } : {}),
512
+ }
513
+ })
514
+ }
515
+
435
516
  async listParticipants(
436
517
  input: ListAgentThreadParticipantsInput
437
518
  ): Promise<readonly AgentThreadParticipantRecord[]> {
@@ -439,6 +520,46 @@ export class PgAgentThreadStore implements AgentThreadStore {
439
520
  }
440
521
  }
441
522
 
523
+ /**
524
+ * Lock a thread that is about to move, with its active turn. Same lock order as run finalization:
525
+ * run, then thread. The thread names the run to lock, so it is read again once both are held, in
526
+ * case its turn changed in between.
527
+ */
528
+ async function lockThreadAndActiveRun(
529
+ tx: PgStoreClient,
530
+ input: { readonly projectId: string; readonly id: string }
531
+ ): Promise<{ readonly thread: AgentThreadRecord | null; readonly active: AgentRunRecord | null }> {
532
+ for (let attempt = 0; ; attempt += 1) {
533
+ const [peek] = await tx<Pick<AgentThreadRow, "active_run_id">[]>`
534
+ SELECT active_run_id FROM agent_threads
535
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
536
+ `
537
+ const runId = peek?.active_run_id ?? null
538
+ const runs = runId
539
+ ? await tx<AgentRunRow[]>`
540
+ SELECT * FROM agent_runs WHERE project_id = ${input.projectId} AND id = ${runId}
541
+ FOR UPDATE
542
+ `
543
+ : []
544
+ const [row] = await tx<AgentThreadRow[]>`
545
+ SELECT * FROM agent_threads WHERE project_id = ${input.projectId} AND id = ${input.id}
546
+ FOR UPDATE
547
+ `
548
+ if ((row?.active_run_id ?? null) === runId) {
549
+ return {
550
+ thread: row ? rowToThreadRecord(row) : null,
551
+ active: runs[0] ? rowToRunRecord(runs[0]) : null,
552
+ }
553
+ }
554
+ if (attempt >= 3) {
555
+ throw new AgentStorageError(
556
+ "invalid_state",
557
+ `[SixbPg] Agent thread '${input.id}' kept changing turns while it moved: try again.`
558
+ )
559
+ }
560
+ }
561
+ }
562
+
442
563
  async function selectParticipants(
443
564
  sql: PgStoreClient,
444
565
  projectId: string,
@@ -0,0 +1,76 @@
1
+ import {
2
+ AGENT_TOKEN_RATE_SAMPLES,
3
+ assertAgentTokenRateRecord,
4
+ } from "@sixb/core/internal/agent-run-storage-provider"
5
+ import type { AgentTokenRateRecord, AgentTokenRateStore } from "@sixb/core/storage"
6
+ import { type PgStoreClient, runPgTransaction } from "../transactions"
7
+
8
+ interface TokenRateRow {
9
+ readonly project_id: string
10
+ readonly run_id: string
11
+ readonly provider_id: string
12
+ readonly model_id: string
13
+ readonly bytes: number
14
+ readonly tokens: number
15
+ readonly measured_at: Date
16
+ }
17
+
18
+ export class PgAgentTokenRateStore implements AgentTokenRateStore {
19
+ constructor(private readonly sql: PgStoreClient) {}
20
+
21
+ async record(input: AgentTokenRateRecord): Promise<void> {
22
+ assertAgentTokenRateRecord(input, "SixbPg")
23
+
24
+ await runPgTransaction(this.sql, async (tx) => {
25
+ await tx`
26
+ INSERT INTO agent_token_rates (
27
+ project_id, run_id, provider_id, model_id, bytes, tokens, measured_at
28
+ ) VALUES (
29
+ ${input.projectId}, ${input.runId}, ${input.providerId}, ${input.modelId},
30
+ ${input.bytes}, ${input.tokens}, ${input.measuredAt}
31
+ )
32
+ ON CONFLICT (project_id, run_id) DO UPDATE SET
33
+ provider_id = EXCLUDED.provider_id, model_id = EXCLUDED.model_id,
34
+ bytes = EXCLUDED.bytes, tokens = EXCLUDED.tokens, measured_at = EXCLUDED.measured_at
35
+ `
36
+
37
+ // A statement of its own: one sharing the insert's snapshot would not see the new row.
38
+ await tx`
39
+ DELETE FROM agent_token_rates
40
+ WHERE project_id = ${input.projectId} AND provider_id = ${input.providerId}
41
+ AND model_id = ${input.modelId}
42
+ AND run_id NOT IN (
43
+ SELECT run_id FROM agent_token_rates
44
+ WHERE project_id = ${input.projectId} AND provider_id = ${input.providerId}
45
+ AND model_id = ${input.modelId}
46
+ ORDER BY measured_at DESC, run_id DESC
47
+ LIMIT ${AGENT_TOKEN_RATE_SAMPLES}
48
+ )
49
+ `
50
+ })
51
+ }
52
+
53
+ async listLatest(input: {
54
+ readonly projectId: string
55
+ readonly providerId: string
56
+ readonly modelId: string
57
+ }): Promise<readonly AgentTokenRateRecord[]> {
58
+ const rows = await this.sql<TokenRateRow[]>`
59
+ SELECT project_id, run_id, provider_id, model_id, bytes, tokens, measured_at
60
+ FROM agent_token_rates
61
+ WHERE project_id = ${input.projectId} AND provider_id = ${input.providerId}
62
+ AND model_id = ${input.modelId}
63
+ ORDER BY measured_at DESC, run_id DESC
64
+ LIMIT ${AGENT_TOKEN_RATE_SAMPLES}
65
+ `
66
+ return rows.map((row) => ({
67
+ projectId: row.project_id,
68
+ providerId: row.provider_id,
69
+ modelId: row.model_id,
70
+ runId: row.run_id,
71
+ bytes: row.bytes,
72
+ tokens: row.tokens,
73
+ measuredAt: row.measured_at,
74
+ }))
75
+ }
76
+ }
@@ -0,0 +1,48 @@
1
+ import type { normalizeAiAccountingQuery } from "@sixb/core/internal/ai-cost-storage-provider"
2
+
3
+ // The kind, source and requester filters every accounting read shares, over the joins it makes:
4
+ // `usage`, `execution`, `direct_agent`, `workflow_node`.
5
+
6
+ /** The filter's values, each `null` when the query leaves that part open. */
7
+ export function pgAccountingFilterValues(query: ReturnType<typeof normalizeAiAccountingQuery>): {
8
+ readonly kind: string | null
9
+ readonly source: string | null
10
+ readonly workflow: string | null
11
+ readonly mode: string | null
12
+ readonly id: string | null
13
+ } {
14
+ return {
15
+ kind: query.modelKind ?? null,
16
+ source: query.source?.kind ?? null,
17
+ workflow: query.source?.kind === "workflow" ? (query.source.workflowId ?? null) : null,
18
+ mode:
19
+ query.requester === undefined
20
+ ? null
21
+ : query.requester === "none"
22
+ ? "none"
23
+ : query.requester.type,
24
+ id: query.requester === undefined || query.requester === "none" ? null : query.requester.id,
25
+ }
26
+ }
27
+
28
+ /** The filter as SQL text over numbered `$n` parameters from `start`, for `sql.unsafe`. */
29
+ export function pgAccountingFilterSql(start: number): string {
30
+ const [kind, source, workflow, mode, id] = [0, 1, 2, 3, 4].map((offset) => `$${start + offset}`)
31
+ const sourceWorkflow = `COALESCE(workflow_node.workflow_id,
32
+ CASE WHEN execution.executor_kind = 'workflow' THEN execution.authority_primitive_id END)`
33
+ return `(${kind}::text IS NULL OR usage.model_kind = ${kind})
34
+ AND (${source}::text IS NULL OR (CASE
35
+ WHEN direct_agent.id IS NOT NULL THEN 'agent'
36
+ WHEN ${sourceWorkflow} IS NOT NULL THEN 'workflow'
37
+ WHEN execution.executor_kind = 'action' THEN 'action'
38
+ ELSE 'other'
39
+ END) = ${source})
40
+ AND (${workflow}::text IS NULL OR ${sourceWorkflow} = ${workflow})
41
+ AND (
42
+ ${mode}::text IS NULL
43
+ OR (${mode} = 'none' AND execution.requested_by_user_id IS NULL
44
+ AND execution.requested_by_service_account_id IS NULL)
45
+ OR (${mode} = 'user' AND execution.requested_by_user_id = ${id})
46
+ OR (${mode} = 'serviceAccount' AND execution.requested_by_service_account_id = ${id})
47
+ )`
48
+ }
@@ -3,17 +3,21 @@ import {
3
3
  aiModelCallGroupFragmentFromRow,
4
4
  buildAiModelCallGroupsFromFragments,
5
5
  normalizeAiModelCallAccountingQuery,
6
+ normalizeAiModelCallGroupSort,
6
7
  TOKENLESS_MODEL_KINDS,
7
8
  } from "@sixb/core/internal/ai-cost-storage-provider"
8
9
  import type { ListAiModelCallGroupsInput, ListAiModelCallGroupsResult } from "@sixb/core/storage"
10
+ import { pgAccountingFilterSql, pgAccountingFilterValues } from "./ai-accounting-filters"
9
11
  import type { PgStoreClient } from "./transactions"
10
12
 
11
- /** Paginate initiating executions, then aggregate their matching calls without loading usage payloads. */
13
+ /** Paginate conversations, workflow runs and other initiating executions, then aggregate their matching calls without loading usage payloads. */
12
14
  export async function listAiModelCallGroups(
13
15
  sql: PgStoreClient,
14
16
  input: ListAiModelCallGroupsInput
15
17
  ): Promise<ListAiModelCallGroupsResult> {
16
18
  const query = normalizeAiModelCallAccountingQuery(input)
19
+ const sort = normalizeAiModelCallGroupSort(input.sort)
20
+ const filter = pgAccountingFilterValues(query)
17
21
  const parameters = [
18
22
  query.projectId,
19
23
  query.from.toISOString(),
@@ -21,17 +25,23 @@ export async function listAiModelCallGroups(
21
25
  query.providerId ?? null,
22
26
  query.modelId ?? null,
23
27
  query.valuationStatus ?? null,
28
+ filter.kind,
29
+ filter.source,
30
+ filter.workflow,
31
+ filter.mode,
32
+ filter.id,
24
33
  ]
25
34
  const [count] = await sql.unsafe<{ total: string }[]>(COUNT_SQL, parameters)
26
35
  const rows = await sql.unsafe<AiModelCallGroupRow[]>(PAGE_SQL, [
27
36
  ...parameters,
28
37
  query.limit,
29
38
  query.offset,
39
+ sort,
30
40
  ])
31
41
  const total = Number(count?.total)
32
42
  if (!Number.isSafeInteger(total) || total < 0)
33
43
  throw new RangeError("[Sixb] Invalid model-call group count.")
34
- const items = buildAiModelCallGroupsFromFragments(rows.map(aiModelCallGroupFragmentFromRow))
44
+ const items = buildAiModelCallGroupsFromFragments(rows.map(aiModelCallGroupFragmentFromRow), sort)
35
45
  return { items, total, hasMore: query.offset + items.length < total }
36
46
  }
37
47
 
@@ -41,8 +51,15 @@ const TOKENLESS_KINDS = TOKENLESS_MODEL_KINDS.map((kind) => `'${kind}'`).join(",
41
51
  const FILTERED_SQL = `
42
52
  WITH filtered AS (
43
53
  SELECT COALESCE(root_agent.execution_id, usage.execution_id) AS root_execution_id,
54
+ -- What the call is listed under, as aiModelCallGroupKey computes it.
55
+ CASE
56
+ WHEN root_agent.thread_id IS NOT NULL THEN 'thread:' || root_agent.thread_id
57
+ WHEN workflow_node.workflow_run_id IS NOT NULL THEN 'workflowRun:' || workflow_node.workflow_run_id
58
+ ELSE COALESCE(root_agent.execution_id, usage.execution_id)
59
+ END AS group_key,
44
60
  usage.execution_id, usage.provider_id, usage.requested_model_id, usage.occurred_at,
45
- usage.total_tokens, usage.model_kind, usage.output_images, usage.input_characters,
61
+ usage.total_tokens, usage.input_tokens, usage.cache_read_input_tokens,
62
+ usage.model_kind, usage.output_images, usage.input_characters,
46
63
  usage.audio_duration_ms,
47
64
  execution.executor_kind, execution.executor_id, execution.authority_primitive_id AS primitive_id,
48
65
  COALESCE(cost.status, 'unvalued') AS valuation_status,
@@ -55,7 +72,8 @@ WITH filtered AS (
55
72
  workflow_node.node_id AS workflow_agent_step_id,
56
73
  workflow_agent.node_run_id AS workflow_node_run_id,
57
74
  workflow_node.workflow_id AS workflow_id,
58
- workflow_node.workflow_run_id AS workflow_run_id
75
+ workflow_node.workflow_run_id AS workflow_run_id,
76
+ execution.requested_by_user_id, execution.requested_by_service_account_id
59
77
  FROM ai_model_call_usage AS usage
60
78
  JOIN executions AS execution ON execution.project_id = usage.project_id AND execution.id = usage.execution_id
61
79
  LEFT JOIN agent_runs AS direct_agent
@@ -75,23 +93,28 @@ WITH filtered AS (
75
93
  AND ($4::text IS NULL OR usage.provider_id = $4)
76
94
  AND ($5::text IS NULL OR usage.requested_model_id = $5)
77
95
  AND ($6::text IS NULL OR COALESCE(cost.status, 'unvalued') = $6)
96
+ AND ${pgAccountingFilterSql(7)}
78
97
  ), roots AS (
79
- SELECT root_execution_id, MAX(occurred_at) AS last_call_at
80
- FROM filtered GROUP BY root_execution_id
98
+ SELECT group_key, MAX(occurred_at) AS last_call_at, SUM(COALESCE(amount_nanos, 0)) AS cost_nanos
99
+ FROM filtered GROUP BY group_key
81
100
  )
82
101
  `
83
102
  const COUNT_SQL = `${FILTERED_SQL} SELECT CAST(COUNT(*) AS TEXT) AS total FROM roots`
84
103
  const PAGE_SQL = `${FILTERED_SQL}, page AS (
85
- SELECT root_execution_id FROM roots
86
- ORDER BY last_call_at DESC, root_execution_id COLLATE "C" ASC LIMIT $7 OFFSET $8
104
+ SELECT group_key FROM roots
105
+ ORDER BY CASE WHEN $14::text = 'cost' THEN cost_nanos END DESC NULLS LAST,
106
+ last_call_at DESC, group_key COLLATE "C" ASC
107
+ LIMIT $12 OFFSET $13
87
108
  )
88
- SELECT filtered.root_execution_id, execution_id, provider_id, requested_model_id,
109
+ SELECT filtered.group_key, root_execution_id, execution_id, provider_id, requested_model_id,
89
110
  MIN(occurred_at) AS first_call_at, MAX(occurred_at) AS last_call_at,
90
111
  CAST(COUNT(*) AS TEXT) AS call_count,
91
112
  CAST(COUNT(total_tokens) AS TEXT) AS token_count,
92
113
  CAST(COUNT(CASE WHEN total_tokens IS NULL AND model_kind IN (${TOKENLESS_KINDS}) THEN 1 END) AS TEXT)
93
114
  AS tokenless_count,
94
115
  CAST(SUM(total_tokens) AS TEXT) AS total_tokens,
116
+ CAST(SUM(input_tokens) AS TEXT) AS input_tokens,
117
+ CAST(SUM(cache_read_input_tokens) AS TEXT) AS cache_read_input_tokens,
95
118
  CAST(SUM(output_images) AS TEXT) AS output_images,
96
119
  CAST(SUM(input_characters) AS TEXT) AS input_characters,
97
120
  CAST(SUM(audio_duration_ms) AS TEXT) AS audio_duration_ms,
@@ -108,8 +131,10 @@ SELECT filtered.root_execution_id, execution_id, provider_id, requested_model_id
108
131
  MAX(workflow_agent_step_id) AS workflow_agent_step_id,
109
132
  MAX(workflow_node_run_id) AS workflow_node_run_id,
110
133
  MAX(workflow_id) AS workflow_id,
111
- MAX(workflow_run_id) AS workflow_run_id
112
- FROM filtered JOIN page ON page.root_execution_id = filtered.root_execution_id
113
- GROUP BY filtered.root_execution_id, execution_id, provider_id, requested_model_id,
134
+ MAX(workflow_run_id) AS workflow_run_id,
135
+ MAX(requested_by_user_id) AS requested_by_user_id,
136
+ MAX(requested_by_service_account_id) AS requested_by_service_account_id
137
+ FROM filtered JOIN page ON page.group_key = filtered.group_key
138
+ GROUP BY filtered.group_key, root_execution_id, execution_id, provider_id, requested_model_id,
114
139
  valuation_status, amount_currency
115
140
  `
package/src/index.ts CHANGED
@@ -37,7 +37,7 @@ import { PgAgentStorage } from "./agents"
37
37
  import { PgAuthStorage } from "./auth-storage"
38
38
  import { PgConnectorConnectionStorage } from "./connector-connection-storage"
39
39
  import { createPostgresStorageMigrators, dropSchema } from "./migrations"
40
- import { PgObjectStorage } from "./objects"
40
+ import { PgObjectStorage, PgSortIndexCatalog } from "./objects"
41
41
  import { preparePgObjectQueries } from "./objects/prepare-queries"
42
42
  import { ensurePgObjectQueryIndexes, type PgObjectQueryIndex } from "./objects/query-indexes"
43
43
 
@@ -77,9 +77,9 @@ export interface PostgresStorageOptions {
77
77
  * Full connection string (e.g. DATABASE_URL). Takes precedence over individual fields.
78
78
  *
79
79
  * Add `sslnegotiation=direct` (with `sslmode=require`, `verify-ca` or `verify-full`) to open TLS
80
- * directly, as libpq does against PostgreSQL 17 or later. It saves a round trip per connection
81
- * and avoids a Bun 1.4.0–1.4.2 bug that keeps in memory every byte read over a TLS connection
82
- * negotiated the classic way.
80
+ * directly, as libpq does against PostgreSQL 17 or later. It saves a round trip per connection.
81
+ * On Bun 1.4.0–1.4.2 it also avoids a bug that keeps in memory every byte read over a TLS
82
+ * connection negotiated the classic way.
83
83
  */
84
84
  connectionString?: string
85
85
 
@@ -98,7 +98,7 @@ export interface PostgresStorageOptions {
98
98
  max?: number
99
99
  /** Concurrent root count/facet calculations per instance; defaults to 1. */
100
100
  maxConcurrentAggregates?: number
101
- /** Idle connection timeout in milliseconds. Defaults to 30000. */
101
+ /** Idle connection timeout in milliseconds. Defaults to 60000. */
102
102
  idleTimeoutMillis?: number
103
103
 
104
104
  /**
@@ -193,6 +193,7 @@ export class PostgresStorage implements MigrationCapableStorage, QueryPreparatio
193
193
  private readonly schemaName: string
194
194
  private readonly shutdownTimeoutSeconds: number
195
195
  private readonly transactionScope = new AsyncLocalStorage<boolean>()
196
+ private readonly sortIndexes = new PgSortIndexCatalog()
196
197
 
197
198
  constructor(options: PostgresStorageOptions) {
198
199
  if (
@@ -240,6 +241,7 @@ export class PostgresStorage implements MigrationCapableStorage, QueryPreparatio
240
241
 
241
242
  this.migrators = createPostgresStorageMigrators(this.sql, this.schemaName)
242
243
  const stores = createPostgresStores(this.sql, {
244
+ sortIndexes: this.sortIndexes,
243
245
  maxConcurrentAggregates: options.maxConcurrentAggregates,
244
246
  runOntologyOperation: (run) => runPgTransaction(this.sql, run),
245
247
  transactionContext: null,
@@ -335,7 +337,11 @@ export class PostgresStorage implements MigrationCapableStorage, QueryPreparatio
335
337
  plan: ObjectQueryPreparationPlan
336
338
  ): Promise<ObjectQueryPreparationResult> {
337
339
  this.assertRootOperationAvailable()
338
- return preparePgObjectQueries(this.sql, this.schemaName, plan)
340
+ try {
341
+ return await preparePgObjectQueries(this.sql, this.schemaName, plan)
342
+ } finally {
343
+ this.sortIndexes.invalidate()
344
+ }
339
345
  }
340
346
 
341
347
  /** Build workload-specific indexes concurrently, after migrations, outside transactions. */
@@ -343,7 +349,12 @@ export class PostgresStorage implements MigrationCapableStorage, QueryPreparatio
343
349
  indexes: readonly PgObjectQueryIndex[]
344
350
  ): Promise<readonly string[]> {
345
351
  this.assertRootOperationAvailable()
346
- return ensurePgObjectQueryIndexes(this.sql, this.schemaName, indexes)
352
+ try {
353
+ return await ensurePgObjectQueryIndexes(this.sql, this.schemaName, indexes)
354
+ } finally {
355
+ // Even a build that failed partway may have created some of them.
356
+ this.sortIndexes.invalidate()
357
+ }
347
358
  }
348
359
 
349
360
  /** Offline maintenance: STORED columns rewrite the objects table before concurrent index builds. */
@@ -385,6 +396,7 @@ export class PostgresStorage implements MigrationCapableStorage, QueryPreparatio
385
396
  ): Storage & { readonly ontology: PgOntologyStorage; readonly aiLimits: PgAiLimitStorage } {
386
397
  return {
387
398
  ...createPostgresStores(client, {
399
+ sortIndexes: this.sortIndexes,
388
400
  runOntologyOperation: async (run) => run(client),
389
401
  transactionContext,
390
402
  }),
@@ -403,6 +415,7 @@ function createPostgresStores(
403
415
  options: {
404
416
  readonly runOntologyOperation: <T>(run: (sql: SQLClient) => Promise<T>) => Promise<T>
405
417
  readonly transactionContext: PgOntologyTransactionContext | null
418
+ readonly sortIndexes: PgSortIndexCatalog
406
419
  readonly maxConcurrentAggregates?: number
407
420
  }
408
421
  ): PostgresStoreSet {
@@ -411,7 +424,7 @@ function createPostgresStores(
411
424
  const shareSessions = new PgShareSessionStorage(sql)
412
425
  const executions = new PgExecutionStorage(sql, auth, shareSessions)
413
426
  return {
414
- objects: new PgObjectStorage(sql, options.maxConcurrentAggregates),
427
+ objects: new PgObjectStorage(sql, options.sortIndexes, options.maxConcurrentAggregates),
415
428
  ontology: new PgOntologyStorage({
416
429
  sql,
417
430
  runRootOperation: options.runOntologyOperation,