@sixb/core 0.1.2 → 0.1.3

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 (264) hide show
  1. package/dist/actions/index.js +16 -13
  2. package/dist/actions/index.js.map +1 -1
  3. package/dist/agents/adapters.d.ts +11 -1
  4. package/dist/agents/adapters.d.ts.map +1 -1
  5. package/dist/agents/context.js +1 -1
  6. package/dist/agents/errors.d.ts +1 -1
  7. package/dist/agents/errors.d.ts.map +1 -1
  8. package/dist/agents/execution.d.ts +3 -0
  9. package/dist/agents/execution.d.ts.map +1 -1
  10. package/dist/agents/index.d.ts +6 -3
  11. package/dist/agents/index.d.ts.map +1 -1
  12. package/dist/agents/index.js +33 -22
  13. package/dist/agents/index.js.map +1 -1
  14. package/dist/agents/prompt.d.ts +8 -2
  15. package/dist/agents/prompt.d.ts.map +1 -1
  16. package/dist/agents/request.d.ts.map +1 -1
  17. package/dist/agents/streams.js +2 -2
  18. package/dist/agents/thread-context-projection.d.ts +19 -0
  19. package/dist/agents/thread-context-projection.d.ts.map +1 -0
  20. package/dist/agents/tool-definition.d.ts.map +1 -1
  21. package/dist/agents/tool-result.d.ts +6 -0
  22. package/dist/agents/tool-result.d.ts.map +1 -0
  23. package/dist/agents/types.d.ts +37 -1
  24. package/dist/agents/types.d.ts.map +1 -1
  25. package/dist/agents/validation.d.ts +1 -1
  26. package/dist/agents/validation.d.ts.map +1 -1
  27. package/dist/auth/index.js +7 -5
  28. package/dist/auth/index.js.map +1 -1
  29. package/dist/authorization/index.js +1 -1
  30. package/dist/bootstrap/index.js +27 -24
  31. package/dist/bootstrap/index.js.map +1 -1
  32. package/dist/{chunk-0mbx247x.js → chunk-177ed2mp.js} +241 -45
  33. package/dist/chunk-177ed2mp.js.map +46 -0
  34. package/dist/{chunk-sa4340y1.js → chunk-1ywq4hzk.js} +7 -7
  35. package/dist/{chunk-zg9yryhz.js → chunk-261ag4t4.js} +3 -3
  36. package/dist/{chunk-k9pts48t.js → chunk-3rsf30p4.js} +5 -5
  37. package/dist/{chunk-8ryen3p3.js → chunk-4aw0jwk0.js} +1 -1
  38. package/dist/{chunk-bh6k3nc6.js → chunk-4p9rh7jj.js} +1 -1
  39. package/dist/{chunk-34bqh420.js → chunk-4z3n1dzt.js} +59 -21
  40. package/dist/{chunk-34bqh420.js.map → chunk-4z3n1dzt.js.map} +4 -4
  41. package/dist/chunk-96swp2wd.js +47 -0
  42. package/dist/chunk-96swp2wd.js.map +10 -0
  43. package/dist/{chunk-n8herkry.js → chunk-bv41fmjn.js} +11 -11
  44. package/dist/{chunk-7pc8b818.js → chunk-c6cfqydk.js} +1 -1
  45. package/dist/{chunk-0k4avqr2.js → chunk-c8bw2b6c.js} +2 -2
  46. package/dist/{chunk-jaj13078.js → chunk-d2adj15j.js} +3 -33
  47. package/dist/{chunk-jaj13078.js.map → chunk-d2adj15j.js.map} +3 -4
  48. package/dist/{chunk-c6qd89g5.js → chunk-d6y2wsfg.js} +3 -3
  49. package/dist/chunk-dysw7nsm.js.map +1 -1
  50. package/dist/{chunk-st4xgxey.js → chunk-ettb0cy4.js} +150 -23
  51. package/dist/chunk-ettb0cy4.js.map +45 -0
  52. package/dist/{chunk-nnyp53zt.js → chunk-f1cyvnrk.js} +1 -1
  53. package/dist/chunk-fmx1sz2h.js.map +2 -2
  54. package/dist/{chunk-bct7hmfc.js → chunk-km4rkj4t.js} +3 -3
  55. package/dist/chunk-kqxgf6kv.js +898 -0
  56. package/dist/chunk-kqxgf6kv.js.map +15 -0
  57. package/dist/{chunk-qvybnnpe.js → chunk-n5x5y80a.js} +2 -2
  58. package/dist/{chunk-4x43bkbp.js → chunk-pxtrxm3p.js} +1 -1
  59. package/dist/chunk-qer6am8w.js +133 -0
  60. package/dist/chunk-qer6am8w.js.map +11 -0
  61. package/dist/{chunk-85j5ybfj.js → chunk-rdeagz6b.js} +2 -2
  62. package/dist/{chunk-85j5ybfj.js.map → chunk-rdeagz6b.js.map} +3 -3
  63. package/dist/chunk-rhrbz7d4.js +36 -0
  64. package/dist/chunk-rhrbz7d4.js.map +10 -0
  65. package/dist/{chunk-663csy96.js → chunk-t0jjkep3.js} +2 -1
  66. package/dist/chunk-t0jjkep3.js.map +10 -0
  67. package/dist/{chunk-5egfka8j.js → chunk-ttba8x6z.js} +2 -2
  68. package/dist/{chunk-nten49ta.js → chunk-wb4051cx.js} +3 -3
  69. package/dist/{chunk-nten49ta.js.map → chunk-wb4051cx.js.map} +1 -1
  70. package/dist/{chunk-57r1cpxx.js → chunk-xc7hq65b.js} +3 -2
  71. package/dist/{chunk-57r1cpxx.js.map → chunk-xc7hq65b.js.map} +3 -3
  72. package/dist/{chunk-ys1nse2v.js → chunk-xmggaxg4.js} +256 -231
  73. package/dist/{chunk-ys1nse2v.js.map → chunk-xmggaxg4.js.map} +8 -10
  74. package/dist/{chunk-g9t3kdtx.js → chunk-z8j83gzd.js} +1 -1
  75. package/dist/{chunk-57zpb99z.js → chunk-zpw39qhj.js} +1 -1
  76. package/dist/execution/agent.js +23 -20
  77. package/dist/execution/agent.js.map +1 -1
  78. package/dist/execution/primitive.js +23 -20
  79. package/dist/execution/primitive.js.map +2 -2
  80. package/dist/execution/request.js +24 -21
  81. package/dist/execution/request.js.map +2 -2
  82. package/dist/index.d.ts +3 -3
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +32 -29
  85. package/dist/index.js.map +1 -1
  86. package/dist/materialization/model.d.ts +4 -0
  87. package/dist/materialization/model.d.ts.map +1 -1
  88. package/dist/materializer/edits/apply.d.ts +6 -1
  89. package/dist/materializer/edits/apply.d.ts.map +1 -1
  90. package/dist/materializer/edits/working-state.d.ts +2 -0
  91. package/dist/materializer/edits/working-state.d.ts.map +1 -1
  92. package/dist/materializer/effective/resolve.d.ts +3 -1
  93. package/dist/materializer/effective/resolve.d.ts.map +1 -1
  94. package/dist/materializer/execution/work-records.d.ts.map +1 -1
  95. package/dist/materializer/index.js +14 -11
  96. package/dist/materializer/index.js.map +1 -1
  97. package/dist/materializer/projections/replacement-plan.d.ts.map +1 -1
  98. package/dist/materializer/shared/normalize.d.ts.map +1 -1
  99. package/dist/objects/index.js +17 -14
  100. package/dist/objects/index.js.map +1 -1
  101. package/dist/objects/query/index.js +2 -2
  102. package/dist/pipelines/index.js +14 -12
  103. package/dist/pipelines/index.js.map +1 -1
  104. package/dist/projections/builders.d.ts +19 -6
  105. package/dist/projections/builders.d.ts.map +1 -1
  106. package/dist/projections/index.d.ts +2 -1
  107. package/dist/projections/index.d.ts.map +1 -1
  108. package/dist/projections/internal.d.ts +4 -1
  109. package/dist/projections/internal.d.ts.map +1 -1
  110. package/dist/projections/internal.js +17 -11
  111. package/dist/projections/internal.js.map +1 -1
  112. package/dist/projections/timestamp.d.ts +3 -0
  113. package/dist/projections/timestamp.d.ts.map +1 -0
  114. package/dist/projections/types.d.ts +9 -0
  115. package/dist/projections/types.d.ts.map +1 -1
  116. package/dist/projections/validation.d.ts.map +1 -1
  117. package/dist/queues/index.d.ts +1 -1
  118. package/dist/queues/index.d.ts.map +1 -1
  119. package/dist/queues/types.d.ts +7 -0
  120. package/dist/queues/types.d.ts.map +1 -1
  121. package/dist/runtime/ai-cost.d.ts +8 -0
  122. package/dist/runtime/ai-cost.d.ts.map +1 -0
  123. package/dist/storage/agents/in-memory.d.ts +18 -4
  124. package/dist/storage/agents/in-memory.d.ts.map +1 -1
  125. package/dist/storage/agents/index.d.ts +1 -1
  126. package/dist/storage/agents/index.d.ts.map +1 -1
  127. package/dist/storage/agents/provider.d.ts +31 -0
  128. package/dist/storage/agents/provider.d.ts.map +1 -1
  129. package/dist/storage/agents/provider.js +18 -7
  130. package/dist/storage/agents/provider.js.map +1 -1
  131. package/dist/storage/agents/types.d.ts +70 -4
  132. package/dist/storage/agents/types.d.ts.map +1 -1
  133. package/dist/storage/ai-cost/analytics.d.ts +61 -0
  134. package/dist/storage/ai-cost/analytics.d.ts.map +1 -0
  135. package/dist/storage/ai-cost/codec.d.ts +14 -0
  136. package/dist/storage/ai-cost/codec.d.ts.map +1 -0
  137. package/dist/storage/ai-cost/errors.d.ts +7 -0
  138. package/dist/storage/ai-cost/errors.d.ts.map +1 -0
  139. package/dist/storage/ai-cost/in-memory.d.ts +32 -0
  140. package/dist/storage/ai-cost/in-memory.d.ts.map +1 -0
  141. package/dist/storage/ai-cost/index.d.ts +6 -0
  142. package/dist/storage/ai-cost/index.d.ts.map +1 -0
  143. package/dist/storage/ai-cost/provider.d.ts +7 -0
  144. package/dist/storage/ai-cost/provider.d.ts.map +1 -0
  145. package/dist/storage/ai-cost/provider.js +132 -0
  146. package/dist/storage/ai-cost/provider.js.map +10 -0
  147. package/dist/storage/ai-cost/types.d.ts +154 -0
  148. package/dist/storage/ai-cost/types.d.ts.map +1 -0
  149. package/dist/storage/ai-cost/validation.d.ts +7 -0
  150. package/dist/storage/ai-cost/validation.d.ts.map +1 -0
  151. package/dist/storage/in-memory/index.d.ts +5 -0
  152. package/dist/storage/in-memory/index.d.ts.map +1 -1
  153. package/dist/storage/index.d.ts +3 -1
  154. package/dist/storage/index.d.ts.map +1 -1
  155. package/dist/storage/index.js +22 -15
  156. package/dist/storage/index.js.map +1 -1
  157. package/dist/storage/ontology/in-memory/materializations.d.ts.map +1 -1
  158. package/dist/storage/ontology/materializations.d.ts +3 -0
  159. package/dist/storage/ontology/materializations.d.ts.map +1 -1
  160. package/dist/storage/operation-scope.d.ts.map +1 -1
  161. package/dist/storage/operation-scope.js +1 -1
  162. package/dist/storage/types.d.ts +2 -0
  163. package/dist/storage/types.d.ts.map +1 -1
  164. package/dist/storage/workflow-runs/provider.js +6 -5
  165. package/dist/storage/workflow-runs/provider.js.map +1 -1
  166. package/dist/syncs/index.js +14 -12
  167. package/dist/syncs/index.js.map +1 -1
  168. package/dist/testing/agent-storage-contract.d.ts +3 -2
  169. package/dist/testing/agent-storage-contract.d.ts.map +1 -1
  170. package/dist/testing/ai-cost-storage-contract.d.ts +12 -0
  171. package/dist/testing/ai-cost-storage-contract.d.ts.map +1 -0
  172. package/dist/testing/index.d.ts +1 -0
  173. package/dist/testing/index.d.ts.map +1 -1
  174. package/dist/testing/index.js +2098 -1468
  175. package/dist/testing/index.js.map +6 -5
  176. package/dist/testing/materializer-storage-contract.d.ts.map +1 -1
  177. package/dist/webhooks/internal.js +12 -10
  178. package/dist/webhooks/internal.js.map +2 -2
  179. package/dist/workers/index.js +12 -2
  180. package/dist/workers/index.js.map +3 -3
  181. package/dist/workers/queue-worker.d.ts +2 -0
  182. package/dist/workers/queue-worker.d.ts.map +1 -1
  183. package/dist/workflows/execution.d.ts +3 -0
  184. package/dist/workflows/execution.d.ts.map +1 -1
  185. package/dist/workflows/index.js +24 -21
  186. package/dist/workflows/index.js.map +1 -1
  187. package/package.json +7 -1
  188. package/src/agents/adapters.ts +64 -23
  189. package/src/agents/errors.ts +2 -2
  190. package/src/agents/execution.ts +14 -2
  191. package/src/agents/index.ts +18 -1
  192. package/src/agents/prompt.ts +33 -5
  193. package/src/agents/request.ts +5 -0
  194. package/src/agents/thread-context-projection.ts +93 -0
  195. package/src/agents/tool-definition.ts +17 -2
  196. package/src/agents/tool-result.ts +61 -0
  197. package/src/agents/types.ts +47 -1
  198. package/src/agents/validation.ts +1 -1
  199. package/src/index.ts +13 -0
  200. package/src/materialization/model.ts +4 -0
  201. package/src/materializer/edits/apply.ts +55 -2
  202. package/src/materializer/edits/operations.ts +8 -1
  203. package/src/materializer/edits/working-state.ts +7 -0
  204. package/src/materializer/effective/resolve.ts +78 -9
  205. package/src/materializer/execution/work-records.ts +3 -1
  206. package/src/materializer/projections/entry-validator.ts +23 -1
  207. package/src/materializer/projections/replacement-plan.ts +2 -0
  208. package/src/materializer/shared/normalize.ts +16 -0
  209. package/src/projections/builders.ts +100 -35
  210. package/src/projections/index.ts +6 -0
  211. package/src/projections/internal.ts +4 -1
  212. package/src/projections/registry.ts +7 -0
  213. package/src/projections/revision.ts +4 -0
  214. package/src/projections/timestamp.ts +66 -0
  215. package/src/projections/types.ts +7 -0
  216. package/src/projections/validation.ts +24 -0
  217. package/src/queues/index.ts +1 -0
  218. package/src/queues/types.ts +8 -0
  219. package/src/runtime/ai-cost.ts +15 -0
  220. package/src/storage/agents/in-memory.ts +171 -4
  221. package/src/storage/agents/index.ts +5 -0
  222. package/src/storage/agents/provider.ts +225 -0
  223. package/src/storage/agents/types.ts +77 -3
  224. package/src/storage/ai-cost/analytics.ts +602 -0
  225. package/src/storage/ai-cost/codec.ts +136 -0
  226. package/src/storage/ai-cost/errors.ts +12 -0
  227. package/src/storage/ai-cost/in-memory.ts +164 -0
  228. package/src/storage/ai-cost/index.ts +35 -0
  229. package/src/storage/ai-cost/provider.ts +20 -0
  230. package/src/storage/ai-cost/types.ts +193 -0
  231. package/src/storage/ai-cost/validation.ts +337 -0
  232. package/src/storage/in-memory/index.ts +50 -0
  233. package/src/storage/index.ts +37 -0
  234. package/src/storage/ontology/in-memory/materializations.ts +1 -0
  235. package/src/storage/ontology/materializations.ts +3 -0
  236. package/src/storage/operation-scope.ts +1 -0
  237. package/src/storage/types.ts +2 -0
  238. package/src/testing/agent-storage-contract.ts +341 -2
  239. package/src/testing/ai-cost-storage-contract.ts +320 -0
  240. package/src/testing/index.ts +5 -0
  241. package/src/testing/materializer-storage-contract.ts +120 -2
  242. package/src/workers/queue-worker.ts +14 -1
  243. package/src/workflows/execution.ts +31 -10
  244. package/dist/chunk-0mbx247x.js.map +0 -43
  245. package/dist/chunk-663csy96.js.map +0 -10
  246. package/dist/chunk-st4xgxey.js.map +0 -45
  247. package/dist/chunk-vp1vc6ee.js +0 -35
  248. package/dist/chunk-vp1vc6ee.js.map +0 -11
  249. /package/dist/{chunk-sa4340y1.js.map → chunk-1ywq4hzk.js.map} +0 -0
  250. /package/dist/{chunk-zg9yryhz.js.map → chunk-261ag4t4.js.map} +0 -0
  251. /package/dist/{chunk-k9pts48t.js.map → chunk-3rsf30p4.js.map} +0 -0
  252. /package/dist/{chunk-8ryen3p3.js.map → chunk-4aw0jwk0.js.map} +0 -0
  253. /package/dist/{chunk-bh6k3nc6.js.map → chunk-4p9rh7jj.js.map} +0 -0
  254. /package/dist/{chunk-n8herkry.js.map → chunk-bv41fmjn.js.map} +0 -0
  255. /package/dist/{chunk-7pc8b818.js.map → chunk-c6cfqydk.js.map} +0 -0
  256. /package/dist/{chunk-0k4avqr2.js.map → chunk-c8bw2b6c.js.map} +0 -0
  257. /package/dist/{chunk-c6qd89g5.js.map → chunk-d6y2wsfg.js.map} +0 -0
  258. /package/dist/{chunk-nnyp53zt.js.map → chunk-f1cyvnrk.js.map} +0 -0
  259. /package/dist/{chunk-bct7hmfc.js.map → chunk-km4rkj4t.js.map} +0 -0
  260. /package/dist/{chunk-qvybnnpe.js.map → chunk-n5x5y80a.js.map} +0 -0
  261. /package/dist/{chunk-4x43bkbp.js.map → chunk-pxtrxm3p.js.map} +0 -0
  262. /package/dist/{chunk-5egfka8j.js.map → chunk-ttba8x6z.js.map} +0 -0
  263. /package/dist/{chunk-g9t3kdtx.js.map → chunk-z8j83gzd.js.map} +0 -0
  264. /package/dist/{chunk-57zpb99z.js.map → chunk-zpw39qhj.js.map} +0 -0
@@ -0,0 +1,15 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/storage/ai-usage/errors.ts", "../src/storage/ai-usage/usage.ts", "../src/storage/ai-usage/record.ts", "../src/storage/ai-usage/in-memory.ts", "../src/storage/ai-cost/analytics.ts", "../src/storage/ai-cost/validation.ts"],
4
+ "sourcesContent": [
5
+ "export type AiUsageStorageErrorCode = \"duplicate_id\" | \"missing_execution\"\n\n/** Storage failure specific to the AI model-call usage ledger. */\nexport class AiUsageStorageError extends Error {\n readonly name = \"AiUsageStorageError\"\n\n constructor(\n readonly code: AiUsageStorageErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n",
6
+ "import type { AiModelCallUsage, AiModelCallUsageInput } from \"./types\"\n\nconst USAGE_FIELDS = [\n \"inputTokens\",\n \"outputTokens\",\n \"uncachedInputTokens\",\n \"cacheReadInputTokens\",\n \"cacheWriteInputTokens\",\n \"textOutputTokens\",\n \"reasoningOutputTokens\",\n] as const\n\ntype AiUsageField = (typeof USAGE_FIELDS)[number]\n\n/** Validate provider-neutral counts and derive total/reporting fields without inventing zeroes. */\nexport function normalizeAiModelCallUsage(input: AiModelCallUsageInput): AiModelCallUsage {\n for (const field of USAGE_FIELDS) {\n assertUsageCount(input[field], field)\n }\n\n const totalTokens =\n input.inputTokens === undefined || input.outputTokens === undefined\n ? undefined\n : addUsageCounts(input.inputTokens, input.outputTokens, \"totalTokens\")\n const reportingStatus =\n input.inputTokens !== undefined && input.outputTokens !== undefined\n ? \"complete\"\n : USAGE_FIELDS.some((field) => input[field] !== undefined)\n ? \"partial\"\n : \"unavailable\"\n\n return {\n ...(input.inputTokens === undefined ? {} : { inputTokens: input.inputTokens }),\n ...(input.outputTokens === undefined ? {} : { outputTokens: input.outputTokens }),\n ...(totalTokens === undefined ? {} : { totalTokens }),\n ...(input.uncachedInputTokens === undefined\n ? {}\n : { uncachedInputTokens: input.uncachedInputTokens }),\n ...(input.cacheReadInputTokens === undefined\n ? {}\n : { cacheReadInputTokens: input.cacheReadInputTokens }),\n ...(input.cacheWriteInputTokens === undefined\n ? {}\n : { cacheWriteInputTokens: input.cacheWriteInputTokens }),\n ...(input.textOutputTokens === undefined ? {} : { textOutputTokens: input.textOutputTokens }),\n ...(input.reasoningOutputTokens === undefined\n ? {}\n : { reasoningOutputTokens: input.reasoningOutputTokens }),\n reportingStatus,\n }\n}\n\n/**\n * Aggregate model-call usage without treating a missing count as zero.\n *\n * A field is present only when every call reported it. This prevents a partial provider response\n * from becoming an apparently complete execution total. Zero remains a reported value.\n */\nexport function aggregateAiModelCallUsage(\n usages: Iterable<AiModelCallUsageInput>\n): AiModelCallUsage {\n const normalized = Array.from(usages, normalizeAiModelCallUsage)\n const fields = Object.fromEntries(\n USAGE_FIELDS.map((field) => [field, sumUsageField(normalized, field)])\n ) as Record<AiUsageField, number | undefined>\n const aggregate = normalizeAiModelCallUsage(fields)\n\n if (\n aggregate.reportingStatus === \"unavailable\" &&\n normalized.some((usage) => usage.reportingStatus !== \"unavailable\")\n ) {\n return { ...aggregate, reportingStatus: \"partial\" }\n }\n return aggregate\n}\n\nfunction sumUsageField(\n usages: readonly AiModelCallUsage[],\n field: AiUsageField\n): number | undefined {\n if (usages.length === 0) return undefined\n\n let total = 0\n for (const usage of usages) {\n const value = usage[field]\n if (value === undefined) return undefined\n total = addUsageCounts(total, value, `aggregate ${field}`)\n }\n return total\n}\n\nfunction assertUsageCount(value: number | undefined, field: AiUsageField): void {\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 0)) {\n throw new TypeError(`[Sixb] AI model-call usage ${field} must be a non-negative safe integer.`)\n }\n}\n\nfunction addUsageCounts(left: number, right: number, field: string): number {\n const result = left + right\n if (!Number.isSafeInteger(result)) {\n throw new TypeError(`[Sixb] AI model-call usage ${field} exceeds the safe integer range.`)\n }\n return result\n}\n",
7
+ "import { normalizeRequesterGroupIds } from \"../../auth/attribution\"\nimport { assertJsonValue, isPlainRecord } from \"../../json\"\nimport type { AiModelCallUsageRecord, RecordAiModelCallInput } from \"./types\"\nimport { normalizeAiModelCallUsage } from \"./usage\"\n\n/** Validate and defensively snapshot one provider-neutral model-call ledger input. */\nexport function normalizeAiModelCallRecord(input: RecordAiModelCallInput): AiModelCallUsageRecord {\n assertNonBlank(input.id, \"id\")\n assertNonBlank(input.projectId, \"projectId\")\n assertAiUsageExecutionId(input.executionId)\n assertPositiveSafeInteger(input.attempt, \"attempt\")\n assertNonBlank(input.callId, \"callId\")\n assertNonBlank(input.providerId, \"providerId\")\n assertNonBlank(input.requestedModelId, \"requestedModelId\")\n if (input.responseModelId !== undefined) {\n assertNonBlank(input.responseModelId, \"responseModelId\")\n }\n assertNonBlank(input.responseId, \"responseId\")\n\n const occurredAt = cloneValidDate(input.occurredAt, \"occurredAt\")\n const recordedAt = cloneValidDate(input.recordedAt ?? new Date(), \"recordedAt\")\n const requesterGroupIds = normalizeRequesterGroupIds(input.requesterGroupIds)\n const rawUsage = cloneRawUsage(input.rawUsage)\n\n return {\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n attempt: input.attempt,\n callId: input.callId,\n requesterGroupIds,\n providerId: input.providerId,\n requestedModelId: input.requestedModelId,\n ...(input.responseModelId === undefined ? {} : { responseModelId: input.responseModelId }),\n responseId: input.responseId,\n usage: normalizeAiModelCallUsage(input.usage),\n ...(rawUsage === undefined ? {} : { rawUsage }),\n occurredAt,\n recordedAt,\n }\n}\n\n/** Validate a durable execution reference at storage and query boundaries. */\nexport function assertAiUsageExecutionId(executionId: string): void {\n assertNonBlank(executionId, \"executionId\")\n}\n\nfunction cloneRawUsage(rawUsage: RecordAiModelCallInput[\"rawUsage\"]) {\n if (rawUsage === undefined) return undefined\n if (!isPlainRecord(rawUsage)) {\n throw new TypeError(\"[Sixb] AI usage rawUsage must be a JSON object.\")\n }\n assertJsonValue(rawUsage, \"AI usage rawUsage\")\n return structuredClone(rawUsage)\n}\n\nfunction assertNonBlank(value: string, field: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`[Sixb] AI usage ${field} must be nonblank.`)\n }\n}\n\nfunction assertPositiveSafeInteger(value: number, field: string): void {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(`[Sixb] AI usage ${field} must be a positive safe integer.`)\n }\n}\n\nfunction cloneValidDate(value: Date, field: string): Date {\n if (!(value instanceof Date) || !Number.isFinite(value.getTime())) {\n throw new TypeError(`[Sixb] AI usage ${field} must be a valid Date.`)\n }\n return new Date(value)\n}\n",
8
+ "import type { ExecutionStorage } from \"../executions\"\nimport { AiUsageStorageError } from \"./errors\"\nimport { assertAiUsageExecutionId, normalizeAiModelCallRecord } from \"./record\"\nimport type {\n AiModelCallUsageRecord,\n AiUsageExecutionSummary,\n AiUsageStorage,\n RecordAiModelCallInput,\n RecordAiModelCallResult,\n SummarizeAiUsageExecutionInput,\n SummarizeAiUsageExecutionsInput,\n} from \"./types\"\nimport { aggregateAiModelCallUsage } from \"./usage\"\n\nexport interface InMemoryAiUsageGroupRow {\n readonly projectId: string\n readonly usageRecordId: string\n readonly groupId: string\n readonly occurredAt: Date\n}\n\nexport interface InMemoryAiUsageStorageSnapshot {\n readonly records: Map<string, AiModelCallUsageRecord>\n readonly recordKeysByIdempotencyKey: Map<string, string>\n readonly groupRows: Map<string, InMemoryAiUsageGroupRow>\n}\n\n/** In-memory model-call ledger used by development runtimes and storage contract tests. */\nexport class InMemoryAiUsageStorage implements AiUsageStorage {\n private readonly records = new Map<string, AiModelCallUsageRecord>()\n private readonly recordKeysByIdempotencyKey = new Map<string, string>()\n private readonly groupRows = new Map<string, InMemoryAiUsageGroupRow>()\n\n constructor(private readonly executions: Pick<ExecutionStorage, \"getById\">) {}\n\n async recordModelCall(input: RecordAiModelCallInput): Promise<RecordAiModelCallResult> {\n const record = normalizeAiModelCallRecord(input)\n await this.assertExecutionExists(record.projectId, record.executionId)\n const idempotencyKey = modelCallIdempotencyKey(record)\n const existingRecordKey = this.recordKeysByIdempotencyKey.get(idempotencyKey)\n if (existingRecordKey !== undefined) {\n const existing = this.records.get(existingRecordKey)\n if (!existing) {\n throw new Error(\"[Sixb] In-memory AI usage idempotency index is inconsistent.\")\n }\n return { record: structuredClone(existing), created: false }\n }\n\n const recordKey = modelCallRecordKey(record.projectId, record.id)\n if (this.records.has(recordKey)) {\n throw new AiUsageStorageError(\n \"duplicate_id\",\n `[Sixb] AI usage record '${record.id}' already exists for project '${record.projectId}'.`\n )\n }\n\n this.records.set(recordKey, structuredClone(record))\n this.recordKeysByIdempotencyKey.set(idempotencyKey, recordKey)\n for (const groupId of record.requesterGroupIds) {\n const row: InMemoryAiUsageGroupRow = {\n projectId: record.projectId,\n usageRecordId: record.id,\n groupId,\n occurredAt: record.occurredAt,\n }\n this.groupRows.set(groupRowKey(row), row)\n }\n\n return { record: structuredClone(record), created: true }\n }\n\n async summarizeExecution(\n input: SummarizeAiUsageExecutionInput\n ): Promise<AiUsageExecutionSummary> {\n const [summary] = await this.summarizeExecutions({\n projectId: input.projectId,\n executionIds: [input.executionId],\n })\n return summary!\n }\n\n async summarizeExecutions(\n input: SummarizeAiUsageExecutionsInput\n ): Promise<readonly AiUsageExecutionSummary[]> {\n if (typeof input.projectId !== \"string\" || input.projectId.trim().length === 0) {\n throw new TypeError(\"[Sixb] AI usage projectId must be nonblank.\")\n }\n\n const usageByExecutionId = new Map<string, AiModelCallUsageRecord[\"usage\"][]>()\n for (const executionId of input.executionIds) {\n assertAiUsageExecutionId(executionId)\n usageByExecutionId.set(executionId, [])\n }\n if (usageByExecutionId.size === 0) return []\n\n for (const record of this.records.values()) {\n if (record.projectId !== input.projectId) continue\n usageByExecutionId.get(record.executionId)?.push(record.usage)\n }\n\n return input.executionIds.map((executionId) => {\n const usages = usageByExecutionId.get(executionId) ?? []\n return {\n modelCallCount: usages.length,\n usage: aggregateAiModelCallUsage(usages),\n }\n })\n }\n\n snapshot(): InMemoryAiUsageStorageSnapshot {\n return structuredClone({\n records: this.records,\n recordKeysByIdempotencyKey: this.recordKeysByIdempotencyKey,\n groupRows: this.groupRows,\n })\n }\n\n restore(snapshot: InMemoryAiUsageStorageSnapshot): void {\n replaceMap(this.records, snapshot.records)\n replaceMap(this.recordKeysByIdempotencyKey, snapshot.recordKeysByIdempotencyKey)\n replaceMap(this.groupRows, snapshot.groupRows)\n }\n\n private async assertExecutionExists(projectId: string, executionId: string): Promise<void> {\n const execution = await this.executions.getById({ projectId, id: executionId })\n if (execution) return\n throw new AiUsageStorageError(\n \"missing_execution\",\n `[Sixb] AI usage execution '${executionId}' does not exist in project '${projectId}'.`\n )\n }\n}\n\nfunction modelCallRecordKey(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nfunction modelCallIdempotencyKey(\n record: Pick<\n AiModelCallUsageRecord,\n \"projectId\" | \"executionId\" | \"attempt\" | \"callId\" | \"responseId\"\n >\n): string {\n return JSON.stringify([\n record.projectId,\n record.executionId,\n record.attempt,\n record.callId,\n record.responseId,\n ])\n}\n\nfunction groupRowKey(row: InMemoryAiUsageGroupRow): string {\n return JSON.stringify([row.projectId, row.usageRecordId, row.groupId])\n}\n\nfunction replaceMap<TKey, TValue>(target: Map<TKey, TValue>, source: Map<TKey, TValue>): void {\n target.clear()\n for (const [key, value] of structuredClone(source)) {\n target.set(key, value)\n }\n}\n",
9
+ "import {\n type AiModelCallUsage,\n type AiModelCallUsageRecord,\n aggregateAiModelCallUsage,\n normalizeAiModelCallUsage,\n} from \"../ai-usage\"\nimport type {\n AiAccountingAgentBreakdown,\n AiAccountingAggregate,\n AiAccountingAttribution,\n AiAccountingBucket,\n AiAccountingModelBreakdown,\n AiAccountingOverview,\n AiAccountingTimeBucket,\n AiAccountingWorkflowBreakdown,\n AiCostSummary,\n AiModelCallAccountingItem,\n AiModelCallCostRecord,\n AiMoney,\n ListAiModelCallAccountingInput,\n ListAiModelCallAccountingResult,\n QueryAiAccountingOverviewInput,\n} from \"./types\"\n\nconst DEFAULT_MODEL_CALL_PAGE_SIZE = 50\nconst MAX_MODEL_CALL_PAGE_SIZE = 200\nconst MAX_CHART_BUCKETS = 10_000\n\n/** One joined immutable model-call row used by in-memory analytics and bounded SQL pages. */\nexport interface AiAccountingRecordSetItem {\n readonly usage: AiModelCallUsageRecord\n readonly attribution?: AiAccountingAttribution\n readonly cost?: AiModelCallCostRecord\n}\n\nexport interface NormalizedAiAccountingQuery {\n readonly projectId: string\n readonly from: Date\n readonly to: Date\n readonly providerId?: string\n readonly modelId?: string\n}\n\nexport interface NormalizedAiModelCallAccountingQuery extends NormalizedAiAccountingQuery {\n readonly executionId?: string\n readonly valuationStatus?: ListAiModelCallAccountingInput[\"valuationStatus\"]\n readonly limit: number\n readonly offset: number\n}\n\ninterface AiAccountingUsageMeterFragment {\n readonly presentCallCount: string\n readonly total: string | null\n}\n\n/** One SQL-aggregated currency fragment; providers merge fragments without loading model calls. */\nexport interface AiAccountingAggregateFragment {\n readonly dimension: \"totals\" | \"series\" | \"model\" | \"agent\" | \"workflow\"\n readonly start?: Date\n readonly providerId?: string\n readonly modelId?: string\n readonly agentId?: string\n readonly workflowId?: string\n readonly modelCallCount: string\n readonly usage: {\n readonly reportedCallCount: string\n readonly inputTokens: AiAccountingUsageMeterFragment\n readonly outputTokens: AiAccountingUsageMeterFragment\n readonly uncachedInputTokens: AiAccountingUsageMeterFragment\n readonly cacheReadInputTokens: AiAccountingUsageMeterFragment\n readonly cacheWriteInputTokens: AiAccountingUsageMeterFragment\n readonly textOutputTokens: AiAccountingUsageMeterFragment\n readonly reasoningOutputTokens: AiAccountingUsageMeterFragment\n }\n readonly costs: {\n readonly amount?: AiMoney\n readonly ratedCallCount: string\n readonly unpriceableCallCount: string\n readonly unvaluedCallCount: string\n }\n}\n\nexport function normalizeAiAccountingQuery(\n input: Omit<QueryAiAccountingOverviewInput, \"bucket\"> | ListAiModelCallAccountingInput\n): NormalizedAiAccountingQuery {\n assertNonBlank(input.projectId, \"accounting projectId\")\n assertDate(input.from, \"accounting from\")\n assertDate(input.to, \"accounting to\")\n if (input.from.getTime() >= input.to.getTime()) {\n throw new TypeError(\"[Sixb] AI accounting from must be before to.\")\n }\n if (input.providerId !== undefined) assertNonBlank(input.providerId, \"accounting providerId\")\n if (input.modelId !== undefined) assertNonBlank(input.modelId, \"accounting modelId\")\n return {\n projectId: input.projectId,\n from: new Date(input.from),\n to: new Date(input.to),\n ...(input.providerId === undefined ? {} : { providerId: input.providerId }),\n ...(input.modelId === undefined ? {} : { modelId: input.modelId }),\n }\n}\n\nexport function normalizeAiModelCallAccountingQuery(\n input: ListAiModelCallAccountingInput\n): NormalizedAiModelCallAccountingQuery {\n const query = normalizeAiAccountingQuery(input)\n if (input.executionId !== undefined) {\n assertNonBlank(input.executionId, \"accounting executionId\")\n }\n const { limit, offset } = normalizePage(input.limit, input.offset)\n return {\n ...query,\n ...(input.executionId === undefined ? {} : { executionId: input.executionId }),\n ...(input.valuationStatus === undefined ? {} : { valuationStatus: input.valuationStatus }),\n limit,\n offset,\n }\n}\n\nexport function aiAccountingItemMatchesQuery(\n item: AiAccountingRecordSetItem,\n query: NormalizedAiAccountingQuery\n): boolean {\n const occurredAt = item.usage.occurredAt.getTime()\n return (\n item.usage.projectId === query.projectId &&\n occurredAt >= query.from.getTime() &&\n occurredAt < query.to.getTime() &&\n (query.providerId === undefined || item.usage.providerId === query.providerId) &&\n (query.modelId === undefined || item.usage.requestedModelId === query.modelId)\n )\n}\n\nexport function buildAiAccountingOverview(\n input: QueryAiAccountingOverviewInput,\n source: Iterable<AiAccountingRecordSetItem>\n): AiAccountingOverview {\n const query = normalizeAiAccountingQuery(input)\n assertAiAccountingBucket(input.bucket)\n const items = Array.from(source).filter((item) => aiAccountingItemMatchesQuery(item, query))\n const periods = accountingPeriods(query.from, query.to, input.bucket)\n const periodItems = new Map<number, AiAccountingRecordSetItem[]>(\n periods.map((period) => [period.start.getTime(), []])\n )\n const modelItems = new Map<string, AiAccountingRecordSetItem[]>()\n const agentItems = new Map<string, AiAccountingRecordSetItem[]>()\n const workflowItems = new Map<string, AiAccountingRecordSetItem[]>()\n\n for (const item of items) {\n const periodStart = aiAccountingBucketStart(item.usage.occurredAt, input.bucket).getTime()\n periodItems.get(periodStart)?.push(item)\n appendGrouped(\n modelItems,\n JSON.stringify([item.usage.providerId, item.usage.requestedModelId]),\n item\n )\n if (item.attribution) appendGrouped(agentItems, item.attribution.agentId, item)\n if (item.attribution?.kind === \"workflowAgent\") {\n appendGrouped(workflowItems, item.attribution.workflowId, item)\n }\n }\n\n const series: AiAccountingTimeBucket[] = periods.map((period) => ({\n ...period,\n ...aggregateAccountingItems(periodItems.get(period.start.getTime()) ?? []),\n }))\n const models: AiAccountingModelBreakdown[] = [...modelItems]\n .map(([key, grouped]) => {\n const [providerId, modelId] = JSON.parse(key) as [string, string]\n return { providerId, modelId, ...aggregateAccountingItems(grouped) }\n })\n .sort(compareModelBreakdowns)\n const agents: AiAccountingAgentBreakdown[] = [...agentItems]\n .map(([agentId, grouped]) => ({ agentId, ...aggregateAccountingItems(grouped) }))\n .sort(compareAgentBreakdowns)\n const workflows: AiAccountingWorkflowBreakdown[] = [...workflowItems]\n .map(([workflowId, grouped]) => ({ workflowId, ...aggregateAccountingItems(grouped) }))\n .sort(compareWorkflowBreakdowns)\n\n return structuredClone({\n range: { from: query.from, to: query.to },\n bucket: input.bucket,\n totals: aggregateAccountingItems(items),\n series,\n models,\n agents,\n workflows,\n })\n}\n\nexport function buildAiAccountingOverviewFromFragments(\n input: QueryAiAccountingOverviewInput,\n fragments: Iterable<AiAccountingAggregateFragment>\n): AiAccountingOverview {\n const query = normalizeAiAccountingQuery(input)\n const periods = accountingPeriods(query.from, query.to, input.bucket)\n const totals = aggregateFragmentAccumulator()\n const series = new Map<number, AggregateFragmentAccumulator>(\n periods.map((period) => [period.start.getTime(), aggregateFragmentAccumulator()])\n )\n const models = new Map<string, AggregateFragmentAccumulator>()\n const agents = new Map<string, AggregateFragmentAccumulator>()\n const workflows = new Map<string, AggregateFragmentAccumulator>()\n\n for (const fragment of fragments) {\n let target: AggregateFragmentAccumulator\n switch (fragment.dimension) {\n case \"totals\":\n target = totals\n break\n case \"series\": {\n const start = requiredFragmentDate(fragment.start, \"series start\")\n const existing = series.get(start.getTime())\n if (!existing) {\n throw new TypeError(\"[Sixb] AI accounting SQL series returned an unexpected bucket.\")\n }\n target = existing\n break\n }\n case \"model\":\n target = getFragmentAccumulator(\n models,\n JSON.stringify([\n requiredFragmentString(fragment.providerId, \"providerId\"),\n requiredFragmentString(fragment.modelId, \"modelId\"),\n ])\n )\n break\n case \"agent\":\n target = getFragmentAccumulator(agents, requiredFragmentString(fragment.agentId, \"agentId\"))\n break\n case \"workflow\":\n target = getFragmentAccumulator(\n workflows,\n requiredFragmentString(fragment.workflowId, \"workflowId\")\n )\n break\n }\n appendAggregateFragment(target, fragment)\n }\n\n return structuredClone({\n range: { from: query.from, to: query.to },\n bucket: input.bucket,\n totals: finishAggregateFragment(totals),\n series: periods.map((period) => ({\n ...period,\n ...finishAggregateFragment(series.get(period.start.getTime())!),\n })),\n models: [...models]\n .map(([key, value]) => {\n const [providerId, modelId] = JSON.parse(key) as [string, string]\n return { providerId, modelId, ...finishAggregateFragment(value) }\n })\n .sort(compareModelBreakdowns),\n agents: [...agents]\n .map(([agentId, value]) => ({ agentId, ...finishAggregateFragment(value) }))\n .sort(compareAgentBreakdowns),\n workflows: [...workflows]\n .map(([workflowId, value]) => ({ workflowId, ...finishAggregateFragment(value) }))\n .sort(compareWorkflowBreakdowns),\n })\n}\n\nexport function buildAiModelCallAccountingList(\n input: ListAiModelCallAccountingInput,\n source: Iterable<AiAccountingRecordSetItem>\n): ListAiModelCallAccountingResult {\n const query = normalizeAiModelCallAccountingQuery(input)\n const { limit, offset } = query\n const items = Array.from(source)\n .filter((item) => aiAccountingItemMatchesQuery(item, query))\n .map(toAccountingItem)\n .filter(\n (item) =>\n (input.executionId === undefined || item.usage.executionId === input.executionId) &&\n (input.valuationStatus === undefined || item.valuationStatus === input.valuationStatus)\n )\n .sort(compareAccountingItems)\n const page = items.slice(offset, offset + limit)\n return structuredClone({\n items: page,\n hasMore: offset + page.length < items.length,\n total: items.length,\n })\n}\n\nexport function toAccountingItem(item: AiAccountingRecordSetItem): AiModelCallAccountingItem {\n return {\n usage: item.usage,\n ...(item.attribution === undefined ? {} : { attribution: item.attribution }),\n ...(item.cost === undefined ? {} : { cost: item.cost }),\n valuationStatus: item.cost?.status ?? \"unvalued\",\n }\n}\n\nexport function aiAccountingBucketStart(at: Date, bucket: AiAccountingBucket): Date {\n assertDate(at, \"accounting bucket timestamp\")\n assertAiAccountingBucket(bucket)\n const start = new Date(at)\n start.setUTCMinutes(0, 0, 0)\n if (bucket === \"hour\") return start\n start.setUTCHours(0)\n if (bucket === \"day\") return start\n const mondayOffset = (start.getUTCDay() + 6) % 7\n start.setUTCDate(start.getUTCDate() - mondayOffset)\n return start\n}\n\nfunction aggregateAccountingItems(\n items: readonly AiAccountingRecordSetItem[]\n): AiAccountingAggregate {\n return {\n modelCallCount: items.length,\n usage: aggregateAiModelCallUsage(items.map((item) => item.usage.usage)),\n costs: aggregateCosts(items),\n }\n}\n\nfunction aggregateCosts(items: readonly AiAccountingRecordSetItem[]): AiCostSummary {\n const amounts = new Map<string, bigint>()\n let ratedCallCount = 0\n let unpriceableCallCount = 0\n let unvaluedCallCount = 0\n for (const item of items) {\n if (item.cost?.status === \"rated\") {\n ratedCallCount += 1\n addAmount(amounts, item.cost.money.currency, item.cost.money.amountNanos)\n } else if (item.cost?.status === \"unpriceable\") {\n unpriceableCallCount += 1\n } else {\n unvaluedCallCount += 1\n }\n }\n return {\n amounts: [...amounts]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([currency, amountNanos]) => ({ currency, amountNanos: amountNanos.toString() })),\n ratedCallCount,\n unpriceableCallCount,\n unvaluedCallCount,\n }\n}\n\nconst AGGREGATE_USAGE_FIELDS = [\n \"inputTokens\",\n \"outputTokens\",\n \"uncachedInputTokens\",\n \"cacheReadInputTokens\",\n \"cacheWriteInputTokens\",\n \"textOutputTokens\",\n \"reasoningOutputTokens\",\n] as const\n\ntype AggregateUsageField = (typeof AGGREGATE_USAGE_FIELDS)[number]\n\ninterface AggregateFragmentAccumulator {\n modelCallCount: bigint\n reportedUsageCallCount: bigint\n usage: Record<AggregateUsageField, { presentCallCount: bigint; total: bigint }>\n amounts: Map<string, bigint>\n ratedCallCount: bigint\n unpriceableCallCount: bigint\n unvaluedCallCount: bigint\n}\n\nfunction aggregateFragmentAccumulator(): AggregateFragmentAccumulator {\n return {\n modelCallCount: 0n,\n reportedUsageCallCount: 0n,\n usage: Object.fromEntries(\n AGGREGATE_USAGE_FIELDS.map((field) => [field, { presentCallCount: 0n, total: 0n }])\n ) as AggregateFragmentAccumulator[\"usage\"],\n amounts: new Map(),\n ratedCallCount: 0n,\n unpriceableCallCount: 0n,\n unvaluedCallCount: 0n,\n }\n}\n\nfunction getFragmentAccumulator(\n values: Map<string, AggregateFragmentAccumulator>,\n key: string\n): AggregateFragmentAccumulator {\n const existing = values.get(key)\n if (existing) return existing\n const created = aggregateFragmentAccumulator()\n values.set(key, created)\n return created\n}\n\nfunction appendAggregateFragment(\n target: AggregateFragmentAccumulator,\n fragment: AiAccountingAggregateFragment\n): void {\n target.modelCallCount += naturalBigInt(fragment.modelCallCount, \"modelCallCount\")\n target.reportedUsageCallCount += naturalBigInt(\n fragment.usage.reportedCallCount,\n \"reported usage call count\"\n )\n for (const field of AGGREGATE_USAGE_FIELDS) {\n const source = fragment.usage[field]\n const presentCallCount = naturalBigInt(source.presentCallCount, `${field} call count`)\n target.usage[field].presentCallCount += presentCallCount\n if (source.total !== null) {\n target.usage[field].total += naturalBigInt(source.total, `${field} total`)\n } else if (presentCallCount !== 0n) {\n throw new TypeError(`[Sixb] AI accounting SQL ${field} total is missing.`)\n }\n }\n target.ratedCallCount += naturalBigInt(fragment.costs.ratedCallCount, \"rated call count\")\n target.unpriceableCallCount += naturalBigInt(\n fragment.costs.unpriceableCallCount,\n \"unpriceable call count\"\n )\n target.unvaluedCallCount += naturalBigInt(fragment.costs.unvaluedCallCount, \"unvalued call count\")\n if (fragment.costs.amount) {\n addAmount(target.amounts, fragment.costs.amount.currency, fragment.costs.amount.amountNanos)\n }\n}\n\nfunction finishAggregateFragment(value: AggregateFragmentAccumulator): AiAccountingAggregate {\n const classifiedCallCount =\n value.ratedCallCount + value.unpriceableCallCount + value.unvaluedCallCount\n if (\n classifiedCallCount !== value.modelCallCount ||\n value.reportedUsageCallCount > value.modelCallCount ||\n AGGREGATE_USAGE_FIELDS.some(\n (field) => value.usage[field].presentCallCount > value.modelCallCount\n )\n ) {\n throw new TypeError(\"[Sixb] AI accounting SQL aggregate counts are inconsistent.\")\n }\n const modelCallCount = safeAggregateNumber(value.modelCallCount, \"model-call count\")\n const usageInput: Partial<Record<AggregateUsageField, number>> = {}\n if (value.modelCallCount > 0n) {\n for (const field of AGGREGATE_USAGE_FIELDS) {\n const aggregate = value.usage[field]\n if (aggregate.presentCallCount === value.modelCallCount) {\n usageInput[field] = safeAggregateNumber(aggregate.total, field)\n }\n }\n }\n let usage: AiModelCallUsage = normalizeAiModelCallUsage(usageInput)\n if (usage.reportingStatus === \"unavailable\" && value.reportedUsageCallCount > 0n) {\n usage = { ...usage, reportingStatus: \"partial\" }\n }\n return {\n modelCallCount,\n usage,\n costs: {\n amounts: [...value.amounts]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([currency, amountNanos]) => ({ currency, amountNanos: amountNanos.toString() })),\n ratedCallCount: safeAggregateNumber(value.ratedCallCount, \"rated call count\"),\n unpriceableCallCount: safeAggregateNumber(\n value.unpriceableCallCount,\n \"unpriceable call count\"\n ),\n unvaluedCallCount: safeAggregateNumber(value.unvaluedCallCount, \"unvalued call count\"),\n },\n }\n}\n\nfunction naturalBigInt(value: string, field: string): bigint {\n if (!/^(0|[1-9]\\d*)$/.test(value)) {\n throw new TypeError(`[Sixb] AI accounting SQL ${field} must be a natural integer.`)\n }\n return BigInt(value)\n}\n\nfunction safeAggregateNumber(value: bigint, field: string): number {\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new TypeError(`[Sixb] AI accounting ${field} exceeds the safe integer range.`)\n }\n return Number(value)\n}\n\nfunction requiredFragmentString(value: string | undefined, field: string): string {\n if (value === undefined || value.length === 0) {\n throw new TypeError(`[Sixb] AI accounting SQL ${field} is missing.`)\n }\n return value\n}\n\nfunction requiredFragmentDate(value: Date | undefined, field: string): Date {\n if (value === undefined) throw new TypeError(`[Sixb] AI accounting SQL ${field} is missing.`)\n assertDate(value, field)\n return value\n}\n\nfunction accountingPeriods(\n from: Date,\n to: Date,\n bucket: AiAccountingBucket\n): Array<{ start: Date; end: Date }> {\n const result: Array<{ start: Date; end: Date }> = []\n let cursor = aiAccountingBucketStart(from, bucket)\n while (cursor.getTime() < to.getTime()) {\n if (result.length >= MAX_CHART_BUCKETS) {\n throw new RangeError(`[Sixb] AI accounting query exceeds ${MAX_CHART_BUCKETS} chart buckets.`)\n }\n const next = nextBucket(cursor, bucket)\n result.push({ start: new Date(cursor), end: next })\n cursor = next\n }\n return result\n}\n\nfunction nextBucket(start: Date, bucket: AiAccountingBucket): Date {\n const next = new Date(start)\n if (bucket === \"hour\") next.setUTCHours(next.getUTCHours() + 1)\n else if (bucket === \"day\") next.setUTCDate(next.getUTCDate() + 1)\n else next.setUTCDate(next.getUTCDate() + 7)\n return next\n}\n\nfunction appendGrouped(\n groups: Map<string, AiAccountingRecordSetItem[]>,\n key: string,\n item: AiAccountingRecordSetItem\n): void {\n const existing = groups.get(key)\n if (existing) existing.push(item)\n else groups.set(key, [item])\n}\n\nfunction addAmount(amounts: Map<string, bigint>, currency: string, amountNanos: string): void {\n amounts.set(currency, (amounts.get(currency) ?? 0n) + BigInt(amountNanos))\n}\n\nfunction normalizePage(\n requestedLimit: number | undefined,\n requestedOffset: number | undefined\n): { limit: number; offset: number } {\n const limit = requestedLimit ?? DEFAULT_MODEL_CALL_PAGE_SIZE\n const offset = requestedOffset ?? 0\n if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_MODEL_CALL_PAGE_SIZE) {\n throw new TypeError(\n `[Sixb] AI accounting list limit must be an integer between 1 and ${MAX_MODEL_CALL_PAGE_SIZE}.`\n )\n }\n if (!Number.isSafeInteger(offset) || offset < 0) {\n throw new TypeError(\"[Sixb] AI accounting list offset must be a non-negative integer.\")\n }\n return { limit, offset }\n}\n\nfunction compareAccountingItems(\n left: AiModelCallAccountingItem,\n right: AiModelCallAccountingItem\n): number {\n return (\n right.usage.occurredAt.getTime() - left.usage.occurredAt.getTime() ||\n left.usage.id.localeCompare(right.usage.id)\n )\n}\n\nfunction compareAgentBreakdowns(\n left: AiAccountingAgentBreakdown,\n right: AiAccountingAgentBreakdown\n): number {\n return right.modelCallCount - left.modelCallCount || left.agentId.localeCompare(right.agentId)\n}\n\nfunction compareWorkflowBreakdowns(\n left: AiAccountingWorkflowBreakdown,\n right: AiAccountingWorkflowBreakdown\n): number {\n return (\n right.modelCallCount - left.modelCallCount || left.workflowId.localeCompare(right.workflowId)\n )\n}\n\nfunction compareModelBreakdowns(\n left: AiAccountingModelBreakdown,\n right: AiAccountingModelBreakdown\n): number {\n return (\n right.modelCallCount - left.modelCallCount ||\n left.providerId.localeCompare(right.providerId) ||\n left.modelId.localeCompare(right.modelId)\n )\n}\n\nfunction assertAiAccountingBucket(bucket: AiAccountingBucket): void {\n if (bucket !== \"hour\" && bucket !== \"day\" && bucket !== \"week\") {\n throw new TypeError(\"[Sixb] AI accounting bucket must be hour, day, or week.\")\n }\n}\n\nfunction assertDate(value: Date, label: string): void {\n if (!(value instanceof Date) || !Number.isFinite(value.getTime())) {\n throw new TypeError(`[Sixb] AI ${label} must be a valid Date.`)\n }\n}\n\nfunction assertNonBlank(value: string, label: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`[Sixb] AI ${label} must be nonblank.`)\n }\n}\n",
10
+ "import type { AiModelCallUsage, AiModelCallUsageRecord } from \"../ai-usage\"\nimport { normalizeAiModelCallUsage } from \"../ai-usage\"\nimport type {\n AiBillableMeter,\n AiBillingIdentity,\n AiCostComponent,\n AiModelCallCostRecord,\n AiPriceSource,\n AiPricingContext,\n AiRatedModelCallCostRecord,\n AiUnpriceableModelCallCostRecord,\n AiUnpriceableReason,\n} from \"./types\"\n\nconst SIGNED_INT64_MAX = 9_223_372_036_854_775_807n\nconst TOKENS_PER_MILLION = 1_000_000n\nconst HALF_MILLION = TOKENS_PER_MILLION / 2n\nconst MAX_NUMERIC_TEXT_LENGTH = 128\nconst METER_ORDER: Readonly<Record<AiBillableMeter, number>> = {\n \"tokens.input.total\": 0,\n \"tokens.input.uncached\": 1,\n \"tokens.input.cacheRead\": 2,\n \"tokens.input.cacheWrite\": 3,\n \"tokens.output.total\": 4,\n \"tokens.output.text\": 5,\n \"tokens.output.reasoning\": 6,\n}\nconst METERS = new Set(Object.keys(METER_ORDER))\nconst UNPRICEABLE_REASONS = new Set<AiUnpriceableReason>([\n \"missingBillingIdentity\",\n \"missingCatalogEntry\",\n \"missingUsageMeter\",\n \"unsupportedPricingDimension\",\n \"invalidUsageForFormula\",\n])\nconst CONTEXT_STRING_FIELDS = [\n \"serviceTier\",\n \"region\",\n \"inferenceGeo\",\n \"routedProviderId\",\n \"deploymentId\",\n \"inferenceProfileId\",\n \"mode\",\n] as const\n\nexport function normalizeAiPricingContext(input: AiPricingContext): AiPricingContext {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) {\n throw new TypeError(\"[Sixb] AI pricing context must be an object.\")\n }\n const result: Record<string, string | boolean | number> = {}\n for (const field of CONTEXT_STRING_FIELDS) {\n const value = input[field]\n if (value !== undefined) {\n assertNonBlank(value, `pricingContext.${field}`)\n result[field] = value\n }\n }\n if (input.batch !== undefined) {\n if (typeof input.batch !== \"boolean\") {\n throw new TypeError(\"[Sixb] AI pricingContext.batch must be boolean.\")\n }\n result.batch = input.batch\n }\n if (input.cacheWriteTtlSeconds !== undefined) {\n if (!Number.isSafeInteger(input.cacheWriteTtlSeconds) || input.cacheWriteTtlSeconds <= 0) {\n throw new TypeError(\n \"[Sixb] AI pricingContext.cacheWriteTtlSeconds must be a positive safe integer.\"\n )\n }\n result.cacheWriteTtlSeconds = input.cacheWriteTtlSeconds\n }\n return result\n}\n\nexport function normalizeAiModelCallCostRecord(\n input: AiModelCallCostRecord\n): AiModelCallCostRecord {\n assertNonBlank(input.projectId, \"cost record projectId\")\n assertNonBlank(input.usageRecordId, \"cost record usageRecordId\")\n const base = {\n projectId: input.projectId,\n usageRecordId: input.usageRecordId,\n pricingContext: normalizeAiPricingContext(input.pricingContext),\n priceSource: normalizePriceSource(input.priceSource),\n ratedAt: cloneDate(input.ratedAt, \"cost record ratedAt\"),\n }\n\n if (input.status === \"rated\") return normalizeRatedCost(input, base)\n if (input.status === \"unpriceable\") return normalizeUnpriceableCost(input, base)\n throw new TypeError(\"[Sixb] AI cost status is invalid.\")\n}\n\n/** Verify that a normalized valuation's billed quantities describe its usage record. */\nexport function aiModelCallCostMatchesUsage(\n record: AiModelCallCostRecord,\n usageRecord: AiModelCallUsageRecord\n): boolean {\n if (record.projectId !== usageRecord.projectId || record.usageRecordId !== usageRecord.id) {\n return false\n }\n if (record.status === \"unpriceable\") return true\n\n const usage = normalizeAiModelCallUsage(usageRecord.usage)\n const components = new Map(record.components.map((component) => [component.meter, component]))\n return (\n inputComponentsMatchUsage(components, usage) && outputComponentsMatchUsage(components, usage)\n )\n}\n\nfunction inputComponentsMatchUsage(\n components: ReadonlyMap<AiBillableMeter, AiCostComponent>,\n usage: AiModelCallUsage\n): boolean {\n if (usage.inputTokens === undefined) return false\n const total = components.get(\"tokens.input.total\")\n const partitions = [\n [\"tokens.input.uncached\", usage.uncachedInputTokens],\n [\"tokens.input.cacheRead\", usage.cacheReadInputTokens],\n [\"tokens.input.cacheWrite\", usage.cacheWriteInputTokens],\n ] as const\n const presentPartitions = partitions.filter(([meter]) => components.has(meter))\n\n if (total) {\n return presentPartitions.length === 0 && BigInt(total.quantity) === BigInt(usage.inputTokens)\n }\n if (presentPartitions.length === 0) return false\n\n let quantity = 0n\n for (const [meter, expected] of presentPartitions) {\n if (expected === undefined) return false\n const component = components.get(meter)!\n if (BigInt(component.quantity) !== BigInt(expected)) return false\n quantity += BigInt(component.quantity)\n }\n return quantity === BigInt(usage.inputTokens)\n}\n\nfunction outputComponentsMatchUsage(\n components: ReadonlyMap<AiBillableMeter, AiCostComponent>,\n usage: AiModelCallUsage\n): boolean {\n if (usage.outputTokens === undefined) return false\n const total = components.get(\"tokens.output.total\")\n const partitions = [\n [\"tokens.output.text\", usage.textOutputTokens],\n [\"tokens.output.reasoning\", usage.reasoningOutputTokens],\n ] as const\n const presentPartitions = partitions.filter(([meter]) => components.has(meter))\n\n if (total) {\n return presentPartitions.length === 0 && BigInt(total.quantity) === BigInt(usage.outputTokens)\n }\n if (presentPartitions.length === 0) return false\n\n let quantity = 0n\n for (const [meter, expected] of presentPartitions) {\n if (expected === undefined) return false\n const component = components.get(meter)!\n if (BigInt(component.quantity) !== BigInt(expected)) return false\n quantity += BigInt(component.quantity)\n }\n return quantity === BigInt(usage.outputTokens)\n}\n\nfunction normalizeRatedCost(\n input: AiRatedModelCallCostRecord,\n base: Pick<\n AiRatedModelCallCostRecord,\n \"projectId\" | \"usageRecordId\" | \"pricingContext\" | \"priceSource\" | \"ratedAt\"\n >\n): AiRatedModelCallCostRecord {\n const billingIdentity = normalizeBillingIdentity(input.billingIdentity)\n const components = input.components.map(normalizeCostComponent).sort(compareComponents)\n if (components.length === 0) throw new TypeError(\"[Sixb] AI rated cost requires components.\")\n if (new Set(components.map((component) => component.meter)).size !== components.length) {\n throw new TypeError(\"[Sixb] AI rated cost cannot contain duplicate meters.\")\n }\n const amountNanos = parseNonnegativeInt64(input.money.amountNanos, \"money amountNanos\").toString()\n if (amountNanos !== sumComponents(components)) {\n throw new TypeError(\"[Sixb] AI cost total does not equal its component charges.\")\n }\n return {\n ...base,\n status: \"rated\",\n billingIdentity,\n money: { currency: normalizeCurrency(input.money.currency), amountNanos },\n components,\n }\n}\n\nfunction normalizeUnpriceableCost(\n input: AiUnpriceableModelCallCostRecord,\n base: Pick<\n AiUnpriceableModelCallCostRecord,\n \"projectId\" | \"usageRecordId\" | \"pricingContext\" | \"priceSource\" | \"ratedAt\"\n >\n): AiUnpriceableModelCallCostRecord {\n if (!UNPRICEABLE_REASONS.has(input.reason)) {\n throw new TypeError(`[Sixb] AI unpriceable reason '${String(input.reason)}' is invalid.`)\n }\n const billingIdentity = input.billingIdentity\n ? normalizeBillingIdentity(input.billingIdentity)\n : undefined\n if (input.reason === \"missingBillingIdentity\" && billingIdentity !== undefined) {\n throw new TypeError(\"[Sixb] AI missingBillingIdentity cannot contain a billing identity.\")\n }\n if (input.reason !== \"missingBillingIdentity\" && billingIdentity === undefined) {\n throw new TypeError(`[Sixb] AI ${input.reason} requires a billing identity.`)\n }\n const missingMeters = normalizeMissingMeters(input.missingMeters)\n if (input.reason === \"missingUsageMeter\" && !missingMeters) {\n throw new TypeError(\"[Sixb] AI missingUsageMeter requires missingMeters.\")\n }\n return {\n ...base,\n status: \"unpriceable\",\n ...(billingIdentity ? { billingIdentity } : {}),\n reason: input.reason,\n ...(missingMeters ? { missingMeters } : {}),\n }\n}\n\nfunction normalizeCostComponent(input: AiCostComponent): AiCostComponent {\n if (!METERS.has(input.meter)) {\n throw new TypeError(`[Sixb] AI cost meter '${String(input.meter)}' is invalid.`)\n }\n const expected = calculateComponent(input.meter, input.quantity, input.rateAmountNanosPerMillion)\n if (expected.chargeAmountNanos !== input.chargeAmountNanos) {\n throw new TypeError(`[Sixb] AI cost component '${input.meter}' charge is invalid.`)\n }\n return expected\n}\n\nfunction calculateComponent(\n meter: AiBillableMeter,\n quantity: number | string,\n rateAmountNanosPerMillion: string\n): AiCostComponent {\n const normalizedQuantity = parseQuantity(quantity, `${meter} quantity`)\n const rate = parseNonnegativeInt64(rateAmountNanosPerMillion, `${meter} rate`)\n const charge = (normalizedQuantity * rate + HALF_MILLION) / TOKENS_PER_MILLION\n assertSignedInt64(charge, `${meter} charge`)\n return {\n meter,\n quantity: normalizedQuantity.toString(),\n rateAmountNanosPerMillion: rate.toString(),\n chargeAmountNanos: charge.toString(),\n }\n}\n\nfunction normalizePriceSource(input: AiPriceSource): AiPriceSource {\n assertNonBlank(input.sourceId, \"price sourceId\")\n assertNonBlank(input.sourceEntryId, \"price sourceEntryId\")\n assertNonBlank(input.sourceVersion, \"price sourceVersion\")\n assertNonBlank(input.sourceUrl, \"price sourceUrl\")\n return { ...input, observedAt: cloneDate(input.observedAt, \"price source observedAt\") }\n}\n\nfunction normalizeBillingIdentity(input: AiBillingIdentity): AiBillingIdentity {\n assertNonBlank(input.providerId, \"billingIdentity.providerId\")\n assertNonBlank(input.modelId, \"billingIdentity.modelId\")\n return { providerId: input.providerId, modelId: input.modelId }\n}\n\nfunction normalizeMissingMeters(\n input: readonly AiBillableMeter[] | undefined\n): readonly AiBillableMeter[] | undefined {\n if (!input?.length) return undefined\n const result = [...new Set(input)]\n for (const meter of result) {\n if (!METERS.has(meter)) throw new TypeError(`[Sixb] AI missing meter '${meter}' is invalid.`)\n }\n return result.sort((left, right) => METER_ORDER[left] - METER_ORDER[right])\n}\n\nfunction sumComponents(components: readonly AiCostComponent[]): string {\n let total = 0n\n for (const component of components) {\n total += parseNonnegativeInt64(component.chargeAmountNanos, \"component charge\")\n assertSignedInt64(total, \"cost total\")\n }\n return total.toString()\n}\n\nfunction parseQuantity(value: number | string, field: string): bigint {\n if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new TypeError(`[Sixb] AI ${field} must be a non-negative safe integer.`)\n }\n return BigInt(value)\n }\n return parseNonnegativeInt64(value, field)\n}\n\nfunction parseNonnegativeInt64(value: string, field: string): bigint {\n if (\n typeof value !== \"string\" ||\n value.length === 0 ||\n value.length > MAX_NUMERIC_TEXT_LENGTH ||\n !/^\\d+$/.test(value)\n ) {\n throw new TypeError(`[Sixb] AI ${field} must be a non-negative integer string.`)\n }\n const parsed = BigInt(value)\n assertSignedInt64(parsed, field)\n return parsed\n}\n\nfunction compareComponents(left: AiCostComponent, right: AiCostComponent): number {\n return METER_ORDER[left.meter] - METER_ORDER[right.meter]\n}\n\nfunction normalizeCurrency(value: string): string {\n if (!/^[A-Z]{3}$/.test(value)) {\n throw new TypeError(\"[Sixb] AI currency must be a three-letter uppercase code.\")\n }\n return value\n}\n\nfunction assertSignedInt64(value: bigint, field: string): void {\n if (value < 0n || value > SIGNED_INT64_MAX) {\n throw new TypeError(`[Sixb] AI ${field} exceeds the signed 64-bit range.`)\n }\n}\n\nfunction assertNonBlank(value: string, field: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`[Sixb] AI ${field} must be nonblank.`)\n }\n}\n\nfunction cloneDate(value: Date, field: string): Date {\n if (!(value instanceof Date) || !Number.isFinite(value.getTime())) {\n throw new Typ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SAAS,OAAO,KAAK;AAAA,EAC3B,kBAAkB,QAAQ,KAAK;AAAA,EAC/B,OAAO;AAAA;AAGT,SAAS,iBAAiB,CAAC,MAAuB,OAAgC;AAAA,EAChF,OAAO,YAAY,KAAK,SAAS,YAAY,MAAM;AAAA;AAGrD,SAAS,iBAAiB,CAAC,OAAuB;AAAA,EAChD,IAAI,CAAC,aAAa,KAAK,KAAK,GAAG;AAAA,IAC7B,MAAM,IAAI,UAAU,2DAA2D;AAAA,EACjF;AAAA,EACA,OAAO;AAAA;AAGT,SAAS,iBAAiB,CAAC,OAAe,OAAqB;AAAA,EAC7D,IAAI,QAAQ,MAAM,QAAQ,kBAAkB;AAAA,IAC1C,MAAM,IAAI,UAAU,aAAa,wCAAwC;AAAA,EAC3E;AAAA;AAGF,SAAS,eAAc,CAAC,OAAe,OAAqB;AAAA,EAC1D,IAAI,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,WAAW,GAAG;AAAA,IAC1D,MAAM,IAAI,UAAU,aAAa,yBAAyB;AAAA,EAC5D;AAAA;AAGF,SAAS,SAAS,CAAC,OAAa,OAAqB;AAAA,EACnD,IAAI,EAAE,iBAAiB,SAAS,CAAC,OAAO,SAAS,MAAM,QAAQ,CAAC,GAAG;AAAA,IACjE,MAAM,IAAI,UAAU,aAAa,6BAA6B;AAAA,EAChE;AAAA,EACA,OAAO,IAAI,KAAK,KAAK;AAAA;",
13
+ "debugId": "57B2CBFC0C6F2A5664756E2164756E21",
14
+ "names": []
15
+ }
@@ -2,10 +2,10 @@
2
2
  import {
3
3
  AuthStorageError,
4
4
  SYSTEM_PRINCIPAL
5
- } from "./chunk-jaj13078.js";
5
+ } from "./chunk-d2adj15j.js";
6
6
  import {
7
7
  resolveAuthorizationContext
8
- } from "./chunk-34bqh420.js";
8
+ } from "./chunk-4z3n1dzt.js";
9
9
 
10
10
  // src/agents/authority.ts
11
11
  function agentServiceAccountId(agentId) {
@@ -1,7 +1,7 @@
1
1
  // @bun
2
2
  import {
3
3
  agentServiceAccountId
4
- } from "./chunk-qvybnnpe.js";
4
+ } from "./chunk-n5x5y80a.js";
5
5
  import {
6
6
  findAgentRunExecution,
7
7
  findPrimitiveRunExecution
@@ -0,0 +1,133 @@
1
+ // @bun
2
+ import {
3
+ agentServiceAccountId
4
+ } from "./chunk-n5x5y80a.js";
5
+ import {
6
+ findAgentRunExecution
7
+ } from "./chunk-t9xghkva.js";
8
+
9
+ // src/storage/agents/errors.ts
10
+ class AgentStorageError extends Error {
11
+ code;
12
+ name = "AgentStorageError";
13
+ constructor(code, message) {
14
+ super(message);
15
+ this.code = code;
16
+ }
17
+ }
18
+
19
+ // src/storage/agents/provider.ts
20
+ async function assertAgentRunExecution(input) {
21
+ const execution = await findAgentRunExecution({
22
+ executions: input.executions,
23
+ projectId: input.projectId,
24
+ executionId: input.executionId,
25
+ runId: input.runId,
26
+ serviceAccountId: agentServiceAccountId(input.agentId)
27
+ });
28
+ if (!execution) {
29
+ throw new AgentStorageError("invalid_input", `[Sixb] Execution '${input.executionId}' does not authorize Agent run '${input.runId}'.`);
30
+ }
31
+ }
32
+ function assertCreateAgentContextCheckpointInput(input, prefix = "Sixb") {
33
+ for (const [name, value] of [
34
+ ["id", input.id],
35
+ ["projectId", input.projectId],
36
+ ["threadId", input.threadId],
37
+ ["createdByRunId", input.createdByRunId],
38
+ ["executionToken", input.executionToken],
39
+ ["summary", input.summary],
40
+ ["summaryModelId", input.summaryModelId]
41
+ ]) {
42
+ if (value.trim().length === 0) {
43
+ throw new AgentStorageError("invalid_input", `[${prefix}] Agent context checkpoint '${name}' must not be empty.`);
44
+ }
45
+ }
46
+ if (input.summaryFormatVersion !== 1) {
47
+ throw new AgentStorageError("invalid_input", `[${prefix}] Agent context checkpoint summary format version must be 1.`);
48
+ }
49
+ if (input.reason !== "threshold" && input.reason !== "overflow") {
50
+ throw new AgentStorageError("invalid_input", `[${prefix}] Agent context checkpoint reason must be 'threshold' or 'overflow'.`);
51
+ }
52
+ if (input.expectedPreviousCheckpointId !== null && input.expectedPreviousCheckpointId.trim().length === 0) {
53
+ throw new AgentStorageError("invalid_input", `[${prefix}] Agent context checkpoint expected previous id must not be empty.`);
54
+ }
55
+ if (input.createdAt && !Number.isFinite(input.createdAt.getTime())) {
56
+ throw new AgentStorageError("invalid_input", `[${prefix}] Agent context checkpoint createdAt must be a valid date.`);
57
+ }
58
+ for (const [name, value, minimum] of [
59
+ ["expectedHeadSeq", input.expectedHeadSeq, 1],
60
+ ["summarizedThroughSeq", input.summarizedThroughSeq, 1],
61
+ ["observedHeadSeq", input.observedHeadSeq, 1],
62
+ ["estimatedInputTokensBefore", input.estimatedInputTokensBefore, 0],
63
+ ["estimatedInputTokensAfter", input.estimatedInputTokensAfter, 0]
64
+ ]) {
65
+ if (!Number.isSafeInteger(value) || value < minimum) {
66
+ throw new AgentStorageError("invalid_input", `[${prefix}] Agent context checkpoint '${name}' must be a safe integer greater than or equal to ${minimum}.`);
67
+ }
68
+ }
69
+ if (input.observedHeadSeq !== input.expectedHeadSeq) {
70
+ throw new AgentStorageError("invalid_input", `[${prefix}] Agent context checkpoint observed head must equal its expected message head.`);
71
+ }
72
+ if (input.summarizedThroughSeq >= input.observedHeadSeq) {
73
+ throw new AgentStorageError("invalid_input", `[${prefix}] Agent context checkpoint must retain the triggering head message.`);
74
+ }
75
+ }
76
+ function assertAgentContextCheckpointAuthority(input) {
77
+ const { create, run, thread } = input;
78
+ const prefix = input.prefix ?? "Sixb";
79
+ if (!run) {
80
+ throw new AgentStorageError("run_not_found", `[${prefix}] Agent run '${create.createdByRunId}' not found for project '${create.projectId}'.`);
81
+ }
82
+ if (!thread) {
83
+ throw new AgentStorageError("thread_not_found", `[${prefix}] Agent thread '${create.threadId}' not found for project '${create.projectId}'.`);
84
+ }
85
+ if (run.threadId !== create.threadId) {
86
+ throw new AgentStorageError("invalid_input", `[${prefix}] Agent run '${run.id}' does not belong to thread '${create.threadId}'.`);
87
+ }
88
+ if (run.status !== "running") {
89
+ throw new AgentStorageError("invalid_state", `[${prefix}] Agent run '${run.id}' is not running (status '${run.status}').`);
90
+ }
91
+ if (!run.execution || run.execution.token !== create.executionToken) {
92
+ throw new AgentStorageError("execution_lost", `[${prefix}] Execution token is no longer current on agent run '${run.id}'.`);
93
+ }
94
+ if (thread.activeRunId !== run.id) {
95
+ throw new AgentStorageError("invalid_state", `[${prefix}] Agent run '${run.id}' no longer owns thread '${thread.id}'.`);
96
+ }
97
+ }
98
+ function assertAgentContextCheckpointAnchors(input) {
99
+ const { create, latest, headSeq, firstRetained } = input;
100
+ const prefix = input.prefix ?? "Sixb";
101
+ if (headSeq !== create.expectedHeadSeq) {
102
+ throw new AgentStorageError("invalid_state", `[${prefix}] Agent thread '${create.threadId}' message head changed from ${create.expectedHeadSeq} to ${headSeq}.`);
103
+ }
104
+ const latestId = latest?.id ?? null;
105
+ if (latestId !== create.expectedPreviousCheckpointId) {
106
+ throw new AgentStorageError("invalid_state", `[${prefix}] Agent thread '${create.threadId}' checkpoint head changed.`);
107
+ }
108
+ if (latest && create.summarizedThroughSeq <= latest.summarizedThroughSeq) {
109
+ throw new AgentStorageError("invalid_input", `[${prefix}] Agent context checkpoint boundary must advance beyond sequence ${latest.summarizedThroughSeq}.`);
110
+ }
111
+ if (!firstRetained || firstRetained.seq !== create.summarizedThroughSeq + 1) {
112
+ throw new AgentStorageError("invalid_state", `[${prefix}] Agent context checkpoint boundary does not align with stored thread messages.`);
113
+ }
114
+ if (firstRetained.role !== "user") {
115
+ throw new AgentStorageError("invalid_input", `[${prefix}] Agent context checkpoint must retain a complete turn beginning with a user message.`);
116
+ }
117
+ }
118
+ function assertAgentContextCheckpointReplayState(input) {
119
+ const prefix = input.prefix ?? "Sixb";
120
+ if (input.headSeq !== input.create.expectedHeadSeq) {
121
+ throw new AgentStorageError("invalid_state", `[${prefix}] Agent thread '${input.create.threadId}' message head changed from ${input.create.expectedHeadSeq} to ${input.headSeq}.`);
122
+ }
123
+ if (input.latest?.id !== input.existing.id) {
124
+ throw new AgentStorageError("invalid_state", `[${prefix}] Agent thread '${input.create.threadId}' checkpoint head changed after '${input.existing.id}'.`);
125
+ }
126
+ }
127
+ function agentContextCheckpointMatchesCreateInput(record, input) {
128
+ return record.id === input.id && record.projectId === input.projectId && record.threadId === input.threadId && record.createdByRunId === input.createdByRunId && (record.previousCheckpointId ?? null) === input.expectedPreviousCheckpointId && record.reason === input.reason && record.summary === input.summary && record.summaryFormatVersion === input.summaryFormatVersion && record.summarizedThroughSeq === input.summarizedThroughSeq && record.observedHeadSeq === input.observedHeadSeq && record.estimatedInputTokensBefore === input.estimatedInputTokensBefore && record.estimatedInputTokensAfter === input.estimatedInputTokensAfter && record.summaryModelId === input.summaryModelId;
129
+ }
130
+
131
+ export { AgentStorageError, assertAgentRunExecution, assertCreateAgentContextCheckpointInput, assertAgentContextCheckpointAuthority, assertAgentContextCheckpointAnchors, assertAgentContextCheckpointReplayState, agentContextCheckpointMatchesCreateInput };
132
+
133
+ //# debugId=C4E16AF3EE9252A464756E2164756E21
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/storage/agents/errors.ts", "../src/storage/agents/provider.ts"],
4
+ "sourcesContent": [
5
+ "export type AgentStorageErrorCode =\n | \"thread_not_found\"\n | \"active_run_exists\"\n | \"run_not_found\"\n | \"invalid_input\"\n | \"invalid_state\"\n | \"execution_lost\"\n | \"duplicate_id\"\n\n/**\n * Error for agent-storage invariants and invalid state transitions (single-flight, execution\n * ownership, run lifecycle, message append). Callers branch on `code` rather than message text.\n */\nexport class AgentStorageError extends Error {\n readonly name = \"AgentStorageError\"\n\n constructor(\n readonly code: AgentStorageErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n",
6
+ "import { agentServiceAccountId } from \"../../agents/authority\"\nimport type { ExecutionStorage } from \"../executions\"\nimport { findAgentRunExecution } from \"../executions/run-link\"\nimport { AgentStorageError } from \"./errors\"\nimport type {\n AgentContextCheckpointRecord,\n AgentMessageRecord,\n AgentRunRecord,\n AgentThreadRecord,\n CreateAgentContextCheckpointInput,\n} from \"./types\"\n\n/** Validate the semantic link between a conversational Agent run and its immutable execution. */\nexport async function assertAgentRunExecution(input: {\n readonly executions: ExecutionStorage\n readonly projectId: string\n readonly executionId: string\n readonly runId: string\n readonly agentId: string\n}): Promise<void> {\n const execution = await findAgentRunExecution({\n executions: input.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.runId,\n serviceAccountId: agentServiceAccountId(input.agentId),\n })\n if (!execution) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[Sixb] Execution '${input.executionId}' does not authorize Agent run '${input.runId}'.`\n )\n }\n}\n\n/** Validate provider-independent checkpoint fields before entering a storage critical section. */\nexport function assertCreateAgentContextCheckpointInput(\n input: CreateAgentContextCheckpointInput,\n prefix = \"Sixb\"\n): void {\n for (const [name, value] of [\n [\"id\", input.id],\n [\"projectId\", input.projectId],\n [\"threadId\", input.threadId],\n [\"createdByRunId\", input.createdByRunId],\n [\"executionToken\", input.executionToken],\n [\"summary\", input.summary],\n [\"summaryModelId\", input.summaryModelId],\n ] as const) {\n if (value.trim().length === 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint '${name}' must not be empty.`\n )\n }\n }\n\n if (input.summaryFormatVersion !== 1) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint summary format version must be 1.`\n )\n }\n if (input.reason !== \"threshold\" && input.reason !== \"overflow\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint reason must be 'threshold' or 'overflow'.`\n )\n }\n if (\n input.expectedPreviousCheckpointId !== null &&\n input.expectedPreviousCheckpointId.trim().length === 0\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint expected previous id must not be empty.`\n )\n }\n if (input.createdAt && !Number.isFinite(input.createdAt.getTime())) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint createdAt must be a valid date.`\n )\n }\n\n for (const [name, value, minimum] of [\n [\"expectedHeadSeq\", input.expectedHeadSeq, 1],\n [\"summarizedThroughSeq\", input.summarizedThroughSeq, 1],\n [\"observedHeadSeq\", input.observedHeadSeq, 1],\n [\"estimatedInputTokensBefore\", input.estimatedInputTokensBefore, 0],\n [\"estimatedInputTokensAfter\", input.estimatedInputTokensAfter, 0],\n ] as const) {\n if (!Number.isSafeInteger(value) || value < minimum) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint '${name}' must be a safe integer greater than or equal to ${minimum}.`\n )\n }\n }\n\n if (input.observedHeadSeq !== input.expectedHeadSeq) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint observed head must equal its expected message head.`\n )\n }\n if (input.summarizedThroughSeq >= input.observedHeadSeq) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint must retain the triggering head message.`\n )\n }\n}\n\n/** Assert that the current delivery still owns the active conversational run. */\nexport function assertAgentContextCheckpointAuthority(input: {\n readonly create: CreateAgentContextCheckpointInput\n readonly run: AgentRunRecord | null\n readonly thread: AgentThreadRecord | null\n readonly prefix?: string\n}): asserts input is typeof input & {\n readonly run: AgentRunRecord\n readonly thread: AgentThreadRecord\n} {\n const { create, run, thread } = input\n const prefix = input.prefix ?? \"Sixb\"\n if (!run) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[${prefix}] Agent run '${create.createdByRunId}' not found for project '${create.projectId}'.`\n )\n }\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[${prefix}] Agent thread '${create.threadId}' not found for project '${create.projectId}'.`\n )\n }\n if (run.threadId !== create.threadId) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent run '${run.id}' does not belong to thread '${create.threadId}'.`\n )\n }\n if (run.status !== \"running\") {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent run '${run.id}' is not running (status '${run.status}').`\n )\n }\n if (!run.execution || run.execution.token !== create.executionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[${prefix}] Execution token is no longer current on agent run '${run.id}'.`\n )\n }\n if (thread.activeRunId !== run.id) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent run '${run.id}' no longer owns thread '${thread.id}'.`\n )\n }\n}\n\n/** Assert both compare-and-swap anchors and the retained-turn boundary. */\nexport function assertAgentContextCheckpointAnchors(input: {\n readonly create: CreateAgentContextCheckpointInput\n readonly latest: AgentContextCheckpointRecord | null\n readonly headSeq: number\n readonly firstRetained: AgentMessageRecord | null\n readonly prefix?: string\n}): void {\n const { create, latest, headSeq, firstRetained } = input\n const prefix = input.prefix ?? \"Sixb\"\n if (headSeq !== create.expectedHeadSeq) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent thread '${create.threadId}' message head changed from ${create.expectedHeadSeq} to ${headSeq}.`\n )\n }\n\n const latestId = latest?.id ?? null\n if (latestId !== create.expectedPreviousCheckpointId) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent thread '${create.threadId}' checkpoint head changed.`\n )\n }\n if (latest && create.summarizedThroughSeq <= latest.summarizedThroughSeq) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint boundary must advance beyond sequence ${latest.summarizedThroughSeq}.`\n )\n }\n if (!firstRetained || firstRetained.seq !== create.summarizedThroughSeq + 1) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent context checkpoint boundary does not align with stored thread messages.`\n )\n }\n if (firstRetained.role !== \"user\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint must retain a complete turn beginning with a user message.`\n )\n }\n}\n\n/** Validate the mutable anchors again before returning an idempotently created checkpoint. */\nexport function assertAgentContextCheckpointReplayState(input: {\n readonly create: CreateAgentContextCheckpointInput\n readonly existing: AgentContextCheckpointRecord\n readonly latest: AgentContextCheckpointRecord | null\n readonly headSeq: number\n readonly prefix?: string\n}): void {\n const prefix = input.prefix ?? \"Sixb\"\n if (input.headSeq !== input.create.expectedHeadSeq) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent thread '${input.create.threadId}' message head changed from ${input.create.expectedHeadSeq} to ${input.headSeq}.`\n )\n }\n if (input.latest?.id !== input.existing.id) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent thread '${input.create.threadId}' checkpoint head changed after '${input.existing.id}'.`\n )\n }\n}\n\n/** Compare the durable semantic payload; delivery token and generated timestamp are not content. */\nexport function agentContextCheckpointMatchesCreateInput(\n record: AgentContextCheckpointRecord,\n input: CreateAgentContextCheckpointInput\n): boolean {\n return (\n record.id === input.id &&\n record.projectId === input.projectId &&\n record.threadId === input.threadId &&\n record.createdByRunId === input.createdByRunId &&\n (record.previousCheckpointId ?? null) === input.expectedPreviousCheckpointId &&\n record.reason === input.reason &&\n record.summary === input.summary &&\n record.summaryFormatVersion === input.summaryFormatVersion &&\n record.summarizedThroughSeq === input.summarizedThroughSeq &&\n record.observedHeadSeq === input.observedHeadSeq &&\n record.estimatedInputTokensBefore === input.estimatedInputTokensBefore &&\n record.estimatedInputTokensAfter === input.estimatedInputTokensAfter &&\n record.summaryModelId === input.summaryModelId\n )\n}\n"
7
+ ],
8
+ "mappings": ";;;;;;;;;AAaO,MAAM,0BAA0B,MAAM;AAAA,EAIhC;AAAA,EAHF,OAAO;AAAA,EAEhB,WAAW,CACA,MACT,SACA;AAAA,IACA,MAAM,OAAO;AAAA,IAHJ;AAAA;AAKb;;;ACTA,eAAsB,uBAAuB,CAAC,OAM5B;AAAA,EAChB,MAAM,YAAY,MAAM,sBAAsB;AAAA,IAC5C,YAAY,MAAM;AAAA,IAClB,WAAW,MAAM;AAAA,IACjB,aAAa,MAAM;AAAA,IACnB,OAAO,MAAM;AAAA,IACb,kBAAkB,sBAAsB,MAAM,OAAO;AAAA,EACvD,CAAC;AAAA,EACD,IAAI,CAAC,WAA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,MAAM,SAAS,MACvG;AAAA,EACF;AAAA;AAIK,SAAS,wCAAwC,CACtD,QACA,OACS;AAAA,EACT,OACE,OAAO,OAAO,MAAM,MACpB,OAAO,cAAc,MAAM,aAC3B,OAAO,aAAa,MAAM,YAC1B,OAAO,mBAAmB,MAAM,mBAC/B,OAAO,wBAAwB,UAAU,MAAM,gCAChD,OAAO,WAAW,MAAM,UACxB,OAAO,YAAY,MAAM,WACzB,OAAO,yBAAyB,MAAM,wBACtC,OAAO,yBAAyB,MAAM,wBACtC,OAAO,oBAAoB,MAAM,mBACjC,OAAO,+BAA+B,MAAM,8BAC5C,OAAO,8BAA8B,MAAM,6BAC3C,OAAO,mBAAmB,MAAM;AAAA;",
9
+ "debugId": "C4E16AF3EE9252A464756E2164756E21",
10
+ "names": []
11
+ }
@@ -23,7 +23,7 @@ class AgentToolResultValidationError extends Error {
23
23
  reason;
24
24
  name = "AgentToolResultValidationError";
25
25
  constructor(toolName, reason, options) {
26
- super(`[Sixb] Agent tool '${toolName}' result must be a JSON value; ${reason}.`, options);
26
+ super(`[Sixb] Agent tool '${toolName}' returned an invalid result; ${reason}.`, options);
27
27
  this.toolName = toolName;
28
28
  this.reason = reason;
29
29
  }
@@ -153,4 +153,4 @@ function invalidContext(message) {
153
153
 
154
154
  export { AgentDefinitionError, AgentMessageAdapterError, AgentToolPublicError, AgentToolResultValidationError, AgentRequestError, MAX_AGENT_CONTEXT_ENTRIES, MAX_AGENT_APP_STATE_ENTRY_BYTES, MAX_AGENT_APP_STATE_TOTAL_BYTES, agentContext, agentContextIdentity, agentContextFingerprint, normalizeAgentContextEntries };
155
155
 
156
- //# debugId=86564C87A0ED8E7F64756E2164756E21
156
+ //# debugId=0BA2036A5CD1F1D964756E2164756E21
@@ -2,10 +2,10 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/agents/errors.ts", "../src/agents/context.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * Base error for the agents module. Specific subclasses extend this so callers\n * can catch any agent-scoped failure with a single `instanceof AgentDefinitionError` check.\n */\nexport class AgentDefinitionError extends Error {\n readonly name: string = \"AgentDefinitionError\"\n}\n\n/**\n * Raised by the message adapters. `fromAiSdk` is **total**: rather than silently dropping a part it\n * cannot model, it throws this — which both prevents data loss and pinpoints exactly when the\n * {@link AgentMessage} part union must be extended. It also fires on transient/streaming parts that\n * must never be persisted, and on out-of-contract (non-JSON) payloads.\n */\nexport class AgentMessageAdapterError extends Error {\n readonly name = \"AgentMessageAdapterError\"\n}\n\n/**\n * An agent-tool failure whose message is intentionally safe to expose to the model and persist in\n * the durable trace. Tool authors must keep the message free of credentials and internal details;\n * unknown errors remain masked by the worker.\n */\nexport class AgentToolPublicError extends Error {\n readonly name: string = \"AgentToolPublicError\"\n}\n\n/** Raised when an agent tool result cannot cross the durable JSON message boundary. */\nexport class AgentToolResultValidationError extends Error {\n readonly name = \"AgentToolResultValidationError\"\n\n constructor(\n readonly toolName: string,\n readonly reason: string,\n options?: ErrorOptions\n ) {\n super(`[Sixb] Agent tool '${toolName}' result must be a JSON value; ${reason}.`, options)\n }\n}\n\nexport type AgentRequestErrorCode =\n | \"agent_not_found\"\n | \"run_not_found\"\n | \"run_not_retryable\"\n | \"thread_not_found\"\n | \"thread_agent_mismatch\"\n | \"active_run_exists\"\n | \"invalid_context\"\n | \"storage_unavailable\"\n\n/**\n * Raised by {@link requestAgentRun} (the trigger). Callers branch on `code` rather than message text\n * — e.g. the HTTP layer maps `active_run_exists` to 409 and `agent_not_found` to 404.\n */\nexport class AgentRequestError extends Error {\n readonly name = \"AgentRequestError\"\n\n constructor(\n readonly code: AgentRequestErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n",
5
+ "/**\n * Base error for the agents module. Specific subclasses extend this so callers\n * can catch any agent-scoped failure with a single `instanceof AgentDefinitionError` check.\n */\nexport class AgentDefinitionError extends Error {\n readonly name: string = \"AgentDefinitionError\"\n}\n\n/**\n * Raised by the message adapters. `fromAiSdk` is **total**: rather than silently dropping a part it\n * cannot model, it throws this — which both prevents data loss and pinpoints exactly when the\n * {@link AgentMessage} part union must be extended. It also fires on transient/streaming parts that\n * must never be persisted, and on out-of-contract (non-JSON) payloads.\n */\nexport class AgentMessageAdapterError extends Error {\n readonly name = \"AgentMessageAdapterError\"\n}\n\n/**\n * An agent-tool failure whose message is intentionally safe to expose to the model and persist in\n * the durable trace. Tool authors must keep the message free of credentials and internal details;\n * unknown errors remain masked by the worker.\n */\nexport class AgentToolPublicError extends Error {\n readonly name: string = \"AgentToolPublicError\"\n}\n\n/** Raised when an agent tool result cannot cross the durable message boundary. */\nexport class AgentToolResultValidationError extends Error {\n readonly name = \"AgentToolResultValidationError\"\n\n constructor(\n readonly toolName: string,\n readonly reason: string,\n options?: ErrorOptions\n ) {\n super(`[Sixb] Agent tool '${toolName}' returned an invalid result; ${reason}.`, options)\n }\n}\n\nexport type AgentRequestErrorCode =\n | \"agent_not_found\"\n | \"run_not_found\"\n | \"run_not_retryable\"\n | \"thread_not_found\"\n | \"thread_agent_mismatch\"\n | \"active_run_exists\"\n | \"invalid_context\"\n | \"storage_unavailable\"\n\n/**\n * Raised by {@link requestAgentRun} (the trigger). Callers branch on `code` rather than message text\n * — e.g. the HTTP layer maps `active_run_exists` to 409 and `agent_not_found` to 404.\n */\nexport class AgentRequestError extends Error {\n readonly name = \"AgentRequestError\"\n\n constructor(\n readonly code: AgentRequestErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n",
6
6
  "import type { JsonValue } from \"../json\"\nimport { cloneJsonValue, getInvalidJsonValueReason, stableJsonStringify } from \"../json\"\nimport type { ObjectRef } from \"../ontology/refs\"\nimport { AgentRequestError } from \"./errors\"\n\nexport type AgentContextInput =\n | { readonly kind: \"object\"; readonly ref: ObjectRef }\n | {\n readonly kind: \"app-state\"\n readonly id: string\n readonly label: string\n readonly description: string\n readonly value: JsonValue\n }\n\nexport type AgentContextOrigin = \"ambient\" | \"explicit\"\n\nexport interface AgentContextEntryInput {\n readonly context: AgentContextInput\n readonly origin: AgentContextOrigin\n}\n\n/** Durable user-message part. Origin is display provenance, never an authorization grant. */\nexport interface AgentContextPart extends AgentContextEntryInput {\n readonly type: \"context\"\n}\n\nexport const MAX_AGENT_CONTEXT_ENTRIES = 12\nexport const MAX_AGENT_APP_STATE_ENTRY_BYTES = 16 * 1024\nexport const MAX_AGENT_APP_STATE_TOTAL_BYTES = 64 * 1024\n\n/** Typed constructors for context values shared by custom apps and agent clients. */\nexport const agentContext = {\n object<const TObjectTypeId extends string>(\n objectType: { readonly id: TObjectTypeId },\n primaryId: string\n ) {\n return {\n kind: \"object\" as const,\n ref: { objectTypeId: objectType.id, primaryId },\n }\n },\n\n appState<const TValue extends JsonValue>(\n id: string,\n input: {\n readonly label: string\n readonly description: string\n readonly value: TValue\n }\n ) {\n return { kind: \"app-state\" as const, id, ...input }\n },\n}\n\n/** Stable identity shared by core deduplication and context-aware clients. */\nexport function agentContextIdentity(context: AgentContextInput): string {\n return context.kind === \"object\"\n ? `object:${encodeURIComponent(context.ref.objectTypeId)}:${encodeURIComponent(context.ref.primaryId)}`\n : `app-state:${encodeURIComponent(context.id)}`\n}\n\n/** Stable semantic key for client-side comparisons. */\nexport function agentContextFingerprint(context: AgentContextInput): string {\n return stableJsonStringify(context)\n}\n\n/**\n * Validate transport-independent context rules and clone mutable app state before it can become\n * durable. Object existence and visibility are resolved separately because they require a runtime.\n */\nexport function normalizeAgentContextEntries(\n input: readonly AgentContextEntryInput[] | undefined\n): readonly AgentContextEntryInput[] {\n if (input === undefined) return []\n if (!Array.isArray(input)) invalidContext(\"context must be an array\")\n if (input.length > MAX_AGENT_CONTEXT_ENTRIES) {\n invalidContext(`context cannot contain more than ${MAX_AGENT_CONTEXT_ENTRIES} entries`)\n }\n\n const entries: AgentContextEntryInput[] = []\n const byIdentity = new Map<string, string>()\n let totalAppStateBytes = 0\n\n for (const [index, rawEntry] of input.entries()) {\n const entry = normalizeEntry(rawEntry, index)\n const identity = agentContextIdentity(entry.context)\n const serialized = stableJsonStringify(entry)\n const existing = byIdentity.get(identity)\n\n if (existing !== undefined) {\n if (existing === serialized) continue\n invalidContext(`context contains conflicting entries for '${identity}'`)\n }\n\n if (entry.context.kind === \"app-state\") {\n const bytes = utf8ByteLength(serialized)\n if (bytes > MAX_AGENT_APP_STATE_ENTRY_BYTES) {\n invalidContext(\n `context entry '${identity}' exceeds the ${MAX_AGENT_APP_STATE_ENTRY_BYTES}-byte limit`\n )\n }\n totalAppStateBytes += bytes\n if (totalAppStateBytes > MAX_AGENT_APP_STATE_TOTAL_BYTES) {\n invalidContext(\n `app-state context exceeds the ${MAX_AGENT_APP_STATE_TOTAL_BYTES}-byte message limit`\n )\n }\n }\n\n byIdentity.set(identity, serialized)\n entries.push(entry)\n }\n\n return entries\n}\n\nfunction normalizeEntry(rawEntry: unknown, index: number): AgentContextEntryInput {\n if (!isRecord(rawEntry)) invalidContext(`context[${index}] must be an object`)\n if (rawEntry.origin !== \"ambient\" && rawEntry.origin !== \"explicit\") {\n invalidContext(`context[${index}].origin must be 'ambient' or 'explicit'`)\n }\n if (!isRecord(rawEntry.context)) invalidContext(`context[${index}].context must be an object`)\n\n const context = rawEntry.context\n if (context.kind === \"object\") {\n if (!isRecord(context.ref)) invalidContext(`context[${index}].context.ref must be an object`)\n const objectTypeId = requireNonEmptyString(\n context.ref.objectTypeId,\n `context[${index}].context.ref.objectTypeId`\n )\n const primaryId = requireNonEmptyString(\n context.ref.primaryId,\n `context[${index}].context.ref.primaryId`\n )\n return {\n context: { kind: \"object\", ref: { objectTypeId, primaryId } },\n origin: rawEntry.origin,\n }\n }\n\n if (context.kind === \"app-state\") {\n const id = requireNonEmptyString(context.id, `context[${index}].context.id`)\n const label = requireNonEmptyString(context.label, `context[${index}].context.label`)\n const description = requireNonEmptyString(\n context.description,\n `context[${index}].context.description`\n )\n const reason = getInvalidJsonValueReason(context.value, `context[${index}].context.value`)\n if (reason) {\n invalidContext(`context[${index}].context.value must be a JSON value; ${reason}`)\n }\n return {\n context: {\n kind: \"app-state\",\n id,\n label,\n description,\n value: cloneJsonValue(context.value as JsonValue),\n },\n origin: rawEntry.origin,\n }\n }\n\n invalidContext(`context[${index}].context.kind must be 'object' or 'app-state'`)\n}\n\nfunction requireNonEmptyString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n invalidContext(`${label} must be a non-empty string`)\n }\n return value\n}\n\nfunction utf8ByteLength(value: string): number {\n return new TextEncoder().encode(value).byteLength\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction invalidContext(message: string): never {\n throw new AgentRequestError(\"invalid_context\", `[Sixb] Invalid agent context: ${message}.`)\n}\n"
7
7
  ],
8
- "mappings": ";;;;;;;;AAIO,MAAM,6BAA6B,MAAM;AAAA,EACrC,OAAe;AAC1B;AAAA;AAQO,MAAM,iCAAiC,MAAM;AAAA,EACzC,OAAO;AAClB;AAAA;AAOO,MAAM,6BAA6B,MAAM;AAAA,EACrC,OAAe;AAC1B;AAAA;AAGO,MAAM,uCAAuC,MAAM;AAAA,EAI7C;AAAA,EACA;AAAA,EAJF,OAAO;AAAA,EAEhB,WAAW,CACA,UACA,QACT,SACA;AAAA,IACA,MAAM,sBAAsB,0CAA0C,WAAW,OAAO;AAAA,IAJ/E;AAAA,IACA;AAAA;AAKb;AAAA;AAgBO,MAAM,0BAA0B,MAAM;AAAA,EAIhC;AAAA,EAHF,OAAO;AAAA,EAEhB,WAAW,CACA,MACT,SACA;AAAA,IACA,MAAM,OAAO;AAAA,IAHJ;AAAA;AAKb;;;ACpCO,IAAM,4BAA4B;AAClC,IAAM,kCAAkC,KAAK;AAC7C,IAAM,kCAAkC,KAAK;AAG7C,IAAM,eAAe;AAAA,EAC1B,MAA0C,CACxC,YACA,WACA;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,MACN,KAAK,EAAE,cAAc,WAAW,IAAI,UAAU;AAAA,IAChD;AAAA;AAAA,EAGF,QAAwC,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F,MAAM,cAAc,sBAClB,QAAQ,aACR,WAAW,4BACb;AAAA,IACA,MAAM,SAAS,0BAA0B,QAAQ,OAAO,WAAW,sBAAsB;AAAA,IACzF,IAAI,QAAQ;AAAA,MACV,eAAe,WAAW,8CAA8C,QAAQ;AAAA,IAClF;AAAA,IACA,OAAO;AAAA,MACL,SAAS;AAAA,QACP,MAAM;AAAA,QACN;AAAA,QACA;AAAA,QACA;AAAA,QACA,OAAO,eAAe,QAAQ,KAAkB;AAAA,MAClD;AAAA,MACA,QAAQ,SAAS;AAAA,IACnB;AAAA,EACF;AAAA,EAEA,eAAe,WAAW,qDAAqD;AAAA;AAGjF,SAAS,qBAAqB,CAAC,OAAgB,OAAuB;AAAA,EACpE,IAAI,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,WAAW,GAAG;AAAA,IAC1D,eAAe,GAAG,kCAAkC;AAAA,EACtD;AAAA,EACA,OAAO;AAAA;AAGT,SAAS,cAAc,CAAC,OAAuB;AAAA,EAC7C,OAAO,IAAI,YAAY,EAAE,OAAO,KAAK,EAAE;AAAA;AAGzC,SAAS,QAAQ,CAAC,OAAkD;AAAA,EAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAAA;AAG5E,SAAS,cAAc,CAAC,SAAwB;AAAA,EAC9C,MAAM,IAAI,kBAAkB,mBAAmB,iCAAiC,UAAU;AAAA;",
9
+ "debugId": "0BA2036A5CD1F1D964756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -0,0 +1,36 @@
1
+ // @bun
2
+ import {
3
+ compareStrings
4
+ } from "./chunk-t8t39h7v.js";
5
+
6
+ // src/auth/attribution.ts
7
+ async function snapshotRequesterGroupIds(input) {
8
+ if (input.principal.type === "system" || !input.auth) {
9
+ return [];
10
+ }
11
+ const memberships = input.principal.type === "user" ? await input.auth.groupMemberships.listForUser({
12
+ projectId: input.projectId,
13
+ userId: input.principal.id
14
+ }) : await input.auth.serviceAccountGroupMemberships.listForServiceAccount({
15
+ projectId: input.projectId,
16
+ serviceAccountId: input.principal.id
17
+ });
18
+ return normalizeRequesterGroupIds(memberships.map((membership) => membership.groupId));
19
+ }
20
+ function normalizeRequesterGroupIds(groupIds) {
21
+ if (!Array.isArray(groupIds)) {
22
+ throw new TypeError("[Sixb] requesterGroupIds must be an array.");
23
+ }
24
+ const unique = new Set;
25
+ for (const groupId of groupIds) {
26
+ if (typeof groupId !== "string" || groupId.trim().length === 0) {
27
+ throw new TypeError("[Sixb] requesterGroupIds entries must be nonblank.");
28
+ }
29
+ unique.add(groupId);
30
+ }
31
+ return [...unique].sort(compareStrings);
32
+ }
33
+
34
+ export { snapshotRequesterGroupIds, normalizeRequesterGroupIds };
35
+
36
+ //# debugId=9060B30B6C744AE864756E2164756E21
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/auth/attribution.ts"],
4
+ "sourcesContent": [
5
+ "import { compareStrings } from \"../json\"\nimport type { AuthStorage } from \"../storage/auth\"\nimport type { Principal } from \"./types\"\n\n/**\n * Resolve the durable group-membership snapshot used to attribute admitted work.\n *\n * Authorization contexts can carry a token-restricted subset of the principal's groups, so they\n * are deliberately not accepted here. Accounting attribution comes from auth storage whenever it\n * is configured. A system principal, or a runtime with no durable auth storage, has no groups.\n */\nexport async function snapshotRequesterGroupIds(input: {\n readonly auth: AuthStorage | undefined\n readonly projectId: string\n readonly principal: Principal\n}): Promise<readonly string[]> {\n if (input.principal.type === \"system\" || !input.auth) {\n return []\n }\n\n const memberships =\n input.principal.type === \"user\"\n ? await input.auth.groupMemberships.listForUser({\n projectId: input.projectId,\n userId: input.principal.id,\n })\n : await input.auth.serviceAccountGroupMemberships.listForServiceAccount({\n projectId: input.projectId,\n serviceAccountId: input.principal.id,\n })\n\n return normalizeRequesterGroupIds(memberships.map((membership) => membership.groupId))\n}\n\n/** Validate and canonicalize an immutable requester-group snapshot at a storage boundary. */\nexport function normalizeRequesterGroupIds(groupIds: readonly string[]): readonly string[] {\n if (!Array.isArray(groupIds)) {\n throw new TypeError(\"[Sixb] requesterGroupIds must be an array.\")\n }\n const unique = new Set<string>()\n for (const groupId of groupIds) {\n if (typeof groupId !== \"string\" || groupId.trim().length === 0) {\n throw new TypeError(\"[Sixb] requesterGroupIds entries must be nonblank.\")\n }\n unique.add(groupId)\n }\n return [...unique].sort(compareStrings)\n}\n"
6
+ ],
7
+ "mappings": ";;;;;;AAWA,eAAsB,yBAAyB,CAAC,OAIjB;AAAA,EAC7B,IAAI,MAAM,UAAU,SAAS,YAAY,CAAC,MAAM,MAAM;AAAA,IACpD,OAAO,CAAC;AAAA,EACV;AAAA,EAEA,MAAM,cACJ,MAAM,UAAU,SAAS,SACrB,MAAM,MAAM,KAAK,iBAAiB,YAAY;AAAA,IAC5C,WAAW,MAAM;AAAA,IACjB,QAAQ,MAAM,UAAU;AAAA,EAC1B,CAAC,IACD,MAAM,MAAM,KAAK,+BAA+B,sBAAsB;AAAA,IACpE,WAAW,MAAM;AAAA,IACjB,kBAAkB,MAAM,UAAU;AAAA,EACpC,CAAC;AAAA,EAEP,OAAO,2BAA2B,YAAY,IAAI,CAAC,eAAe,WAAW,OAAO,CAAC;AAAA;AAIhF,SAAS,0BAA0B,CAAC,UAAgD;AAAA,EACzF,IAAI,CAAC,MAAM,QAAQ,QAAQ,GAAG;AAAA,IAC5B,MAAM,IAAI,UAAU,4CAA4C;AAAA,EAClE;AAAA,EACA,MAAM,SAAS,IAAI;AAAA,EACnB,WAAW,WAAW,UAAU;AAAA,IAC9B,IAAI,OAAO,YAAY,YAAY,QAAQ,KAAK,EAAE,WAAW,GAAG;AAAA,MAC9D,MAAM,IAAI,UAAU,oDAAoD;AAAA,IAC1E;AAAA,IACA,OAAO,IAAI,OAAO;AAAA,EACpB;AAAA,EACA,OAAO,CAAC,GAAG,MAAM,EAAE,KAAK,cAAc;AAAA;",
8
+ "debugId": "9060B30B6C744AE864756E2164756E21",
9
+ "names": []
10
+ }
@@ -10,6 +10,7 @@ var AGENT_RUN_FINISH_REASONS = [
10
10
  "length",
11
11
  "content-filter",
12
12
  "tool-calls",
13
+ "timeout",
13
14
  "error",
14
15
  "other",
15
16
  "unknown"
@@ -31,4 +32,4 @@ var AGENT_RUN_DIAGNOSTIC_CODES = [
31
32
 
32
33
  export { AGENT_RUN_FAILURE_CODES, AGENT_RUN_FINISH_REASONS, coerceAgentRunFinishReason, AGENT_RUN_DIAGNOSTIC_CODES };
33
34
 
34
- //# debugId=BB5C92FEA5685CA164756E2164756E21
35
+ //# debugId=E6142794534A3A5D64756E2164756E21
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/storage/agents/types.ts"],
4
+ "sourcesContent": [
5
+ "import type { AgentMessage, AgentMessagePart, AgentMessageRole } from \"../../agents/message\"\nimport type { Principal } from \"../../auth\"\nimport type { SixbErrorCode, SixbFailure } from \"../../errors/types\"\nimport type { JsonValue } from \"../../json\"\n\n// ── agent_threads — one conversation with an agent ──────────────────────────────────────────────\n\nexport type AgentThreadStatus = \"active\" | \"archived\"\n\nexport interface AgentThreadRecord {\n readonly id: string\n readonly projectId: string\n readonly agentId: string\n /** Who owns/opened the thread. Reuses the canonical auth principal (gains `agent` later for free). */\n readonly ownerPrincipal: Principal\n readonly title?: string\n readonly status: AgentThreadStatus\n /** Single-flight anchor: the id of the one run currently allowed to write, or `null` when idle. */\n readonly activeRunId: string | null\n readonly lastMessageAt?: Date\n readonly messageCount: number\n readonly createdAt: Date\n readonly updatedAt: Date\n}\n\nexport interface CreateAgentThreadInput {\n readonly id: string\n readonly projectId: string\n readonly agentId: string\n readonly ownerPrincipal: Principal\n readonly title?: string\n readonly status?: AgentThreadStatus\n readonly createdAt?: Date\n readonly updatedAt?: Date\n}\n\nexport interface ListAgentThreadsInput {\n readonly projectId: string\n readonly agentId?: string\n /** Optional allowlist intersected with `agentId` when both are provided. Empty means no rows. */\n readonly agentIds?: readonly string[]\n readonly statuses?: readonly AgentThreadStatus[]\n readonly ownerPrincipal?: Principal\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListAgentThreadsResult {\n readonly threads: readonly AgentThreadRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n// ── agent_runs — one loop execution (the worker job; attribution + fencing) ───────────────────\n\n/** Lifecycle shared by every durable agent execution, conversational or workflow-owned. */\nexport type AgentExecutionStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\"\n\nexport type AgentRunStatus = AgentExecutionStatus\n\n/** Error codes an agent execution can persist and expose through its public contract. */\nexport const AGENT_RUN_FAILURE_CODES = [\n \"internal.unexpected\",\n \"runtime.cancelled\",\n \"agent.execution_failed\",\n] as const satisfies readonly [SixbErrorCode, ...SixbErrorCode[]]\n\nexport type AgentRunFailureCode = (typeof AGENT_RUN_FAILURE_CODES)[number]\n\n/**\n * Why a run ended — our own SDK-independent vocabulary. It includes the AI SDK's unified finish\n * reasons plus platform-level endings such as `timeout`, so reads are typed and exhaustive without\n * core depending on `ai`. `other`/`unknown` are catch-alls: an unrecognised provider value still\n * records *that* the run ended.\n */\nexport const AGENT_RUN_FINISH_REASONS = [\n \"stop\",\n \"length\",\n \"content-filter\",\n \"tool-calls\",\n \"timeout\",\n \"error\",\n \"other\",\n \"unknown\",\n] as const\n\nexport type AgentRunFinishReason = (typeof AGENT_RUN_FINISH_REASONS)[number]\n\n/**\n * Coerce an external finish-reason string — a DB column or an SDK value — to {@link\n * AgentRunFinishReason}. An unrecognised value becomes `\"unknown\"` rather than being dropped.\n */\nexport function coerceAgentRunFinishReason(\n value: string | null | undefined\n): AgentRunFinishReason | undefined {\n if (value === null || value === undefined) {\n return undefined\n }\n return (AGENT_RUN_FINISH_REASONS as readonly string[]).includes(value)\n ? (value as AgentRunFinishReason)\n : \"unknown\"\n}\n\n/** Stable, user-facing diagnostics emitted by the platform while executing a run. */\nexport const AGENT_RUN_DIAGNOSTIC_CODES = [\n \"output_file_limit_exceeded\",\n \"output_file_too_large\",\n \"output_budget_exhausted\",\n \"output_collection_failed\",\n \"output_file_changed\",\n \"output_storage_failed\",\n] as const\n\n/**\n * Closed on purpose, and the wire is closed with it.\n *\n * Sixb writes these codes and the generated client is what reads them, so an open union would only\n * be honest if the HTTP schema were open too — and that costs the OpenAPI enum, the client's\n * autocompletion, and Atlas's exhaustive `switch`. Sixb owns both ends, so a new code is a minor\n * version bump: cheap here, and a broken `switch` is better than a 500 from `z.enum`.\n */\nexport type AgentRunDiagnosticCode = (typeof AGENT_RUN_DIAGNOSTIC_CODES)[number]\nexport type AgentRunDiagnosticSeverity = \"warning\" | \"error\"\n\nexport interface AgentRunDiagnostic {\n readonly code: AgentRunDiagnosticCode\n readonly severity: AgentRunDiagnosticSeverity\n readonly scope: \"output\"\n /** Relative path inside the run's published output directory, when one file is involved. */\n readonly path?: string\n /** Sanitized, stable copy suitable for display to an end user. */\n readonly message: string\n}\n\n/**\n * Authorization state for the current queue delivery.\n *\n * `queueLeaseExpiresAt` is a persisted projection of `ClaimedQueueJob.leaseExpiresAt`, not an\n * independently managed run lease. It may only be extended from a successful queue lease renewal.\n */\nexport interface AgentRunExecution {\n readonly token: string\n readonly queueLeaseExpiresAt: Date\n}\n\nexport interface AgentRunRecord {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly threadId: string\n readonly agentId: string\n readonly triggerMessageId: string\n /** Durable group memberships snapshotted when the run was admitted. */\n readonly requesterGroupIds: readonly string[]\n readonly status: AgentRunStatus\n readonly modelId?: string\n /** Why the run ended (our own SDK-independent enum). */\n readonly finishReason?: AgentRunFinishReason\n /** Platform diagnostics are transcript annotations, never agent-authored message content. */\n readonly diagnostics?: readonly AgentRunDiagnostic[]\n /** Portable failure snapshot when the run did not succeed. */\n readonly error?: SixbFailure<AgentRunFailureCode>\n /** Execution attempts: `0` while queued, `1` on first start, incremented on redelivery. */\n readonly attempt: number\n readonly execution?: AgentRunExecution\n readonly createdAt: Date\n readonly startedAt?: Date\n readonly completedAt?: Date\n}\n\nexport interface CreateAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly threadId: string\n readonly agentId: string\n readonly triggerMessageId: string\n readonly requesterGroupIds: readonly string[]\n readonly createdAt?: Date\n}\n\nexport interface StartAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly modelId?: string\n readonly execution: AgentRunExecution\n readonly startedAt?: Date\n}\n\nexport interface FinishQueuedAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\" | \"cancelled\"\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly completedAt?: Date\n}\n\nexport interface ReclaimAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly execution: AgentRunExecution\n}\n\nexport interface ConfirmAgentRunExecutionOwnershipInput {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n /** Exact expiration returned by the queue claim or its latest successful renewal. */\n readonly queueLeaseExpiresAt: Date\n}\n\nexport type FinishAgentRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n readonly status: \"succeeded\"\n readonly modelId?: string\n readonly finishReason?: AgentRunFinishReason\n readonly diagnostics?: readonly AgentRunDiagnostic[]\n readonly completedAt?: Date\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n readonly status: \"failed\" | \"cancelled\"\n readonly modelId?: string\n readonly finishReason?: AgentRunFinishReason\n readonly diagnostics?: readonly AgentRunDiagnostic[]\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly completedAt?: Date\n }\n\nexport interface ListAgentRunsInput {\n readonly projectId: string\n readonly threadId?: string\n readonly agentId?: string\n readonly statuses?: readonly AgentRunStatus[]\n /** Effective start time; runs that never started use `createdAt`. */\n readonly startedAfter?: Date\n /** Effective start time; runs that never started use `createdAt`. */\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListAgentRunsResult {\n readonly runs: readonly AgentRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n// ── agent_messages — one message (assistant messages inserted only once finalized) ─────────────\n\nexport type { AgentMessageRole }\n\nexport interface AgentMessageRecord {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n /** The run that produced this message; `null` for user-authored messages. */\n readonly runId: string | null\n readonly role: AgentMessageRole\n /** Principal that authored this persisted message: caller for user messages, agent identity later for assistant messages. */\n readonly authorPrincipal?: Principal\n /** Monotonic per thread, assigned by the store. */\n readonly seq: number\n /** Structured message content — text / reasoning / step boundaries / tool calls. */\n readonly parts: readonly AgentMessagePart[]\n /** Message-level metadata (mirrors `UIMessage.metadata`). */\n readonly metadata?: JsonValue\n /** Versions the `parts` shape so it can be migrated; stamped from `AGENT_MESSAGE_CONTENT_VERSION`. */\n readonly contentVersion: number\n readonly createdAt: Date\n readonly completedAt?: Date\n}\n\n/** Append a message: a {@link AgentMessage} (role + parts + metadata) plus its storage identity. */\nexport interface AppendAgentMessageInput extends AgentMessage {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n readonly runId: string | null\n readonly authorPrincipal?: Principal\n readonly createdAt?: Date\n readonly completedAt?: Date\n}\n\nexport interface DeleteAgentMessagesByRunInput {\n readonly projectId: string\n readonly threadId: string\n readonly runId: string\n}\n\nexport interface ListAgentMessagesInput {\n readonly projectId: string\n readonly threadId: string\n /** Return only messages whose per-thread sequence is greater than this retained boundary. */\n readonly afterSeq?: number\n readonly roles?: readonly AgentMessageRole[]\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListAgentMessagesResult {\n readonly messages: readonly AgentMessageRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n// ── agent_context_checkpoints — append-only model-context boundaries ──────────────────────────\n\nexport type AgentContextCheckpointReason = \"threshold\" | \"overflow\"\n\n/**\n * A durable summary boundary used only when projecting a thread into model context.\n *\n * Checkpoints never replace or mutate transcript messages. Normal thread reads remain authoritative\n * and complete; the worker reads the latest checkpoint and only the retained message tail.\n */\nexport interface AgentContextCheckpointRecord {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n readonly createdByRunId: string\n readonly previousCheckpointId?: string\n readonly reason: AgentContextCheckpointReason\n readonly summary: string\n readonly summaryFormatVersion: 1\n readonly summarizedThroughSeq: number\n readonly observedHeadSeq: number\n readonly estimatedInputTokensBefore: number\n readonly estimatedInputTokensAfter: number\n readonly summaryModelId: string\n readonly createdAt: Date\n}\n\nexport interface CreateAgentContextCheckpointInput {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n readonly createdByRunId: string\n /** Compare-and-swap anchor. `null` means the thread must not have a prior checkpoint. */\n readonly expectedPreviousCheckpointId: string | null\n /** Compare-and-swap anchor for the complete transcript observed by the summarizer. */\n readonly expectedHeadSeq: number\n /** Current delivery token for `createdByRunId`; stale redeliveries must not write. */\n readonly executionToken: string\n readonly reason: AgentContextCheckpointReason\n readonly summary: string\n readonly summaryFormatVersion: 1\n readonly summarizedThroughSeq: number\n readonly observedHeadSeq: number\n readonly estimatedInputTokensBefore: number\n readonly estimatedInputTokensAfter: number\n readonly summaryModelId: string\n readonly createdAt?: Date\n}\n\n// ── Store ───────────────────────────────────────────────────────────────────────────────────────\n\nexport interface AgentThreadStore {\n create(input: CreateAgentThreadInput): Promise<AgentThreadRecord>\n getById(params: { projectId: string; id: string }): Promise<AgentThreadRecord | null>\n list(input: ListAgentThreadsInput): Promise<ListAgentThreadsResult>\n}\n\nexport interface AgentRunStore {\n /** Persist a queued run and atomically claim the thread's single-flight slot. */\n create(input: CreateAgentRunInput): Promise<AgentRunRecord>\n /** Transition a queued run to running and install the first delivery's execution token. */\n start(input: StartAgentRunInput): Promise<AgentRunRecord>\n /** Finish a queued run before execution and release the thread's single-flight slot. */\n finishQueued(input: FinishQueuedAgentRunInput): Promise<AgentRunRecord>\n /** Rotate the execution token for a redelivered running job (`attempt++`). */\n reclaim(input: ReclaimAgentRunInput): Promise<AgentRunRecord>\n /**\n * Project the queue's latest confirmed ownership expiration onto the current execution.\n * Implementations must fence by token and must never move the expiration backwards.\n */\n confirmExecutionOwnership(input: ConfirmAgentRunExecutionOwnershipInput): Promise<AgentRunRecord>\n /** Finalize a run and release the thread's `activeRunId`. */\n finish(input: FinishAgentRunInput): Promise<AgentRunRecord>\n getById(params: { projectId: string; id: string }): Promise<AgentRunRecord | null>\n getByIds(params: {\n projectId: string\n ids: readonly string[]\n }): Promise<readonly AgentRunRecord[]>\n list(input: ListAgentRunsInput): Promise<ListAgentRunsResult>\n}\n\nexport interface AgentMessageStore {\n /** Insert a message (its `parts` are the canonical content) and bump thread stats. */\n append(input: AppendAgentMessageInput): Promise<AgentMessageRecord>\n /** Delete every message produced by one run and repair the thread's message stats. */\n deleteByRunId(input: DeleteAgentMessagesByRunInput): Promise<number>\n getById(params: { projectId: string; id: string }): Promise<AgentMessageRecord | null>\n list(input: ListAgentMessagesInput): Promise<ListAgentMessagesResult>\n}\n\nexport interface AgentContextCheckpointStore {\n /**\n * Append one checkpoint after atomically validating run ownership and both transcript anchors.\n * Repeating the same payload for the same creating run is idempotent.\n */\n create(input: CreateAgentContextCheckpointInput): Promise<AgentContextCheckpointRecord>\n getLatest(input: {\n readonly projectId: string\n readonly threadId: string\n }): Promise<AgentContextCheckpointRecord | null>\n}\n\nexport interface AgentStorage {\n readonly threads: AgentThreadStore\n readonly runs: AgentRunStore\n readonly messages: AgentMessageStore\n readonly checkpoints: AgentContextCheckpointStore\n}\n"
6
+ ],
7
+ "mappings": ";;AA8DO,IAAM,0BAA0B;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AACF;AAUO,IAAM,2BAA2B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAQO,SAAS,0BAA0B,CACxC,OACkC;AAAA,EAClC,IAAI,UAAU,QAAQ,UAAU,WAAW;AAAA,IACzC;AAAA,EACF;AAAA,EACA,OAAQ,yBAA+C,SAAS,KAAK,IAChE,QACD;AAAA;AAIC,IAAM,6BAA6B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
8
+ "debugId": "E6142794534A3A5D64756E2164756E21",
9
+ "names": []
10
+ }
@@ -7,10 +7,10 @@ import {
7
7
  effectsWithoutEditsMessage,
8
8
  isObjectActionDefinition,
9
9
  missingActionMutationMessage
10
- } from "./chunk-c6qd89g5.js";
10
+ } from "./chunk-d6y2wsfg.js";
11
11
  import {
12
12
  createLinkScopeFingerprint
13
- } from "./chunk-st4xgxey.js";
13
+ } from "./chunk-ettb0cy4.js";
14
14
  import {
15
15
  linkRefKey,
16
16
  linkScopeKey,
@@ -1,7 +1,7 @@
1
1
  // @bun
2
2
  import {
3
3
  createPrimitiveExecutionRecord
4
- } from "./chunk-8ryen3p3.js";
4
+ } from "./chunk-4aw0jwk0.js";
5
5
  import {
6
6
  sha256Canonical
7
7
  } from "./chunk-fmx1sz2h.js";
@@ -19,7 +19,7 @@ import {
19
19
  } from "./chunk-dsrkgtnh.js";
20
20
  import {
21
21
  ProjectionValidationError
22
- } from "./chunk-34bqh420.js";
22
+ } from "./chunk-4z3n1dzt.js";
23
23
  import {
24
24
  createSixbError,
25
25
  toSixbFailure
@@ -401,4 +401,4 @@ function toEnqueueFailure(error, run, at) {
401
401
  }
402
402
  export { registerProjectionRegistry, getProjectionRegistry, getProjectionDispatchDescriptors, shareProjectionRegistry, createProjectionRunId, PROJECTION_TELEMETRY_BATCH_SIZE, ProjectionRunDispatcher };
403
403
 
404
- //# debugId=E8546CFEC17DF5E464756E2164756E21
404
+ //# debugId=562D2A2DDB41546364756E2164756E21