@sixb/core 0.2.5 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (385) hide show
  1. package/dist/actions/index.js +36 -35
  2. package/dist/actions/index.js.map +1 -1
  3. package/dist/actions/validation.d.ts.map +1 -1
  4. package/dist/agents/errors.d.ts +1 -1
  5. package/dist/agents/errors.d.ts.map +1 -1
  6. package/dist/agents/execution.d.ts +17 -2
  7. package/dist/agents/execution.d.ts.map +1 -1
  8. package/dist/agents/index.d.ts +2 -2
  9. package/dist/agents/index.d.ts.map +1 -1
  10. package/dist/agents/index.js +50 -44
  11. package/dist/agents/index.js.map +1 -1
  12. package/dist/agents/model-routing.d.ts +5 -2
  13. package/dist/agents/model-routing.d.ts.map +1 -1
  14. package/dist/agents/request.d.ts +45 -4
  15. package/dist/agents/request.d.ts.map +1 -1
  16. package/dist/agents/run-events.d.ts +4 -0
  17. package/dist/agents/run-events.d.ts.map +1 -1
  18. package/dist/agents/run-session-children.d.ts.map +1 -1
  19. package/dist/agents/run-turn.d.ts +9 -1
  20. package/dist/agents/run-turn.d.ts.map +1 -1
  21. package/dist/agents/streams/index.d.ts +1 -1
  22. package/dist/agents/streams/index.d.ts.map +1 -1
  23. package/dist/agents/streams/index.js +1 -1
  24. package/dist/agents/streams/internal.d.ts +2 -1
  25. package/dist/agents/streams/internal.d.ts.map +1 -1
  26. package/dist/agents/streams/internal.js +22 -2
  27. package/dist/agents/streams/internal.js.map +1 -1
  28. package/dist/agents/streams/protocol.d.ts +37 -0
  29. package/dist/agents/streams/protocol.d.ts.map +1 -1
  30. package/dist/agents/streams/steps.d.ts +24 -0
  31. package/dist/agents/streams/steps.d.ts.map +1 -0
  32. package/dist/agents/thread-access.d.ts +44 -2
  33. package/dist/agents/thread-access.d.ts.map +1 -1
  34. package/dist/artifacts/live/server.js +19 -18
  35. package/dist/artifacts/live/server.js.map +1 -1
  36. package/dist/artifacts/publish/index.js +18 -17
  37. package/dist/artifacts/publish/index.js.map +1 -1
  38. package/dist/artifacts/publish/merge.d.ts +2 -1
  39. package/dist/artifacts/publish/merge.d.ts.map +1 -1
  40. package/dist/artifacts/run-query.d.ts.map +1 -1
  41. package/dist/auth/index.js +6 -6
  42. package/dist/authorization/index.js +2 -2
  43. package/dist/bootstrap/index.js +40 -38
  44. package/dist/bootstrap/index.js.map +2 -2
  45. package/dist/calendar.d.ts +55 -0
  46. package/dist/calendar.d.ts.map +1 -0
  47. package/dist/calendar.js +19 -0
  48. package/dist/calendar.js.map +9 -0
  49. package/dist/{chunk-5a4a52tq.js → chunk-0pmpwn3g.js} +18 -2
  50. package/dist/chunk-0pmpwn3g.js.map +10 -0
  51. package/dist/{chunk-xcrnrpfh.js → chunk-394zjzjs.js} +20 -10
  52. package/dist/{chunk-xcrnrpfh.js.map → chunk-394zjzjs.js.map} +5 -5
  53. package/dist/{chunk-stmxh0hv.js → chunk-3neam1y5.js} +2 -2
  54. package/dist/{chunk-zeykm8my.js → chunk-3qtk0070.js} +16 -42
  55. package/dist/chunk-3qtk0070.js.map +14 -0
  56. package/dist/{chunk-0mvjpgvm.js → chunk-425ydk65.js} +4 -4
  57. package/dist/{chunk-s5pj68fa.js → chunk-5sswe5ej.js} +2 -2
  58. package/dist/chunk-6hfbz4d0.js +98 -0
  59. package/dist/chunk-6hfbz4d0.js.map +10 -0
  60. package/dist/{chunk-3zagkr6w.js → chunk-7mhbs9yy.js} +4 -4
  61. package/dist/{chunk-3zagkr6w.js.map → chunk-7mhbs9yy.js.map} +1 -1
  62. package/dist/{chunk-fpf57gca.js → chunk-7r9mqpva.js} +273 -66
  63. package/dist/{chunk-fpf57gca.js.map → chunk-7r9mqpva.js.map} +5 -5
  64. package/dist/{chunk-ewqn51gr.js → chunk-88xeh6zx.js} +6 -4
  65. package/dist/{chunk-ewqn51gr.js.map → chunk-88xeh6zx.js.map} +4 -4
  66. package/dist/chunk-90nqenq8.js +386 -0
  67. package/dist/chunk-90nqenq8.js.map +14 -0
  68. package/dist/{chunk-gjhrz66x.js → chunk-9c9yknwt.js} +247 -20
  69. package/dist/{chunk-gjhrz66x.js.map → chunk-9c9yknwt.js.map} +6 -6
  70. package/dist/{chunk-q9nkpr8k.js → chunk-9tpmfh3n.js} +1 -1
  71. package/dist/chunk-9wr3yajk.js.map +2 -2
  72. package/dist/{chunk-z1njfqqs.js → chunk-ats8y3d9.js} +721 -156
  73. package/dist/{chunk-z1njfqqs.js.map → chunk-ats8y3d9.js.map} +13 -13
  74. package/dist/{chunk-68hm50qh.js → chunk-bcz9dxtf.js} +16 -46
  75. package/dist/chunk-bcz9dxtf.js.map +12 -0
  76. package/dist/{chunk-naxjka9v.js → chunk-brhp9d97.js} +2 -2
  77. package/dist/{chunk-8a8k38tz.js → chunk-brybqw5k.js} +1 -1
  78. package/dist/{chunk-s1mqyqmm.js → chunk-bs1sd0e0.js} +12 -8
  79. package/dist/chunk-bs1sd0e0.js.map +18 -0
  80. package/dist/{chunk-vehcr9eb.js → chunk-cg7cygfj.js} +1 -1
  81. package/dist/chunk-dq3t5sr3.js +114 -0
  82. package/dist/chunk-dq3t5sr3.js.map +11 -0
  83. package/dist/{chunk-r2psmn42.js → chunk-eg6xqef7.js} +1 -1
  84. package/dist/{chunk-zxhym8tr.js → chunk-f05994as.js} +1 -1
  85. package/dist/{chunk-5t9gm5tt.js → chunk-fmgf9h5e.js} +38 -14
  86. package/dist/chunk-fmgf9h5e.js.map +22 -0
  87. package/dist/{chunk-ey1p8w68.js → chunk-gaj8djsw.js} +80 -4
  88. package/dist/chunk-gaj8djsw.js.map +13 -0
  89. package/dist/{chunk-1yh6jgtz.js → chunk-grt2j5vp.js} +2 -2
  90. package/dist/{chunk-zft9bzbc.js → chunk-hkbks1xm.js} +2 -1
  91. package/dist/{chunk-zft9bzbc.js.map → chunk-hkbks1xm.js.map} +3 -3
  92. package/dist/{chunk-rtdrm592.js → chunk-htdzx40w.js} +2 -2
  93. package/dist/{chunk-bc3y6gff.js → chunk-jka26v8c.js} +1 -1
  94. package/dist/{chunk-m3qx2pns.js → chunk-jt012fxq.js} +28 -12
  95. package/dist/{chunk-m3qx2pns.js.map → chunk-jt012fxq.js.map} +5 -5
  96. package/dist/{chunk-k3jh8gsg.js → chunk-kft7mp7z.js} +20 -3
  97. package/dist/chunk-kft7mp7z.js.map +10 -0
  98. package/dist/{chunk-qavwr628.js → chunk-n1hbwc6y.js} +5 -6
  99. package/dist/chunk-n1hbwc6y.js.map +12 -0
  100. package/dist/chunk-nxysqbt0.js.map +2 -2
  101. package/dist/{chunk-pqvvqc65.js → chunk-pqj8vff9.js} +3 -3
  102. package/dist/{chunk-wqe9shx2.js → chunk-qbd282aa.js} +2 -2
  103. package/dist/{chunk-e91fmg6t.js → chunk-qsa7nw6f.js} +2 -1
  104. package/dist/{chunk-e91fmg6t.js.map → chunk-qsa7nw6f.js.map} +3 -3
  105. package/dist/{chunk-rg725hry.js → chunk-s8xxef60.js} +83 -33
  106. package/dist/{chunk-rg725hry.js.map → chunk-s8xxef60.js.map} +5 -5
  107. package/dist/{chunk-fzae1jpq.js → chunk-t19wjmnc.js} +5 -5
  108. package/dist/{chunk-paxabbqd.js → chunk-tapdssb5.js} +1 -1
  109. package/dist/{chunk-dhkc9b23.js → chunk-v8a1qjzp.js} +1 -1
  110. package/dist/{chunk-q8d9p0tb.js → chunk-wzcjhv54.js} +8 -1
  111. package/dist/{chunk-q8d9p0tb.js.map → chunk-wzcjhv54.js.map} +3 -3
  112. package/dist/{chunk-pc7kra3k.js → chunk-xavet0qs.js} +1 -1
  113. package/dist/{chunk-0hkdtwqk.js → chunk-xf76csps.js} +5 -5
  114. package/dist/{chunk-m9ketb51.js → chunk-ygvay56w.js} +1 -1
  115. package/dist/{chunk-b4escq4c.js → chunk-ykchk644.js} +6 -6
  116. package/dist/{chunk-k29n4176.js → chunk-ym1bqd98.js} +6 -6
  117. package/dist/connectors/connections/capability.d.ts +11 -0
  118. package/dist/connectors/connections/capability.d.ts.map +1 -1
  119. package/dist/connectors/connections/internal.d.ts +2 -1
  120. package/dist/connectors/connections/internal.d.ts.map +1 -1
  121. package/dist/connectors/connections/internal.js +8 -4
  122. package/dist/connectors/connections/internal.js.map +1 -1
  123. package/dist/connectors/connections/service.d.ts +9 -1
  124. package/dist/connectors/connections/service.d.ts.map +1 -1
  125. package/dist/connectors/execution.d.ts +7 -1
  126. package/dist/connectors/execution.d.ts.map +1 -1
  127. package/dist/connectors/service.d.ts +5 -1
  128. package/dist/connectors/service.d.ts.map +1 -1
  129. package/dist/deploy/types.d.ts +4 -1
  130. package/dist/deploy/types.d.ts.map +1 -1
  131. package/dist/events/execution.d.ts +8 -1
  132. package/dist/events/execution.d.ts.map +1 -1
  133. package/dist/events/types/syncs.d.ts +4 -0
  134. package/dist/events/types/syncs.d.ts.map +1 -1
  135. package/dist/execution/agent.js +37 -36
  136. package/dist/execution/agent.js.map +1 -1
  137. package/dist/execution/authorized-object-reader.d.ts +4 -0
  138. package/dist/execution/authorized-object-reader.d.ts.map +1 -1
  139. package/dist/execution/object-reader-ontology.d.ts +3 -0
  140. package/dist/execution/object-reader-ontology.d.ts.map +1 -1
  141. package/dist/execution/primitive.js +36 -35
  142. package/dist/execution/primitive.js.map +1 -1
  143. package/dist/execution/request.d.ts +1 -1
  144. package/dist/execution/request.d.ts.map +1 -1
  145. package/dist/execution/request.js +33 -32
  146. package/dist/execution/request.js.map +3 -3
  147. package/dist/http/api-routes.d.ts.map +1 -1
  148. package/dist/http/index.js +1 -1
  149. package/dist/index.d.ts +5 -5
  150. package/dist/index.d.ts.map +1 -1
  151. package/dist/index.js +61 -59
  152. package/dist/index.js.map +1 -1
  153. package/dist/maintenance/index.js +1 -1
  154. package/dist/materializer/index.js +22 -21
  155. package/dist/materializer/index.js.map +1 -1
  156. package/dist/models/audio/runtime.d.ts.map +1 -1
  157. package/dist/models/audio/types.d.ts +19 -0
  158. package/dist/models/audio/types.d.ts.map +1 -1
  159. package/dist/models/execution/index.js +20 -19
  160. package/dist/models/execution/index.js.map +1 -1
  161. package/dist/models/index.d.ts +1 -1
  162. package/dist/models/index.d.ts.map +1 -1
  163. package/dist/objects/index.js +36 -35
  164. package/dist/objects/index.js.map +1 -1
  165. package/dist/objects/query/executor.d.ts +3 -1
  166. package/dist/objects/query/executor.d.ts.map +1 -1
  167. package/dist/objects/query/explain.d.ts +3 -1
  168. package/dist/objects/query/explain.d.ts.map +1 -1
  169. package/dist/objects/query/index.d.ts +1 -1
  170. package/dist/objects/query/index.d.ts.map +1 -1
  171. package/dist/objects/query/index.js +19 -18
  172. package/dist/objects/query/index.js.map +1 -1
  173. package/dist/objects/query/link-query-clearance.d.ts +3 -0
  174. package/dist/objects/query/link-query-clearance.d.ts.map +1 -1
  175. package/dist/objects/query/links.d.ts +1 -1
  176. package/dist/objects/query/links.d.ts.map +1 -1
  177. package/dist/objects/query/validate.d.ts +17 -0
  178. package/dist/objects/query/validate.d.ts.map +1 -1
  179. package/dist/objects/sdk/runtime-query-executor.d.ts +1 -1
  180. package/dist/objects/sdk/runtime-query-executor.d.ts.map +1 -1
  181. package/dist/ontology/index.js +3 -3
  182. package/dist/ontology/internal.js +3 -3
  183. package/dist/pipelines/index.js +21 -20
  184. package/dist/pipelines/index.js.map +1 -1
  185. package/dist/projections/internal.js +20 -19
  186. package/dist/projections/internal.js.map +1 -1
  187. package/dist/queues/in-memory.d.ts +1 -1
  188. package/dist/queues/in-memory.d.ts.map +1 -1
  189. package/dist/runtime/host.d.ts.map +1 -1
  190. package/dist/runtime/internal.js +24 -23
  191. package/dist/runtime/internal.js.map +2 -2
  192. package/dist/runtime/locale.d.ts +0 -2
  193. package/dist/runtime/locale.d.ts.map +1 -1
  194. package/dist/runtime/sixb.d.ts.map +1 -1
  195. package/dist/sandboxes/auth.d.ts +26 -4
  196. package/dist/sandboxes/auth.d.ts.map +1 -1
  197. package/dist/sandboxes/index.d.ts +3 -1
  198. package/dist/sandboxes/index.d.ts.map +1 -1
  199. package/dist/sandboxes/index.js +5 -5
  200. package/dist/security/view-conditions.d.ts.map +1 -1
  201. package/dist/shares/internal.js +16 -15
  202. package/dist/shares/internal.js.map +2 -2
  203. package/dist/storage/agents/in-memory.d.ts +18 -1
  204. package/dist/storage/agents/in-memory.d.ts.map +1 -1
  205. package/dist/storage/agents/index.d.ts +1 -1
  206. package/dist/storage/agents/index.d.ts.map +1 -1
  207. package/dist/storage/agents/provider.d.ts +43 -9
  208. package/dist/storage/agents/provider.d.ts.map +1 -1
  209. package/dist/storage/agents/provider.js +18 -2
  210. package/dist/storage/agents/provider.js.map +1 -1
  211. package/dist/storage/agents/types.d.ts +136 -3
  212. package/dist/storage/agents/types.d.ts.map +1 -1
  213. package/dist/storage/ai-cost/analytics.d.ts +3 -2
  214. package/dist/storage/ai-cost/analytics.d.ts.map +1 -1
  215. package/dist/storage/ai-cost/provider.js +4 -3
  216. package/dist/storage/ai-cost/provider.js.map +1 -1
  217. package/dist/storage/ai-cost/types.d.ts +5 -1
  218. package/dist/storage/ai-cost/types.d.ts.map +1 -1
  219. package/dist/storage/artifacts/in-memory.d.ts.map +1 -1
  220. package/dist/storage/artifacts/record.d.ts +3 -1
  221. package/dist/storage/artifacts/record.d.ts.map +1 -1
  222. package/dist/storage/artifacts/types.d.ts +7 -0
  223. package/dist/storage/artifacts/types.d.ts.map +1 -1
  224. package/dist/storage/file-upload-sessions/provider.js +7 -7
  225. package/dist/storage/index.d.ts +2 -2
  226. package/dist/storage/index.d.ts.map +1 -1
  227. package/dist/storage/index.js +22 -21
  228. package/dist/storage/index.js.map +1 -1
  229. package/dist/storage/internal.js +8 -8
  230. package/dist/storage/operation-scope.d.ts.map +1 -1
  231. package/dist/storage/operation-scope.js +1 -1
  232. package/dist/storage/sync-runs/idempotency.d.ts.map +1 -1
  233. package/dist/storage/sync-runs/in-memory.d.ts +2 -1
  234. package/dist/storage/sync-runs/in-memory.d.ts.map +1 -1
  235. package/dist/storage/sync-runs/index.d.ts +1 -1
  236. package/dist/storage/sync-runs/index.d.ts.map +1 -1
  237. package/dist/storage/sync-runs/types.d.ts +27 -2
  238. package/dist/storage/sync-runs/types.d.ts.map +1 -1
  239. package/dist/storage/workflow-runs/provider.js +7 -7
  240. package/dist/syncs/accounts.d.ts +36 -0
  241. package/dist/syncs/accounts.d.ts.map +1 -0
  242. package/dist/syncs/builders.d.ts.map +1 -1
  243. package/dist/syncs/connections.d.ts +36 -0
  244. package/dist/syncs/connections.d.ts.map +1 -0
  245. package/dist/syncs/execution.d.ts +14 -4
  246. package/dist/syncs/execution.d.ts.map +1 -1
  247. package/dist/syncs/index.d.ts +2 -1
  248. package/dist/syncs/index.d.ts.map +1 -1
  249. package/dist/syncs/index.js +22 -21
  250. package/dist/syncs/index.js.map +1 -1
  251. package/dist/syncs/request.d.ts +16 -2
  252. package/dist/syncs/request.d.ts.map +1 -1
  253. package/dist/syncs/run-dispatch.d.ts +14 -2
  254. package/dist/syncs/run-dispatch.d.ts.map +1 -1
  255. package/dist/testing/agent-approval-storage-contract.d.ts.map +1 -1
  256. package/dist/testing/agent-inbox-storage-contract.d.ts.map +1 -1
  257. package/dist/testing/agent-storage-contract.d.ts.map +1 -1
  258. package/dist/testing/ai-cost-storage-contract.d.ts.map +1 -1
  259. package/dist/testing/artifact-storage-contract.d.ts.map +1 -1
  260. package/dist/testing/index.js +1051 -58
  261. package/dist/testing/index.js.map +8 -8
  262. package/dist/testing/run-claim-storage-contract.d.ts.map +1 -1
  263. package/dist/webhooks/internal.js +17 -16
  264. package/dist/webhooks/internal.js.map +2 -2
  265. package/dist/workers/index.js +66 -13
  266. package/dist/workers/index.js.map +4 -4
  267. package/dist/workers/queue-worker.d.ts +5 -0
  268. package/dist/workers/queue-worker.d.ts.map +1 -1
  269. package/dist/workers/worker.d.ts +8 -0
  270. package/dist/workers/worker.d.ts.map +1 -1
  271. package/dist/workflows/index.js +42 -40
  272. package/dist/workflows/index.js.map +1 -1
  273. package/package.json +7 -1
  274. package/src/actions/validation.ts +3 -1
  275. package/src/agents/children.ts +6 -0
  276. package/src/agents/errors.ts +3 -0
  277. package/src/agents/execution.ts +170 -20
  278. package/src/agents/index.ts +4 -0
  279. package/src/agents/model-routing.ts +25 -9
  280. package/src/agents/request.ts +759 -40
  281. package/src/agents/run-events.ts +235 -38
  282. package/src/agents/run-session-children.ts +13 -2
  283. package/src/agents/run-turn.ts +140 -23
  284. package/src/agents/streams/index.ts +2 -0
  285. package/src/agents/streams/internal.ts +12 -0
  286. package/src/agents/streams/protocol.ts +69 -1
  287. package/src/agents/streams/steps.ts +131 -0
  288. package/src/agents/thread-access.ts +57 -2
  289. package/src/artifacts/publish/merge.ts +14 -3
  290. package/src/artifacts/run-query.ts +5 -2
  291. package/src/calendar.ts +195 -0
  292. package/src/connectors/connections/capability.ts +40 -0
  293. package/src/connectors/connections/internal.ts +3 -0
  294. package/src/connectors/connections/service.ts +74 -5
  295. package/src/connectors/execution.ts +5 -6
  296. package/src/connectors/service.ts +23 -0
  297. package/src/deploy/types.ts +4 -1
  298. package/src/events/execution.ts +42 -2
  299. package/src/events/types/syncs.ts +4 -0
  300. package/src/execution/authorized-object-reader.ts +33 -5
  301. package/src/execution/object-reader-ontology.ts +6 -0
  302. package/src/execution/request.ts +1 -0
  303. package/src/http/api-routes.ts +8 -0
  304. package/src/index.ts +18 -2
  305. package/src/models/audio/runtime.ts +57 -14
  306. package/src/models/audio/types.ts +20 -0
  307. package/src/models/index.ts +1 -0
  308. package/src/objects/query/executor.ts +4 -0
  309. package/src/objects/query/explain.ts +5 -0
  310. package/src/objects/query/index.ts +1 -0
  311. package/src/objects/query/link-query-clearance.ts +4 -1
  312. package/src/objects/query/links.ts +5 -1
  313. package/src/objects/query/validate.ts +33 -1
  314. package/src/objects/sdk/runtime-query-executor.ts +7 -3
  315. package/src/runtime/host.ts +13 -7
  316. package/src/runtime/locale.ts +0 -10
  317. package/src/runtime/sixb.ts +12 -2
  318. package/src/sandboxes/README.md +3 -1
  319. package/src/sandboxes/auth.ts +32 -4
  320. package/src/sandboxes/index.ts +15 -1
  321. package/src/security/view-conditions.ts +2 -1
  322. package/src/storage/agents/in-memory.ts +271 -6
  323. package/src/storage/agents/index.ts +10 -0
  324. package/src/storage/agents/provider.ts +170 -13
  325. package/src/storage/agents/types.ts +148 -3
  326. package/src/storage/ai-cost/analytics.ts +22 -43
  327. package/src/storage/ai-cost/types.ts +5 -1
  328. package/src/storage/artifacts/in-memory.ts +20 -5
  329. package/src/storage/artifacts/record.ts +8 -2
  330. package/src/storage/artifacts/types.ts +7 -0
  331. package/src/storage/index.ts +11 -0
  332. package/src/storage/operation-scope.ts +1 -0
  333. package/src/storage/sync-runs/idempotency.ts +1 -0
  334. package/src/storage/sync-runs/in-memory.ts +43 -1
  335. package/src/storage/sync-runs/index.ts +1 -0
  336. package/src/storage/sync-runs/types.ts +30 -1
  337. package/src/syncs/accounts.ts +85 -0
  338. package/src/syncs/builders.ts +18 -1
  339. package/src/syncs/connections.ts +123 -0
  340. package/src/syncs/execution.ts +64 -22
  341. package/src/syncs/index.ts +3 -0
  342. package/src/syncs/request.ts +81 -23
  343. package/src/syncs/run-dispatch.ts +69 -7
  344. package/src/testing/agent-approval-storage-contract.ts +123 -0
  345. package/src/testing/agent-inbox-storage-contract.ts +59 -0
  346. package/src/testing/agent-storage-contract.ts +767 -8
  347. package/src/testing/ai-cost-storage-contract.ts +80 -0
  348. package/src/testing/artifact-storage-contract.ts +129 -0
  349. package/src/testing/run-claim-storage-contract.ts +116 -0
  350. package/src/workers/README.md +4 -1
  351. package/src/workers/lost-runs.ts +1 -0
  352. package/src/workers/queue-worker.ts +16 -5
  353. package/src/workers/worker.ts +67 -7
  354. package/dist/chunk-5a4a52tq.js.map +0 -10
  355. package/dist/chunk-5t9gm5tt.js.map +0 -22
  356. package/dist/chunk-68hm50qh.js.map +0 -13
  357. package/dist/chunk-aw1z0gre.js +0 -234
  358. package/dist/chunk-aw1z0gre.js.map +0 -12
  359. package/dist/chunk-ey1p8w68.js.map +0 -13
  360. package/dist/chunk-k3jh8gsg.js.map +0 -10
  361. package/dist/chunk-qavwr628.js.map +0 -12
  362. package/dist/chunk-s1mqyqmm.js.map +0 -18
  363. package/dist/chunk-zeykm8my.js.map +0 -14
  364. /package/dist/{chunk-stmxh0hv.js.map → chunk-3neam1y5.js.map} +0 -0
  365. /package/dist/{chunk-0mvjpgvm.js.map → chunk-425ydk65.js.map} +0 -0
  366. /package/dist/{chunk-s5pj68fa.js.map → chunk-5sswe5ej.js.map} +0 -0
  367. /package/dist/{chunk-q9nkpr8k.js.map → chunk-9tpmfh3n.js.map} +0 -0
  368. /package/dist/{chunk-naxjka9v.js.map → chunk-brhp9d97.js.map} +0 -0
  369. /package/dist/{chunk-8a8k38tz.js.map → chunk-brybqw5k.js.map} +0 -0
  370. /package/dist/{chunk-vehcr9eb.js.map → chunk-cg7cygfj.js.map} +0 -0
  371. /package/dist/{chunk-r2psmn42.js.map → chunk-eg6xqef7.js.map} +0 -0
  372. /package/dist/{chunk-zxhym8tr.js.map → chunk-f05994as.js.map} +0 -0
  373. /package/dist/{chunk-1yh6jgtz.js.map → chunk-grt2j5vp.js.map} +0 -0
  374. /package/dist/{chunk-rtdrm592.js.map → chunk-htdzx40w.js.map} +0 -0
  375. /package/dist/{chunk-bc3y6gff.js.map → chunk-jka26v8c.js.map} +0 -0
  376. /package/dist/{chunk-pqvvqc65.js.map → chunk-pqj8vff9.js.map} +0 -0
  377. /package/dist/{chunk-wqe9shx2.js.map → chunk-qbd282aa.js.map} +0 -0
  378. /package/dist/{chunk-fzae1jpq.js.map → chunk-t19wjmnc.js.map} +0 -0
  379. /package/dist/{chunk-paxabbqd.js.map → chunk-tapdssb5.js.map} +0 -0
  380. /package/dist/{chunk-dhkc9b23.js.map → chunk-v8a1qjzp.js.map} +0 -0
  381. /package/dist/{chunk-pc7kra3k.js.map → chunk-xavet0qs.js.map} +0 -0
  382. /package/dist/{chunk-0hkdtwqk.js.map → chunk-xf76csps.js.map} +0 -0
  383. /package/dist/{chunk-m9ketb51.js.map → chunk-ygvay56w.js.map} +0 -0
  384. /package/dist/{chunk-b4escq4c.js.map → chunk-ykchk644.js.map} +0 -0
  385. /package/dist/{chunk-k29n4176.js.map → chunk-ym1bqd98.js.map} +0 -0
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/storage/agents/errors.ts", "../src/storage/agents/provider.ts", "../src/agents/ids.ts", "../src/agents/types.ts"],
4
+ "sourcesContent": [
5
+ "export type AgentStorageErrorCode =\n | \"thread_not_found\"\n /** A conversation's operation on a sub-agent's thread: a turn, a fork, a participant. */\n | \"thread_not_conversation\"\n | \"active_run_exists\"\n | \"active_child_limit\"\n | \"run_not_found\"\n | \"invalid_input\"\n | \"invalid_state\"\n | \"execution_lost\"\n | \"duplicate_id\"\n | \"participant_limit\"\n | \"inbox_limit\"\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 { isDeepStrictEqual } from \"node:util\"\nimport { createAgentMessageId, createCopiedAgentContextCheckpointId } from \"../../agents/ids\"\nimport type { AgentMessagePart } from \"../../agents/message\"\nimport { AGENT_REASONING_LEVELS } from \"../../agents/types\"\nimport type { Principal, UserPrincipal } from \"../../auth\"\nimport { isFileRef } from \"../../blob-storage/validation\"\nimport { isJsonObject, isPlainRecord } from \"../../json\"\nimport { isLanguageModelTier, LANGUAGE_MODEL_TIERS } from \"../../models/catalog\"\nimport { isModelReasoning } from \"../../models/language-model\"\nimport type { ExecutionRecord, ExecutionStorage } from \"../executions\"\nimport { findAgentRunExecution } from \"../executions/run-link\"\nimport { AgentStorageError } from \"./errors\"\nimport { AGENT_COMPUTER_BACKGROUND_COMMANDS_MAX, AGENT_THREAD_INBOX_MAX_ITEMS } from \"./types\"\n\nexport { AGENT_COMPUTER_BACKGROUND_COMMANDS_MAX, AGENT_THREAD_INBOX_MAX_ITEMS }\n\nimport type {\n AddAgentThreadParticipantsInput,\n AgentApprovalCall,\n AgentApprovalMode,\n AgentApprovalRecord,\n AgentApprovalStatus,\n AgentBackgroundCommandRef,\n AgentComputerSessionRecord,\n AgentContextCheckpointRecord,\n AgentInboxItemRecord,\n AgentInboxMode,\n AgentInboxSpec,\n AgentMemoryChange,\n AgentMessageRecord,\n AgentRunRecord,\n AgentThreadComputer,\n AgentThreadParticipantRecord,\n AgentThreadPlace,\n AgentThreadRecord,\n AgentThreadSandboxParams,\n AgentThreadSandboxState,\n AgentTokenRateRecord,\n ConsumeClaimedAgentInboxInput,\n ConversationAgentRunRecord,\n ConversationAgentRunSpec,\n CreateAgentContextCheckpointInput,\n CreateSubagentRunInput,\n DeleteAgentContextCheckpointsAfterSeqInput,\n DeleteAgentMessagesFromSeqInput,\n EnqueueAgentInboxItemInput,\n FinishAgentRunInput,\n ForkAgentThreadInput,\n ListAgentApprovalsInput,\n RequestAgentApprovalInput,\n SaveAgentMemoryInput,\n StopAgentApprovalsInput,\n SubagentRunFile,\n SubagentRunRecord,\n SubagentRunResult,\n TakeAgentInboxSteersInput,\n TransitionAgentThreadSandboxInput,\n UpdateAgentInboxItemInput,\n} from \"./types\"\nimport {\n AGENT_APPROVAL_MODES,\n AGENT_HOLDING_APPROVAL_MODES,\n AGENT_INBOX_MODES,\n AGENT_MEMORY_HISTORY_DAYS,\n AGENT_TOKEN_RATE_MAX_BYTES_PER_TOKEN,\n AGENT_TOKEN_RATE_MIN_BYTES_PER_TOKEN,\n} from \"./types\"\n\nconst SANDBOX_NAME_PATTERN = /^[a-zA-Z0-9-]{1,80}$/\n\n/**\n * Shared state machine. Providers must lock the run, then thread, around this decision/write.\n *\n * A conversation has a workspace once its sandbox is configured. A sub-agent's thread may keep a\n * blank one while the sub-agent pauses, fenced by the thread's active run as a turn's is. Its\n * next run starts a fresh one where a conversation's would need an explicit recreation.\n */\nexport function transitionAgentThreadSandbox(\n thread: AgentThreadRecord | null,\n run: AgentRunRecord | null,\n input: TransitionAgentThreadSandboxInput\n): AgentThreadSandboxState {\n const fail = (message: string): never => {\n throw new AgentStorageError(\"invalid_state\", `[Sixb] Sandbox ${message}`)\n }\n if (!thread || (!thread.sandboxParams && thread.kind !== \"subagent\")) {\n return fail(\"is not configured on this thread.\")\n }\n if (!SANDBOX_NAME_PATTERN.test(input.name)) return fail(\"name is invalid.\")\n const state = thread.sandboxState\n if (input.action === \"recreate\") {\n if (thread.activeRunId !== null) return fail(\"cannot be recreated during an active run.\")\n if (!state || state.name !== input.expectedSandboxName || input.name === state.name)\n return fail(\"changed; reload before recreating.\")\n if (![\"busy\", \"blocked\", \"unavailable\"].includes(state.status)) {\n return fail(\"does not require recovery.\")\n }\n return {\n name: input.name,\n status: \"new\",\n initialized: false,\n resetAt: new Date().toISOString(),\n }\n }\n if (input.action === \"restore\") {\n if (thread.activeRunId !== null) return fail(\"cannot be restored during an active run.\")\n if (!state || state.name !== input.name) return fail(\"changed; reload before restoring.\")\n if (state.status !== \"busy\" && state.status !== \"blocked\") {\n return fail(\"does not require recovery.\")\n }\n // Only a workspace its run finished preparing holds anything to go on from. A provider never\n // resumes a VM that still runs, so the next run cannot reach a late operation of the last one.\n if (!state.initialized) return fail(\"was never prepared; start fresh instead.\")\n return {\n name: state.name,\n status: \"ready\",\n initialized: true,\n ...(state.sourceFingerprint ? { sourceFingerprint: state.sourceFingerprint } : {}),\n ...(state.resetAt ? { resetAt: state.resetAt } : {}),\n }\n }\n if (\n !run ||\n run.threadId !== thread.id ||\n run.status !== \"running\" ||\n thread.activeRunId !== run.id ||\n run.id !== input.runId ||\n run.execution?.token !== input.executionToken ||\n run.execution.queueLeaseExpiresAt.getTime() <= Date.now()\n ) {\n throw new AgentStorageError(\"execution_lost\", \"[Sixb] Sandbox execution ownership was lost.\")\n }\n if (input.action === \"acquire\") {\n if (state && state.status !== \"new\" && state.status !== \"ready\") {\n if (thread.kind === \"subagent\" && state.name !== input.name) {\n return startSubagentWorkspaceAgain(input)\n }\n return fail(\"requires recovery; previous operations may still be in flight.\")\n }\n if (state && state.name !== input.name) return fail(\"name changed.\")\n if (!/^[a-f0-9]{64}$/.test(input.sourceFingerprint))\n return fail(\"source fingerprint is invalid.\")\n if (state?.sourceFingerprint && state.sourceFingerprint !== input.sourceFingerprint) {\n return fail(\"source identity changed; the existing checkout was not opened.\")\n }\n return {\n name: input.name,\n status: \"busy\",\n initialized: state?.initialized ?? false,\n ...(state?.resetAt ? { resetAt: state.resetAt } : {}),\n sourceFingerprint: input.sourceFingerprint,\n owner: { runId: input.runId, executionToken: input.executionToken },\n }\n }\n if (\n state?.status !== \"busy\" ||\n state.name !== input.name ||\n state.owner?.runId !== input.runId ||\n state.owner.executionToken !== input.executionToken\n ) {\n return fail(\"is not owned by this execution.\")\n }\n if (input.action === \"replace\") {\n if (\n !state.initialized ||\n input.nextName === state.name ||\n !SANDBOX_NAME_PATTERN.test(input.nextName)\n ) {\n return fail(\"replacement requires initialized state and a fresh valid name.\")\n }\n // Only the owning worker may report confirmed loss; retain its fence across replacement.\n return {\n ...state,\n name: input.nextName,\n initialized: false,\n resetAt: new Date().toISOString(),\n }\n }\n if (input.status === \"ready\" && !input.initialized) return fail(\"initialization is incomplete.\")\n return {\n name: state.name,\n status: input.status,\n initialized: input.initialized,\n sourceFingerprint: state.sourceFingerprint,\n ...(state.resetAt ? { resetAt: state.resetAt } : {}),\n }\n}\n\n/**\n * A sub-agent's thread whose workspace an ended run left destroyed, unsaved or in doubt: the run\n * that continues it starts from a fresh one, under a new name, and is told its files were reset.\n * Nobody can recreate a sub-agent's workspace, and the thread's single active run is this one, so\n * whatever the old name still holds is never opened again.\n */\nfunction startSubagentWorkspaceAgain(\n input: Extract<TransitionAgentThreadSandboxInput, { readonly action: \"acquire\" }>\n): AgentThreadSandboxState {\n if (!/^[a-f0-9]{64}$/.test(input.sourceFingerprint)) {\n throw new AgentStorageError(\"invalid_state\", \"[Sixb] Sandbox source fingerprint is invalid.\")\n }\n return {\n name: input.name,\n status: \"busy\",\n initialized: false,\n resetAt: new Date().toISOString(),\n sourceFingerprint: input.sourceFingerprint,\n owner: { runId: input.runId, executionToken: input.executionToken },\n }\n}\n\n/** Snapshot application parameters independently of worker-owned sandbox state. */\nexport function snapshotAgentThreadSandboxParams(value: unknown): AgentThreadSandboxParams {\n if (!isPlainRecord(value) || !isJsonObject(value)) {\n throw new AgentStorageError(\n \"invalid_input\",\n \"[Sixb] Thread sandbox must contain only JSON params.\"\n )\n }\n return structuredClone(value)\n}\n\n/**\n * The users an add actually adds: those not already taking part. Providers call it under the\n * thread's lock with the participants they read there, so the cap holds across concurrent adds.\n * Who may be added is the caller's decision; this enforces only the cap.\n */\nexport function participantsToAdd(\n input: AddAgentThreadParticipantsInput,\n existing: readonly AgentThreadParticipantRecord[],\n prefix = \"Sixb\"\n): readonly UserPrincipal[] {\n const taken = new Set(existing.map((participant) => participant.principal.id))\n const added = input.principals.filter((principal) => !taken.has(principal.id))\n\n if (existing.length + added.length > input.maxParticipants) {\n throw new AgentStorageError(\n \"participant_limit\",\n `[${prefix}] Agent thread '${input.threadId}' can have at most ${input.maxParticipants} participants.`\n )\n }\n\n return added\n}\n\n/**\n * Participants oldest first, then by user id and thread id compared as UTF-8 bytes: the order\n * PostgreSQL's \"C\" collation and SQLite's binary one give, so every provider lists them alike.\n */\nexport function compareAgentThreadParticipants(\n left: AgentThreadParticipantRecord,\n right: AgentThreadParticipantRecord\n): number {\n return (\n left.addedAt.getTime() - right.addedAt.getTime() ||\n Buffer.compare(Buffer.from(left.principal.id), Buffer.from(right.principal.id)) ||\n Buffer.compare(Buffer.from(left.threadId), Buffer.from(right.threadId))\n )\n}\n\nconst ARTIFACT_ID_TOKEN = /art_[0-9a-z]{10}/g\n\n/**\n * Text with each artifact id the copies map replaced by its copy's: a copied message's parts, as\n * JSON, or a summary. Ids are fixed-length tokens, so one never matches inside another.\n */\nexport function remapArtifactIds(\n text: string,\n copies: Readonly<Record<string, string>> | undefined\n): string {\n if (!copies || Object.keys(copies).length === 0) return text\n return text.replace(ARTIFACT_ID_TOKEN, (id) => copies[id] ?? id)\n}\n\n/** What a fork reads from its source thread, inside the provider's transaction. */\nexport interface AgentThreadForkSource {\n /** Where the source runs: a fork starts in the cloud, without the files its turns worked on. */\n readonly workspace: {\n readonly runsOn?: string | null\n readonly movedAt?: Date | string | null\n }\n /** The active run's trigger message, when a turn is running. */\n readonly triggerMessageId?: string\n /**\n * Every message of the source, ordered by ascending `seq`. `counted: false` marks one the thread\n * does not count ({@link countsAsThreadMessage}); a provider reads it from the parts it copies.\n */\n readonly messages: readonly (Pick<AgentMessageRecord, \"id\" | \"seq\"> & {\n readonly counted?: boolean\n })[]\n /** Every checkpoint of the source, latest first, in `getLatest` order. */\n readonly checkpoints: readonly AgentContextCheckpointRecord[]\n}\n\n/** The rows a provider writes for a fork. */\nexport interface AgentThreadForkPlan {\n readonly thread: AgentThreadRecord\n /** The source messages to copy, in `seq` order, with the id of each copy. */\n readonly messages: readonly { readonly sourceId: string; readonly id: string }[]\n /** The seq of the last message copied, 0 when none: the copy's newest, as copies keep theirs. */\n readonly headSeq: number\n readonly checkpoint?: AgentContextCheckpointRecord\n}\n\n/** `fromSeq` names a message of the thread: sequences start at 1. */\nexport function assertDeleteAgentMessagesFromSeqInput(\n input: DeleteAgentMessagesFromSeqInput,\n prefix = \"Sixb\"\n): void {\n if (!Number.isSafeInteger(input.fromSeq) || input.fromSeq < 1) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent message 'fromSeq' must be a positive safe integer.`\n )\n }\n}\n\n/** `afterSeq` is the last sequence whose summaries stay: 0 keeps none. */\nexport function assertDeleteAgentContextCheckpointsAfterSeqInput(\n input: DeleteAgentContextCheckpointsAfterSeqInput,\n prefix = \"Sixb\"\n): void {\n if (!Number.isSafeInteger(input.afterSeq) || input.afterSeq < 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent context checkpoint 'afterSeq' must be a non-negative safe integer.`\n )\n }\n}\n\n/**\n * Whether a message counts in its thread's `messageCount`, which reads as what the conversation\n * shows. The message Sixb writes to resume a paused turn carries only how its calls ended, which the\n * chat shows on their cards: it is not counted.\n */\nexport function countsAsThreadMessage(message: Pick<AgentMessageRecord, \"parts\">): boolean {\n return !(\n message.parts.length > 0 && message.parts.every((part) => part.type === \"approval-outcome\")\n )\n}\n\n/**\n * Whether a message past a reader's place is new to them: every Agent answer and every other\n * person's message. What they wrote themselves is not, and neither is a message the thread does\n * not count. An Agent answer carries its requester as author, so only a user message is theirs.\n * The SQL providers say the same in their `unread` count.\n */\nexport function isUnreadFor(\n message: Pick<AgentMessageRecord, \"role\" | \"authorPrincipal\" | \"parts\">,\n reader: UserPrincipal\n): boolean {\n if (!countsAsThreadMessage(message)) return false\n\n const author = message.authorPrincipal\n const ownMessage = message.role === \"user\" && author?.type === \"user\" && author.id === reader.id\n\n return !ownMessage\n}\n\n/**\n * Decide what a fork copies. While a turn is running, the fork copies what came before its trigger\n * message, so the copy never has a gap; otherwise it copies everything. Copies keep their `seq`,\n * so the latest checkpoint whose observed head was copied projects unchanged.\n *\n * The plan mints the ids of the copies: which messages are copied is only known here, under the\n * provider's lock, so the caller cannot supply them.\n */\nexport function planAgentThreadFork(\n input: ForkAgentThreadInput,\n source: AgentThreadForkSource,\n prefix = \"Sixb\"\n): AgentThreadForkPlan {\n const createdAt = new Date(input.createdAt ?? new Date())\n const sandboxState = forkedSandboxState(input, createdAt, prefix)\n\n const trigger = source.messages.find((message) => message.id === source.triggerMessageId)\n const copied =\n trigger === undefined\n ? source.messages\n : source.messages.filter((message) => message.seq < trigger.seq)\n const lastCopiedSeq = copied.at(-1)?.seq ?? 0\n\n const checkpoint = source.checkpoints.find(\n (candidate) => candidate.observedHeadSeq <= lastCopiedSeq\n )\n\n const { runsOn, movedAt: moved } = source.workspace\n const movedAt = moved ? new Date(moved) : runsOn === \"computer\" ? createdAt : undefined\n const thread: AgentThreadRecord = {\n id: input.id,\n projectId: input.projectId,\n kind: \"conversation\",\n ownerPrincipal: structuredClone(input.ownerPrincipal),\n ...(input.title === undefined ? {} : { title: input.title }),\n ...(movedAt === undefined ? {} : { movedAt }),\n ...(input.sandboxParams === undefined\n ? {}\n : { sandboxParams: snapshotAgentThreadSandboxParams(input.sandboxParams) }),\n ...(sandboxState === undefined ? {} : { sandboxState }),\n status: \"active\",\n activeRunId: null,\n // No `lastMessageAt` until the fork's first new message: threads sort by it, else by their\n // creation, so a fork of an old conversation sorts with what its owner just did.\n messageCount: copied.filter((message) => message.counted !== false).length,\n createdAt,\n updatedAt: createdAt,\n }\n\n return {\n thread,\n messages: copied.map((message) => ({ sourceId: message.id, id: createAgentMessageId() })),\n headSeq: lastCopiedSeq,\n ...(checkpoint === undefined\n ? {}\n : {\n checkpoint: {\n ...copyCheckpoint(checkpoint, input.id),\n summary: remapArtifactIds(checkpoint.summary, input.artifactCopies),\n },\n }),\n }\n}\n\n/**\n * The copy starts the fork's chain: its predecessors stay in the source. Its `createdByRunId`\n * still names the source run, under a foreign key that restricts deletion: deleting runs or\n * threads later must account for the forks that copied their checkpoints.\n */\nfunction copyCheckpoint(\n checkpoint: AgentContextCheckpointRecord,\n threadId: string\n): AgentContextCheckpointRecord {\n const { previousCheckpointId: _previous, ...copied } = structuredClone(checkpoint)\n return { ...copied, id: createCopiedAgentContextCheckpointId(), threadId }\n}\n\n/** A fresh sandbox, reset at the fork, so the Agent knows earlier local files are not there. */\nfunction forkedSandboxState(\n input: ForkAgentThreadInput,\n createdAt: Date,\n prefix: string\n): AgentThreadSandboxState | undefined {\n if ((input.sandboxParams === undefined) !== (input.sandboxName === undefined)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] A forked thread needs a sandbox name exactly when it has sandbox params.`\n )\n }\n\n if (input.sandboxName === undefined) return undefined\n\n if (!SANDBOX_NAME_PATTERN.test(input.sandboxName)) {\n throw new AgentStorageError(\"invalid_input\", `[${prefix}] Sandbox name is invalid.`)\n }\n\n return {\n name: input.sandboxName,\n status: \"new\",\n initialized: false,\n resetAt: createdAt.toISOString(),\n }\n}\n\n/** Validate the provider-neutral model selection captured for a conversational turn. */\nexport function assertConversationAgentRunSpec(\n spec: ConversationAgentRunSpec,\n prefix = \"Sixb\"\n): void {\n if (!isRecord(spec) || !isRecord(spec.model)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run spec must contain a model reference.`\n )\n }\n for (const [name, value] of [\n [\"model.provider\", spec.model.provider],\n [\"model.modelId\", spec.model.modelId],\n ] as const) {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run '${name}' must not be empty.`\n )\n }\n }\n if (spec.reasoning !== undefined && !isModelReasoning(spec.reasoning)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent reasoning must be one of: ${AGENT_REASONING_LEVELS.join(\", \")}, or a nonnegative budgetTokens object.`\n )\n }\n\n if (spec.tier !== undefined && !isLanguageModelTier(spec.tier)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run 'tier' must be one of: ${LANGUAGE_MODEL_TIERS.join(\", \")}.`\n )\n }\n if (spec.tierProbabilities !== undefined && !isTierProbabilities(spec.tierProbabilities)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run 'tierProbabilities' must give each tier a probability.`\n )\n }\n\n for (const [name, value] of [\n [\"timeZone\", spec.timeZone],\n [\"locale\", spec.locale],\n ] as const) {\n if (value !== undefined && (typeof value !== \"string\" || value.trim().length === 0)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run '${name}' must be a non-empty string.`\n )\n }\n }\n assertApprovalModeField(spec.approvalMode, \"Conversational Agent run\", prefix)\n assertRunsOn(spec.runsOn, \"Conversational Agent run\", prefix)\n if (spec.computer !== undefined) {\n if (spec.runsOn !== \"computer\") {\n throw new AgentStorageError(\"invalid_input\", `[${prefix}] Only a computer's turn names one.`)\n }\n assertAgentThreadPlace(spec.computer, prefix)\n }\n}\n\n/** Validate where a thread or turn runs: `computer`, or absent for the cloud. */\nexport function assertRunsOn(value: unknown, subject: string, prefix = \"Sixb\"): void {\n if (value !== undefined && value !== \"computer\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] ${subject} 'runsOn' must be \"computer\", or absent for the cloud.`\n )\n }\n}\n\n/**\n * Validate which computer and folder a turn ran in. Both are shown back to its owner, so neither\n * holds a control character.\n */\nexport function assertAgentThreadPlace(\n value: unknown,\n prefix = \"Sixb\"\n): asserts value is AgentThreadPlace {\n const place = value as Partial<AgentThreadPlace> | null\n for (const [field, text, max] of [\n [\"id\", place?.id, 200],\n [\"folder\", place?.folder, 4096],\n ] as const) {\n if (\n typeof text !== \"string\" ||\n text.trim() === \"\" ||\n text.length > max ||\n CONTROL_CHARACTER.test(text)\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] A turn's computer '${field}' must be a non-blank string of at most ${max} characters, without control characters.`\n )\n }\n }\n}\n\n/**\n * Validate where on a computer a thread runs: the CLI's id for the computer, its name, and the\n * folder there. All are shown back to its owner, so none holds a control character.\n */\nexport function assertAgentThreadComputer(\n value: unknown,\n prefix = \"Sixb\"\n): asserts value is AgentThreadComputer {\n const computer = value as Partial<AgentThreadComputer> | null\n const fields = [\n [\"id\", computer?.id, 200],\n [\"name\", computer?.name, 120],\n [\"folder\", computer?.folder, 4096],\n ] as const\n for (const [field, text, max] of fields) {\n if (\n typeof text !== \"string\" ||\n text.trim() === \"\" ||\n text.length > max ||\n CONTROL_CHARACTER.test(text)\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] An Agent thread's computer '${field}' must be a non-blank string of at most ${max} characters, without control characters.`\n )\n }\n }\n}\n\n/** A thread runs on a computer exactly when it names the computer and folder. */\nexport function assertComputerPlace(runsOn: unknown, computer: unknown, prefix = \"Sixb\"): void {\n assertRunsOn(runsOn, \"Agent thread\", prefix)\n if (runsOn === \"computer\") assertAgentThreadComputer(computer, prefix)\n else if (computer !== undefined) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Only a thread that runs on a computer names one.`\n )\n }\n}\n\n/** Validate a computer session before a store keeps it. */\nexport function assertAgentComputerSession(\n session: Omit<AgentComputerSessionRecord, \"stopRequests\">,\n prefix = \"Sixb\"\n): void {\n if (typeof session.id !== \"string\" || session.id.trim() === \"\" || session.id.length > 200) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] A computer session's 'id' must be a non-blank string of at most 200 characters.`\n )\n }\n if (!(session.expiresAt instanceof Date) || Number.isNaN(session.expiresAt.getTime())) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] A computer session's 'expiresAt' must be a valid date.`\n )\n }\n assertAgentThreadComputer(session.computer, prefix)\n\n const commands = session.backgroundCommands ?? []\n if (!Array.isArray(commands) || commands.length > AGENT_COMPUTER_BACKGROUND_COMMANDS_MAX) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] A computer session reports at most ${AGENT_COMPUTER_BACKGROUND_COMMANDS_MAX} background commands.`\n )\n }\n for (const command of commands) {\n assertAgentBackgroundCommandRef(command, prefix)\n if (\n typeof command.command !== \"string\" ||\n ![\"running\", \"exited\", \"stopped\"].includes(command.status) ||\n (command.exitCode !== undefined && !Number.isInteger(command.exitCode)) ||\n (command.endedAt !== undefined && typeof command.endedAt !== \"string\")\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] A background command names its command, its status (running, exited or stopped), and an integer exit code once it ended.`\n )\n }\n }\n}\n\n/** Validate which background command a stop names. */\nexport function assertAgentBackgroundCommandRef(\n ref: AgentBackgroundCommandRef,\n prefix = \"Sixb\"\n): void {\n const fields = [ref?.threadId, ref?.id, ref?.startedAt]\n if (fields.some((field) => typeof field !== \"string\" || field === \"\" || field.length > 200)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] A background command is named by its thread, its id and its start, each a non-empty string of at most 200 characters.`\n )\n }\n}\n\n/** The stop requests a session keeps with `command` added: once, the newest ones. */\nexport function withStopRequest(\n requests: readonly AgentBackgroundCommandRef[],\n command: AgentBackgroundCommandRef\n): AgentBackgroundCommandRef[] {\n const same = (other: AgentBackgroundCommandRef) =>\n other.threadId === command.threadId &&\n other.id === command.id &&\n other.startedAt === command.startedAt\n if (requests.some(same)) return [...requests]\n\n const ref = { threadId: command.threadId, id: command.id, startedAt: command.startedAt }\n return [...requests, ref].slice(-AGENT_COMPUTER_BACKGROUND_COMMANDS_MAX)\n}\n\n/** C0 and C1 controls, DEL, and the marks that reorder text where a terminal or page shows it. */\nexport const CONTROL_CHARACTER =\n /[\\u0000-\\u001f\\u007f-\\u009f\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/\n\n/**\n * Refuse to assign a computer to a sub-agent's thread or one that does not exist, to move a cloud\n * thread while a turn holds it, or to move a computer's thread while a turn runs in its folder.\n */\nexport function assertAssignableComputer(\n thread: AgentThreadRecord | null,\n activeRun: AgentRunRecord | null,\n computer: AgentThreadComputer,\n id: string,\n prefix = \"Sixb\"\n): asserts thread is AgentThreadRecord {\n if (!thread) {\n throw new AgentStorageError(\"thread_not_found\", `[${prefix}] Agent thread '${id}' not found.`)\n }\n if (thread.kind !== \"conversation\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Sub-agent thread '${id}' never runs on a computer.`\n )\n }\n if (thread.runsOn !== \"computer\") {\n // A turn in flight, or one waiting for its computer, would be left where nothing runs it. A\n // turn paused on held calls passes here: the caller refuses that, with its approvals in view.\n if (activeRun?.status === \"queued\" || activeRun?.status === \"running\") {\n throw new AgentStorageError(\n \"active_run_exists\",\n `[${prefix}] A turn of Agent thread '${id}' is in progress in the cloud: stop it, or let it end, first.`\n )\n }\n return\n }\n if (movesComputerPlace(thread, computer)) assertNoTurnRunning(activeRun, id, prefix)\n}\n\n/**\n * Refuse to move a thread to the cloud unless it runs on a computer and no turn runs there now. A\n * queued turn moves with it.\n */\nexport function assertMovableToCloud(\n thread: AgentThreadRecord | null,\n activeRun: AgentRunRecord | null,\n id: string,\n prefix = \"Sixb\"\n): asserts thread is AgentThreadRecord {\n if (!thread) {\n throw new AgentStorageError(\"thread_not_found\", `[${prefix}] Agent thread '${id}' not found.`)\n }\n if (thread.runsOn !== \"computer\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent thread '${id}' runs in the cloud already.`\n )\n }\n assertNoTurnRunning(activeRun, id, prefix)\n}\n\n/** A turn works in its thread's folder until it ends: its thread moves after that. */\nfunction assertNoTurnRunning(activeRun: AgentRunRecord | null, id: string, prefix: string): void {\n if (activeRun?.status === \"running\") {\n throw new AgentStorageError(\n \"active_run_exists\",\n `[${prefix}] A turn of Agent thread '${id}' is running on its computer: stop it, or let it end, first.`\n )\n }\n}\n\n/**\n * A turn runs where its thread runs: one asked for before the thread moved, and created after, is\n * refused rather than left where nothing claims it.\n */\nexport function assertTurnInThreadPlace(\n threadRunsOn: unknown,\n spec: ConversationAgentRunSpec,\n threadId: string,\n prefix = \"Sixb\"\n): void {\n if ((threadRunsOn ?? undefined) !== spec.runsOn) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent thread '${threadId}' moved while this turn was asked for: send it again.`\n )\n }\n}\n\n/** Refuse to start a computer's turn that moved to the cloud before it started. */\nexport function assertStartsOnComputer(\n run: AgentRunRecord,\n threadPlace: AgentThreadPlace | undefined,\n place: AgentThreadPlace,\n prefix = \"Sixb\"\n): void {\n if (run.kind !== \"conversation\" || run.spec?.runsOn !== \"computer\") {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent run '${run.id}' runs in the cloud now: no computer starts it.`\n )\n }\n if (!threadPlace || !sameComputerPlace(threadPlace, place)) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent run '${run.id}' moved to another folder or computer: it starts there.`\n )\n }\n}\n\n/** Whether `computer` takes a thread's turns away from the computer or folder it had. */\nexport function movesComputerPlace(\n thread: AgentThreadRecord,\n computer: AgentThreadComputer\n): boolean {\n // One from before folders were kept ran somewhere unknown: its first folder is a move too.\n return !thread.computer || !sameComputerPlace(thread.computer, computer)\n}\n\n/** The queued turn of a thread that moves to the cloud, as the cloud runs it. */\nexport function queuedTurnInCloud(\n active: AgentRunRecord | null\n): ConversationAgentRunRecord | undefined {\n if (active?.kind !== \"conversation\" || active.status !== \"queued\") return undefined\n if (active.spec?.runsOn !== \"computer\") return undefined\n const { runsOn: _runsOn, computer: _computer, ...cloud } = active.spec\n return { ...active, spec: cloud }\n}\n\n/** The queued turn of a computer's thread that moves to another folder, with its new place. */\nexport function queuedTurnOnComputer(\n active: AgentRunRecord | null,\n computer: AgentThreadPlace\n): ConversationAgentRunRecord | undefined {\n if (active?.kind !== \"conversation\" || active.status !== \"queued\") return undefined\n if (active.spec?.runsOn !== \"computer\" || active.spec.computer === undefined) return undefined\n const place = { id: computer.id, folder: computer.folder }\n if (sameComputerPlace(active.spec.computer, place)) return undefined\n return { ...active, spec: { ...active.spec, computer: place } }\n}\n\n/**\n * Mark a paused sub-agent's saved cloud workspace unavailable when its conversation leaves the\n * cloud: a continuation on the computer updates out/, so a later return to the cloud starts fresh.\n */\nexport function unavailableChildSandboxState(\n state: AgentThreadSandboxState | undefined\n): AgentThreadSandboxState | undefined {\n if (!state || (state.status !== \"ready\" && state.status !== \"new\")) return undefined\n return { ...state, status: \"unavailable\" }\n}\n\n/** Whether two places are the same folder of the same computer, whatever they call it. */\nexport function sameComputerPlace(a: AgentThreadPlace, b: AgentThreadPlace): boolean {\n return a.id === b.id && a.folder === b.folder\n}\n\n/** Where a turn runs, as its spec records it: the cloud, or a folder of its owner's computer. */\nexport type AgentTurnPlace = Pick<ConversationAgentRunSpec, \"runsOn\" | \"computer\">\n\n/** The place a turn's spec records, from its thread's: the cloud, or a computer and its folder. */\nexport function turnPlace(\n runsOn: \"computer\" | undefined,\n computer: AgentThreadPlace | undefined\n): AgentTurnPlace {\n if (runsOn === undefined) return {}\n\n return computer\n ? { runsOn, computer: Object.freeze({ id: computer.id, folder: computer.folder }) }\n : { runsOn }\n}\n\n/**\n * The same key for two turns that ran in the same workspace: the cloud, or one folder of one\n * computer. A computer's turn from before folders were kept ran in a folder nobody knows.\n */\nexport function runPlaceKey(spec: AgentTurnPlace | undefined): string {\n if (spec?.runsOn !== \"computer\") return \"cloud\"\n return spec.computer ? `computer:${spec.computer.id}:${spec.computer.folder}` : \"computer\"\n}\n\nexport function isAgentApprovalMode(value: unknown): value is AgentApprovalMode {\n return (AGENT_APPROVAL_MODES as readonly unknown[]).includes(value)\n}\n\n/** Validate a mode a store is asked to keep, before it writes anything. */\nexport function assertAgentApprovalModeInput(\n mode: unknown,\n prefix = \"Sixb\"\n): asserts mode is AgentApprovalMode {\n if (!isAgentApprovalMode(mode)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent approval mode must be one of: ${AGENT_APPROVAL_MODES.join(\", \")}.`\n )\n }\n}\n\nfunction assertApprovalModeField(value: unknown, owner: string, prefix: string): void {\n if (value !== undefined && !isAgentApprovalMode(value)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] ${owner} 'approvalMode' must be one of: ${AGENT_APPROVAL_MODES.join(\", \")}.`\n )\n }\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction isTierProbabilities(value: unknown): boolean {\n if (!isRecord(value) || Object.keys(value).length !== LANGUAGE_MODEL_TIERS.length) return false\n\n return LANGUAGE_MODEL_TIERS.every((tier) => {\n const probability = value[tier]\n return typeof probability === \"number\" && probability >= 0 && probability <= 1\n })\n}\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}): Promise<ExecutionRecord> {\n const execution = await findAgentRunExecution({\n executions: input.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.runId,\n authority: { type: \"inherited\" },\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 return execution\n}\n\n/** Validate the provider-neutral payload of an idempotent child admission. */\nexport function assertCreateSubagentRunInput(input: CreateSubagentRunInput, prefix = \"Sixb\"): void {\n for (const [name, value] of [\n [\"id\", input.id],\n [\"projectId\", input.projectId],\n [\"executionId\", input.executionId],\n [\"parentRunId\", input.parentRunId],\n [\"parentExecutionToken\", input.parentExecutionToken],\n [\"spawnKey\", input.spawnKey],\n [\"model.provider\", input.spec.model.provider],\n [\"model.modelId\", input.spec.model.modelId],\n [\"task\", input.spec.task],\n [\"thread.id\", input.thread.id],\n [\"trigger.id\", input.trigger.id],\n ] as const) {\n if (value.trim().length === 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run '${name}' must not be empty.`\n )\n }\n }\n if (input.spawnKey.length > 128) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent spawn key must not exceed 128 characters.`\n )\n }\n if (!Number.isSafeInteger(input.maxActiveChildren) || input.maxActiveChildren < 1) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run 'maxActiveChildren' must be a positive safe integer.`\n )\n }\n if (new Set(input.spec.toolNames).size !== input.spec.toolNames.length) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run tool names must be unique.`\n )\n }\n if (input.spec.reasoning !== undefined && !isModelReasoning(input.spec.reasoning)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent reasoning must be one of: ${AGENT_REASONING_LEVELS.join(\", \")}, or a nonnegative budgetTokens object.`\n )\n }\n if (\n input.spec.maxSteps !== undefined &&\n (!Number.isSafeInteger(input.spec.maxSteps) || input.spec.maxSteps < 1)\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run 'maxSteps' must be a positive safe integer.`\n )\n }\n assertApprovalModeField(input.spec.approvalMode, \"Subagent run\", prefix)\n\n assertSubagentRunFiles(input.spec.files, \"spec.files\", prefix)\n\n if (input.spec.toolNames.some((name) => !name.trim())) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run tool names must not be empty.`\n )\n }\n if (!Array.isArray(input.trigger.parts) || input.trigger.parts.length === 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run trigger must have at least one part.`\n )\n }\n if (input.createdAt && !Number.isFinite(input.createdAt.getTime())) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run createdAt must be a valid date.`\n )\n }\n}\n\n/** Exact semantic match required when a durable spawn key is replayed. */\nexport function subagentRunMatchesCreateInput(\n run: AgentRunRecord,\n input: CreateSubagentRunInput\n): run is SubagentRunRecord {\n return (\n run.kind === \"subagent\" &&\n run.id === input.id &&\n run.projectId === input.projectId &&\n run.executionId === input.executionId &&\n run.parentRunId === input.parentRunId &&\n run.spawnKey === input.spawnKey &&\n run.threadId === input.thread.id &&\n isDeepStrictEqual(run.spec, input.spec)\n )\n}\n\n/** Refuse what only a conversation does on a sub-agent's thread. */\nexport function assertConversationThreadRow(\n thread: Pick<AgentThreadRecord, \"id\" | \"kind\">,\n /** What is refused, completing \"only a conversation …\". */\n operation: string,\n prefix = \"Sixb\"\n): void {\n if (thread.kind === \"conversation\") return\n throw new AgentStorageError(\n \"thread_not_conversation\",\n `[${prefix}] Agent thread '${thread.id}' is a sub-agent's: only a conversation ${operation}.`\n )\n}\n\n/**\n * The thread a child's first run creates. Its conversation's owner owns it, and its run is active\n * in it from the start: the trigger is its first and only message.\n */\nexport function newSubagentThreadRecord(\n input: CreateSubagentRunInput,\n conversation: { readonly id: string; readonly ownerPrincipal: Principal },\n createdAt: Date\n): AgentThreadRecord {\n return {\n id: input.thread.id,\n projectId: input.projectId,\n kind: \"subagent\",\n parent: { threadId: conversation.id, spawnedBy: input.parentRunId, key: input.spawnKey },\n ownerPrincipal: structuredClone(conversation.ownerPrincipal),\n status: \"active\",\n activeRunId: input.id,\n lastMessageAt: createdAt,\n messageCount: 1,\n createdAt,\n updatedAt: createdAt,\n }\n}\n\n/**\n * A later run of a child goes into its thread: the same child of the same conversation, and only\n * once the thread's previous run has ended, as in a conversation.\n */\nexport function assertSubagentThreadTakesRun(\n thread: AgentThreadRecord | null,\n input: CreateSubagentRunInput,\n conversationId: string,\n prefix = \"Sixb\"\n): asserts thread is AgentThreadRecord {\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[${prefix}] Agent thread '${input.thread.id}' not found for project '${input.projectId}'.`\n )\n }\n if (\n thread.kind !== \"subagent\" ||\n thread.parent?.threadId !== conversationId ||\n thread.parent.key !== input.spawnKey\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent thread '${thread.id}' is not the thread of child '${input.spawnKey}' of this conversation.`\n )\n }\n if (thread.activeRunId !== null) {\n throw new AgentStorageError(\n \"active_run_exists\",\n `[${prefix}] Agent thread '${thread.id}' already has an active run '${thread.activeRunId}'.`\n )\n }\n}\n\n/**\n * Validate what a finish keeps: a child's result once it succeeded. A child that paused, on its\n * held calls or on a question, may not have answered yet, so its text may be empty. A conversation\n * turn keeps none, and has no parent to wait for.\n */\nexport function assertAgentRunFinishPayload(\n kind: AgentRunRecord[\"kind\"],\n input: FinishAgentRunInput,\n runId: string,\n prefix = \"Sixb\"\n): void {\n if (kind === \"conversation\") {\n if (input.status === \"succeeded\" && input.result !== undefined) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run '${runId}' cannot persist a subagent result.`\n )\n }\n if (input.finishReason === \"awaiting_answer\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Conversational Agent run '${runId}' has no parent to wait for: only a subagent finishes awaiting_answer.`\n )\n }\n return\n }\n\n if (input.status === \"succeeded\") {\n const paused =\n input.finishReason === \"awaiting_approval\" || input.finishReason === \"awaiting_answer\"\n assertSubagentRunResult(input.result, runId, prefix, paused)\n }\n}\n\n/**\n * Validate the small durable result returned by a successful child. A child that paused on its held\n * calls may not have answered yet, so its text may be empty.\n */\nexport function assertSubagentRunResult(\n result: SubagentRunResult | undefined,\n runId: string,\n prefix = \"Sixb\",\n paused = false\n): asserts result is SubagentRunResult {\n if (typeof result?.text !== \"string\" || (!paused && result.text.trim().length === 0)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Succeeded subagent run '${runId}' requires text.`\n )\n }\n assertSubagentRunFiles(result.files, \"result.files\", prefix)\n if (\n result.filesError !== undefined &&\n (typeof result.filesError !== \"string\" || !result.filesError.trim() || result.files?.length)\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run '${runId}' result.filesError must say why it returned no files.`\n )\n }\n if (\n result.unread !== undefined &&\n (!paused ||\n !Array.isArray(result.unread) ||\n !result.unread.every((mail) => typeof mail?.id === \"string\" && typeof mail.text === \"string\"))\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Only a paused subagent run keeps unread mail, each with its id and text: '${runId}'.`\n )\n }\n}\n\n/** Each file a parent and its child exchange: a safe relative path, once, and a valid FileRef. */\nfunction assertSubagentRunFiles(\n files: readonly SubagentRunFile[] | undefined,\n field: string,\n prefix: string\n): void {\n if (files === undefined) return\n\n if (!Array.isArray(files)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run ${field} must be a list.`\n )\n }\n\n const paths = new Set<string>()\n for (const file of files) {\n const segments: readonly string[] = typeof file?.path === \"string\" ? file.path.split(\"/\") : []\n const safe =\n segments.length > 0 &&\n !file.path.includes(\"\\0\") &&\n segments.every((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\")\n if (!safe || paths.has(file.path) || !isFileRef(file.fileRef)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Subagent run ${field} must hold unique relative paths, each with a valid FileRef.`\n )\n }\n paths.add(file.path)\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 // A conversation's turn checkpoints its conversation, a child its own thread.\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 // A run that ended no longer holds its execution, as a reclaimed one does not.\n if (run.status !== \"running\") {\n throw new AgentStorageError(\n \"execution_lost\",\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\n/** Validate the fields of a save that storage relies on, before entering its transaction. */\nexport function assertSaveAgentMemoryInput(input: SaveAgentMemoryInput, prefix = \"Sixb\"): void {\n const fail = (message: string): never => {\n throw new AgentStorageError(\"invalid_input\", `[${prefix}] Agent memory ${message}`)\n }\n if (input.projectId.trim().length === 0) fail(\"project id must not be empty.\")\n if (input.repoId.trim().length === 0) fail(\"repo id must not be empty.\")\n if (!Number.isSafeInteger(input.baseRevision) || input.baseRevision < 0) {\n fail(\"base revision must be a non-negative integer.\")\n }\n if (input.message.trim().length === 0) fail(\"save message must not be empty.\")\n if (input.changes.length === 0) fail(\"save must change at least one file.\")\n const paths = new Set<string>()\n for (const change of input.changes) {\n if (change.path.length === 0) fail(\"paths must not be empty.\")\n if (paths.has(change.path)) fail(`save changes '${change.path}' more than once.`)\n paths.add(change.path)\n }\n if (input.createdAt && !Number.isFinite(input.createdAt.getTime())) {\n fail(\"save time must be a valid date.\")\n }\n}\n\n/** A path's highest-revision version; `contents: null` when that revision deleted it. */\nexport interface LatestAgentMemoryFile {\n readonly revision: number\n readonly contents: string | null\n}\n\n/**\n * The changes of a save that would overwrite another save's work, as their files are now: every\n * change when the repo is behind the base revision (it was deleted since), otherwise each change\n * whose path was written after the base revision. Ordered by path.\n */\nexport function agentMemoryConflicts(\n input: SaveAgentMemoryInput,\n head: number,\n latest: ReadonlyMap<string, LatestAgentMemoryFile>\n): AgentMemoryChange[] {\n return input.changes\n .filter(\n (change) =>\n input.baseRevision > head || (latest.get(change.path)?.revision ?? 0) > input.baseRevision\n )\n .map((change) => ({ path: change.path, contents: latest.get(change.path)?.contents ?? null }))\n .sort((left, right) => compareAgentMemoryPaths(left.path, right.path))\n}\n\n/** Code-unit order, as SQLite and Postgres (with `COLLATE \"C\"`) compare paths. */\nexport function compareAgentMemoryPaths(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\n/** File versions written before this time leave the history once a newer version exists. */\nexport function agentMemoryHistoryCutoff(savedAt: Date): Date {\n return new Date(savedAt.getTime() - AGENT_MEMORY_HISTORY_DAYS * 24 * 60 * 60 * 1000)\n}\n\n// ── token rates ───────────────────────────────────────────────────────────────────────────────\n\nexport { AGENT_TOKEN_RATE_SAMPLES } from \"./types\"\n\n/** Validate a measurement before a store keeps it: it comes from whichever runner ran the run. */\nexport function assertAgentTokenRateRecord(input: AgentTokenRateRecord, prefix = \"Sixb\"): void {\n const fail = (message: string): never => {\n throw new AgentStorageError(\"invalid_input\", `[${prefix}] Agent token rate ${message}`)\n }\n\n for (const field of [\"projectId\", \"providerId\", \"modelId\", \"runId\"] as const) {\n const value: unknown = input[field]\n if (typeof value !== \"string\" || value.trim().length === 0) fail(`${field} must not be empty.`)\n }\n for (const field of [\"bytes\", \"tokens\"] as const) {\n const value: unknown = input[field]\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value <= 0) {\n fail(`${field} must be a positive integer.`)\n }\n }\n if (!(input.measuredAt instanceof Date) || !Number.isFinite(input.measuredAt.getTime())) {\n fail(\"measurement time must be a valid date.\")\n }\n\n const rate = input.bytes / input.tokens\n if (rate < AGENT_TOKEN_RATE_MIN_BYTES_PER_TOKEN || rate > AGENT_TOKEN_RATE_MAX_BYTES_PER_TOKEN) {\n fail(\n `bytes per token must be between ${AGENT_TOKEN_RATE_MIN_BYTES_PER_TOKEN} and ${AGENT_TOKEN_RATE_MAX_BYTES_PER_TOKEN}.`\n )\n }\n}\n\n// ── approvals ─────────────────────────────────────────────────────────────────────────────────\n\n/** An approval that still answers for its call key: a settled one asks again. */\nexport const LIVE_AGENT_APPROVAL_STATUSES = [\n \"pending\",\n \"approved\",\n \"denied\",\n] as const satisfies readonly AgentApprovalStatus[]\n\n/**\n * Whether an approval keeps its run paused: still waiting, or decided and not reported to the model\n * yet. A run finishes `awaiting_approval` only while it holds one.\n */\nexport function agentApprovalHoldsRun(approval: AgentApprovalRecord, runId: string): boolean {\n return (\n (approval.runId === runId || approval.callerRunId === runId) &&\n (LIVE_AGENT_APPROVAL_STATUSES as readonly string[]).includes(approval.status) &&\n approval.reportedInMessageId === undefined\n )\n}\n\n/** Refuse a paused finish that holds no call, or a paused finish that did not succeed. */\nexport function assertAwaitingApprovalFinish(input: {\n readonly runId: string\n readonly status: string\n readonly holdsApproval: boolean\n readonly prefix?: string\n}): void {\n const prefix = input.prefix ?? \"Sixb\"\n if (input.status !== \"succeeded\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent run '${input.runId}' can only pause for approval when it succeeds.`\n )\n }\n if (!input.holdsApproval) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent run '${input.runId}' holds no call waiting for approval, so it cannot finish awaiting one.`\n )\n }\n}\n\n/**\n * Whether a run can have approvals: its mode holds some calls. A turn from before approval modes,\n * or in `auto`, holds none, and neither do its children, which copy its mode.\n */\nexport function agentRunMayHoldCalls(run: AgentRunRecord): boolean {\n return (AGENT_HOLDING_APPROVAL_MODES as readonly unknown[]).includes(run.spec?.approvalMode)\n}\n\n/** Whether a stop request reaches this approval. */\nexport function agentApprovalStops(\n approval: AgentApprovalRecord,\n input: StopAgentApprovalsInput\n): boolean {\n return (\n approval.projectId === input.projectId &&\n approval.threadId === input.threadId &&\n approval.reportedInMessageId === undefined &&\n (input.runId === undefined || approval.runId === input.runId) &&\n (input.requestedBy === undefined ||\n (approval.requestedBy.type === input.requestedBy.type &&\n approval.requestedBy.id === input.requestedBy.id))\n )\n}\n\n/** Whether a repair pass has work on this approval; providers run the same filter in SQL. */\nexport function agentApprovalRepairable(\n approval: AgentApprovalRecord,\n claimableBefore: Date\n): boolean {\n const unfinished =\n approval.status === \"approved\" &&\n approval.outcome === undefined &&\n (approval.executionClaimedAt ?? approval.decidedAt ?? new Date(0)) <= claimableBefore\n const resumable =\n (approval.status === \"approved\" || approval.status === \"denied\") &&\n approval.reportedInMessageId === undefined &&\n approval.turnStoppedAt === undefined\n return unfinished || resumable\n}\n\n/** Whether an approved call without an outcome can be claimed now. */\nexport function agentApprovalClaimable(approval: AgentApprovalRecord, staleBefore: Date): boolean {\n return (\n approval.status === \"approved\" &&\n approval.outcome === undefined &&\n (approval.executionClaimedAt ?? approval.decidedAt ?? new Date(0)) <= staleBefore\n )\n}\n\n/** The run id the call names: unique among a thread's live approvals. */\nexport function agentApprovalCallKey(call: AgentApprovalCall): string {\n return call.kind === \"action\" ? call.actionRunId : call.workflowRunId\n}\n\nexport function assertRequestAgentApprovalInput(\n input: RequestAgentApprovalInput,\n prefix = \"Sixb\"\n): void {\n for (const [name, value] of [\n [\"id\", input.id],\n [\"projectId\", input.projectId],\n [\"runId\", input.runId],\n [\"callerRunId\", input.callerRunId],\n [\"executionToken\", input.executionToken],\n [\"call key\", agentApprovalCallKey(input.call)],\n ] as const) {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent approval '${name}' must not be empty.`\n )\n }\n }\n if (!(AGENT_HOLDING_APPROVAL_MODES as readonly unknown[]).includes(input.mode)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent approval mode must be one of: ${AGENT_HOLDING_APPROVAL_MODES.join(\", \")}.`\n )\n }\n}\n\n/**\n * Fence a held call: the caller run is running with the request's token, and is the turn or one of\n * its children. Returns the turn's thread.\n */\nexport function assertAgentApprovalCaller(input: {\n readonly request: RequestAgentApprovalInput\n readonly turn: AgentRunRecord | null\n readonly caller: AgentRunRecord | null\n readonly prefix?: string\n}): string {\n const { request, turn, caller } = input\n const prefix = input.prefix ?? \"Sixb\"\n if (!turn || !caller) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[${prefix}] Agent run '${turn ? request.callerRunId : request.runId}' not found for project '${request.projectId}'.`\n )\n }\n if (turn.kind !== \"conversation\") {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent approval run '${turn.id}' must be a conversation turn.`\n )\n }\n if (caller.id !== turn.id && !(caller.kind === \"subagent\" && caller.parentRunId === turn.id)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent run '${caller.id}' does not belong to turn '${turn.id}'.`\n )\n }\n if (caller.status !== \"running\") {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Agent run '${caller.id}' is not running (status '${caller.status}').`\n )\n }\n if (!caller.execution || caller.execution.token !== request.executionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[${prefix}] Execution token is no longer current on agent run '${caller.id}'.`\n )\n }\n return turn.threadId\n}\n\n/** The approval a request creates, before any provider writes it. */\nexport function newAgentApprovalRecord(\n input: RequestAgentApprovalInput,\n threadId: string\n): AgentApprovalRecord {\n return {\n id: input.id,\n projectId: input.projectId,\n threadId,\n runId: input.runId,\n callerRunId: input.callerRunId,\n requestedBy: structuredClone(input.requestedBy),\n mode: input.mode,\n callKey: agentApprovalCallKey(input.call),\n call: structuredClone(input.call),\n status: \"pending\",\n createdAt: new Date(input.createdAt ?? new Date()),\n expiresAt: new Date(input.expiresAt),\n }\n}\n\n/** Whether an approval matches a list filter; providers run the same filter in SQL. */\nexport function agentApprovalMatches(\n approval: AgentApprovalRecord,\n input: ListAgentApprovalsInput\n): boolean {\n return (\n approval.projectId === input.projectId &&\n (input.threadId === undefined || approval.threadId === input.threadId) &&\n (input.runId === undefined || approval.runId === input.runId) &&\n (input.requestedBy === undefined ||\n (approval.requestedBy.type === input.requestedBy.type &&\n approval.requestedBy.id === input.requestedBy.id)) &&\n (input.statuses === undefined || input.statuses.includes(approval.status)) &&\n (input.reported === undefined ||\n (approval.reportedInMessageId !== undefined) === input.reported)\n )\n}\n\n// -- agent_thread_inbox: shared validation and transitions ------------------------------------\n\nfunction assertNonEmptyText(value: unknown, field: string, prefix: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent inbox '${field}' must not be empty.`\n )\n }\n}\n\nfunction assertPrincipalInput(principal: Principal, field: string, prefix: string): void {\n if (\n !isPlainRecord(principal) ||\n ![\"user\", \"serviceAccount\", \"system\"].includes(principal.type) ||\n typeof principal.id !== \"string\" ||\n principal.id.trim().length === 0\n ) {\n throw new AgentStorageError(\"invalid_input\", `[${prefix}] Agent inbox '${field}' is invalid.`)\n }\n}\n\nexport function assertAgentInboxMode(\n mode: unknown,\n prefix = \"Sixb\"\n): asserts mode is AgentInboxMode {\n if (!(AGENT_INBOX_MODES as readonly unknown[]).includes(mode)) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent inbox mode must be one of: ${AGENT_INBOX_MODES.join(\", \")}.`\n )\n }\n}\n\nexport function assertAgentInboxSpec(spec: AgentInboxSpec | undefined, prefix = \"Sixb\"): void {\n if (spec === undefined) return\n if (!isPlainRecord(spec)) {\n throw new AgentStorageError(\"invalid_input\", `[${prefix}] Agent inbox spec must be an object.`)\n }\n if (spec.model !== undefined) {\n if (\n !isPlainRecord(spec.model) ||\n typeof spec.model.provider !== \"string\" ||\n spec.model.provider.trim().length === 0 ||\n typeof spec.model.modelId !== \"string\" ||\n spec.model.modelId.trim().length === 0\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent inbox model reference must have non-empty provider and modelId.`\n )\n }\n }\n if (spec.reasoning !== undefined) {\n const validLevel = (AGENT_REASONING_LEVELS as readonly unknown[]).includes(spec.reasoning)\n if (!validLevel && !isModelReasoning(spec.reasoning)) {\n throw new AgentStorageError(\"invalid_input\", `[${prefix}] Agent inbox reasoning is invalid.`)\n }\n }\n if (\n spec.approvalMode !== undefined &&\n !(AGENT_APPROVAL_MODES as readonly unknown[]).includes(spec.approvalMode)\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent inbox approvalMode must be one of: ${AGENT_APPROVAL_MODES.join(\", \")}.`\n )\n }\n}\n\nexport function assertEnqueueAgentInboxItemInput(\n input: EnqueueAgentInboxItemInput,\n prefix = \"Sixb\"\n): void {\n assertNonEmptyText(input.projectId, \"projectId\", prefix)\n assertNonEmptyText(input.id, \"id\", prefix)\n assertNonEmptyText(input.threadId, \"threadId\", prefix)\n assertNonEmptyText(input.messageId, \"messageId\", prefix)\n assertPrincipalInput(input.authorPrincipal, \"authorPrincipal\", prefix)\n assertAgentInboxMode(input.mode, prefix)\n assertAgentInboxParts(input.parts, input.mode, prefix)\n assertAgentInboxSpec(input.spec, prefix)\n if (input.executionId !== undefined) assertNonEmptyText(input.executionId, \"executionId\", prefix)\n if (input.replacesMessageId !== undefined) {\n assertNonEmptyText(input.replacesMessageId, \"replacesMessageId\", prefix)\n if (input.mode !== \"queue\" || input.immediate !== true) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] An agent inbox item that replaces a message is a queued message sent now.`\n )\n }\n }\n}\n\n/**\n * A steer is read mid-turn, where nothing prepares its files: its bytes must be the ones a later\n * replay of the saved message sends, so it carries no file part. A message with one waits for the\n * next turn, where the turn prepares its attachments as it does the trigger's.\n */\nfunction assertAgentInboxParts(\n parts: readonly AgentMessagePart[] | undefined,\n mode: AgentInboxMode,\n prefix: string\n): void {\n if (!Array.isArray(parts) || parts.length === 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent inbox 'parts' must be a non-empty array.`\n )\n }\n if (mode === \"steer\" && parts.some((part) => part.type === \"file\")) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] An agent inbox 'steer' carries no file: queue it for the next turn instead.`\n )\n }\n}\n\nexport function assertUpdateAgentInboxItemInput(\n input: UpdateAgentInboxItemInput,\n prefix = \"Sixb\"\n): void {\n assertNonEmptyText(input.projectId, \"projectId\", prefix)\n assertNonEmptyText(input.threadId, \"threadId\", prefix)\n assertNonEmptyText(input.id, \"id\", prefix)\n if (input.mode !== undefined) assertAgentInboxMode(input.mode, prefix)\n if (input.parts !== undefined) assertAgentInboxParts(input.parts, input.mode ?? \"queue\", prefix)\n if (input.spec !== undefined && input.spec !== null) assertAgentInboxSpec(input.spec, prefix)\n}\n\nexport function assertTakeAgentInboxSteersInput(\n input: TakeAgentInboxSteersInput,\n prefix = \"Sixb\"\n): void {\n assertNonEmptyText(input.projectId, \"projectId\", prefix)\n assertNonEmptyText(input.threadId, \"threadId\", prefix)\n assertNonEmptyText(input.runId, \"runId\", prefix)\n assertNonEmptyText(input.executionToken, \"executionToken\", prefix)\n if (!Number.isInteger(input.stepIndex) || input.stepIndex < 0) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[${prefix}] Agent inbox 'stepIndex' must be a non-negative integer.`\n )\n }\n assertPrincipalInput(input.authorPrincipal, \"authorPrincipal\", prefix)\n}\n\nexport function assertInboxThreadAcceptsItem(\n thread: Pick<AgentThreadRecord, \"id\" | \"kind\" | \"status\"> | null,\n threadId: string,\n projectId: string,\n existingCount: number,\n prefix = \"Sixb\"\n): void {\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[${prefix}] Agent thread '${threadId}' not found for project '${projectId}'.`\n )\n }\n assertConversationThreadRow(thread, \"holds inbox messages\", prefix)\n if (thread.status !== \"active\") {\n throw new AgentStorageError(\n \"invalid_state\",\n `[${prefix}] Archived agent thread '${thread.id}' does not accept inbox messages.`\n )\n }\n if (existingCount >= AGENT_THREAD_INBOX_MAX_ITEMS) {\n throw new AgentStorageError(\n \"inbox_limit\",\n `[${prefix}] Agent thread '${thread.id}' can hold at most ${AGENT_THREAD_INBOX_MAX_ITEMS} pending inbox items.`\n )\n }\n}\n\nexport function assertInboxRunOwnership(\n run: Pick<AgentRunRecord, \"id\" | \"kind\" | \"threadId\" | \"status\" | \"execution\"> | null,\n input: Pick<ConsumeClaimedAgentInboxInput, \"projectId\" | \"threadId\" | \"runId\" | \"executionToken\">,\n prefix = \"Sixb\"\n): void {\n if (\n !run ||\n run.kind !== \"conversation\" ||\n run.threadId !== input.threadId ||\n run.status !== \"running\" ||\n run.execution?.token !== input.executionToken\n ) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[${prefix}] Execution token is no longer current on agent run '${input.runId}'.`\n )\n }\n}\n\nexport function newAgentInboxItemRecord(\n input: EnqueueAgentInboxItemInput,\n seq: number\n): AgentInboxItemRecord {\n const createdAt = new Date(input.createdAt ?? new Date())\n const normalizedSpec = normalizeInboxSpec(input.spec)\n return {\n id: input.id,\n projectId: input.projectId,\n threadId: input.threadId,\n messageId: input.messageId,\n seq,\n authorPrincipal: structuredClone(input.authorPrincipal),\n mode: input.mode,\n parts: structuredClone(input.parts),\n ...(normalizedSpec ? { spec: normalizedSpec } : {}),\n ...(input.timeZone ? { timeZone: input.timeZone } : {}),\n ...(input.locale ? { locale: input.locale } : {}),\n ...(input.immediate ? { immediate: true } : {}),\n ...(input.replacesMessageId ? { replacesMessageId: input.replacesMessageId } : {}),\n ...(input.executionId ? { executionId: input.executionId } : {}),\n createdAt,\n updatedAt: new Date(createdAt),\n }\n}\n\nexport function updatedAgentInboxItemRecord(\n current: AgentInboxItemRecord,\n input: UpdateAgentInboxItemInput\n): AgentInboxItemRecord {\n if (current.claimedBy !== undefined) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[Sixb] Agent inbox item '${current.id}' was already claimed by run '${current.claimedBy.runId}'.`\n )\n }\n const nextSpec =\n input.spec === undefined\n ? current.spec\n : input.spec === null\n ? undefined\n : normalizeInboxSpec(input.spec)\n const nextImmediate = input.immediate === undefined ? current.immediate : input.immediate\n const { spec: _oldSpec, immediate: _oldImmediate, ...base } = current\n const mode = input.mode ?? current.mode\n // An edit rewinds the thread when it starts: it goes now, after the turn it stopped.\n if (current.replacesMessageId !== undefined && (mode !== \"queue\" || nextImmediate !== true)) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[Sixb] Agent inbox item '${current.id}' edits message '${current.replacesMessageId}': it stays a message sent now.`\n )\n }\n const parts =\n input.parts !== undefined ? structuredClone(input.parts) : structuredClone(current.parts)\n // Promoting a message that carries a file to a steer would read bytes a replay cannot send.\n assertAgentInboxParts(parts, mode, \"Sixb\")\n return {\n ...base,\n mode,\n parts,\n ...(nextSpec ? { spec: structuredClone(nextSpec) } : {}),\n ...(nextImmediate ? { immediate: true } : {}),\n updatedAt: new Date(input.updatedAt ?? new Date()),\n }\n}\n\nfunction normalizeInboxSpec(spec: AgentInboxSpec | undefined): AgentInboxSpec | undefined {\n if (!spec) return undefined\n const out: {\n model?: AgentInboxSpec[\"model\"]\n reasoning?: AgentInboxSpec[\"reasoning\"]\n approvalMode?: AgentInboxSpec[\"approvalMode\"]\n } = {}\n if (spec.model !== undefined) out.model = structuredClone(spec.model)\n if (spec.reasoning !== undefined) out.reasoning = structuredClone(spec.reasoning)\n if (spec.approvalMode !== undefined) out.approvalMode = spec.approvalMode\n return Object.keys(out).length > 0 ? out : undefined\n}\n",
7
+ "import { createHash, randomUUID } from \"node:crypto\"\n\n/**\n * Id helpers for agent persistence. Threads, the run id, and the user (trigger) message are minted\n * by the trigger; the queued run is persisted with the user message, and the assistant message id\n * is minted when the turn finalizes. Prefixes make ids self-describing in logs.\n */\n\nexport function createAgentThreadId(): string {\n return `agt_thr_${randomUUID()}`\n}\n\n/** A fresh provider name, scoped to one project's thread; never a filesystem revision. */\nexport function createAgentThreadSandboxName(projectId: string, threadId: string): string {\n const digest = createHash(\"sha256\")\n .update(JSON.stringify([projectId, threadId, randomUUID()]))\n .digest(\"hex\")\n return `sixb-sb-${digest}`\n}\n\nexport function createAgentRunId(): string {\n return `agt_run_${randomUUID()}`\n}\n\n/** How every child's first run id starts: told apart from the key the Agent spawned it under. */\nexport const SUBAGENT_RUN_ID_PREFIX = \"agt_run_child_\"\n\n/** One stable child identity per parent-selected spawn key. */\nexport function createSubagentRunId(parentRunId: string, spawnKey: string): string {\n return `${SUBAGENT_RUN_ID_PREFIX}${spawnDigest(parentRunId, spawnKey)}`\n}\n\n/**\n * The thread a child works in, named after the turn that spawned it and its key. It shares its\n * first run's digest: migration `subagent-threads` names the threads of earlier children so.\n */\nexport function createSubagentThreadId(spawningRunId: string, spawnKey: string): string {\n return `agt_thr_child_${spawnDigest(spawningRunId, spawnKey)}`\n}\n\nfunction spawnDigest(runId: string, spawnKey: string): string {\n return createHash(\"sha256\").update(runId).update(\"\\0\").update(spawnKey).digest(\"hex\")\n}\n\n/** Stable execution identity paired with a deterministic child run. */\nexport function createSubagentExecutionId(runId: string): string {\n return `exec_${runId}`\n}\n\nexport function createAgentMessageId(): string {\n return `agt_msg_${randomUUID()}`\n}\n\n/** A message waiting in a thread's inbox, before it is a message of the conversation. */\nexport function createAgentInboxItemId(): string {\n return `agt_inb_${randomUUID()}`\n}\n\n/** One deterministic context-checkpoint identity per conversational run. */\nexport function agentContextCheckpointId(runId: string): string {\n return `agt_ctx_${runId}`\n}\n\n/** A checkpoint copied into a fork; the source's checkpoint keeps its run-derived id. */\nexport function createCopiedAgentContextCheckpointId(): string {\n return `agt_ctx_copy_${randomUUID()}`\n}\n\n/** A queue delivery's fencing token for writes to an `agent_runs` record. */\nexport function createAgentRunExecutionToken(): string {\n return `agt_exec_${randomUUID()}`\n}\n",
8
+ "import type { ActionsRuntime } from \"../actions/execution\"\nimport type { BlobBody, FileRef, OpenedFileRef } from \"../blob-storage\"\nimport type { ConnectorRuntime } from \"../connectors\"\nimport type { JsonPrimitive, JsonValue, ReadonlyJsonValue } from \"../json\"\nimport type { Logger } from \"../logging\"\nimport { type LanguageModelRef, MODEL_REASONING_LEVELS, type ModelReasoning } from \"../models\"\nimport type { ModelsRuntime } from \"../models/generation-types\"\nimport type { InferSchema } from \"../ontology/inference\"\nimport type { Schema } from \"../ontology/types\"\nimport type { ObjectReader } from \"../runtime/types\"\nimport type { UsersRuntime } from \"../users\"\n\nexport type {\n AgentContextEntryInput,\n AgentContextInput,\n AgentContextOrigin,\n AgentContextPart,\n} from \"./context/entries\"\n\n/** Public capability reference used by security grants such as `can.run(agent)`. */\nexport interface AgentReference {\n readonly kind: \"agent\"\n readonly usage: AgentUsageReference\n readonly threads: AgentThreadsReference\n readonly memory: AgentMemoryReference\n}\n\n/** Project-wide AI accounting and limit capability, independent of permission to run the Agent. */\nexport interface AgentUsageReference {\n readonly kind: \"aiUsage\"\n}\n\n/** Every user's conversations with the Agent, as `can.observe(agent.threads)` reads them. */\nexport interface AgentThreadsReference {\n readonly kind: \"agentThreads\"\n}\n\n/** The project's shared Agent memory, which every conversation reads. */\nexport interface AgentMemoryReference {\n readonly kind: \"agentMemory\"\n}\n\n/** Public metadata for the project's conversational Agent. */\nexport interface AgentDescriptor {\n readonly name: string\n readonly model: LanguageModelRef\n}\n\nexport type AgentReasoning = ModelReasoning\n\nexport const AGENT_REASONING_LEVELS = MODEL_REASONING_LEVELS\n\ntype Simplify<T> = { [K in keyof T]: T[K] } & {}\ntype JsonifyAgentToolInput<T> = unknown extends T\n ? ReadonlyJsonValue\n : T extends Date\n ? string\n : T extends readonly (infer TItem)[]\n ? readonly JsonifyAgentToolInput<TItem>[]\n : T extends JsonPrimitive\n ? T\n : T extends object\n ? { readonly [K in keyof T]: JsonifyAgentToolInput<T[K]> }\n : never\n\n/** A model-facing object shape expressed with Sixb's schema DSL. */\nexport type AgentToolInputSchema = Readonly<Record<string, Schema>>\n\n/** Infer the handler input represented by an agent tool schema. */\nexport type InferAgentToolInputSchema<TInput extends AgentToolInputSchema> =\n string extends keyof TInput\n ? Readonly<Record<string, unknown>>\n : Simplify<{\n readonly [K in keyof TInput]: JsonifyAgentToolInput<InferSchema<TInput[K]>>\n }>\n\n/** Identifies the conversational, workflow, or child Agent execution that invoked a tool. */\nexport type AgentToolRunInfo =\n | {\n readonly kind: \"conversation\"\n readonly id: string\n readonly threadId: string\n }\n | {\n readonly kind: \"subagent\"\n readonly id: string\n readonly parentRunId: string\n }\n | {\n readonly kind: \"workflow\"\n readonly id: string\n readonly workflowId: string\n readonly stepId: string\n }\n\n/** Input accepted by the run-scoped file publisher exposed to agent tools. */\nexport interface AgentToolFilePutInput {\n readonly body: BlobBody\n readonly fileName: string\n readonly mediaType?: string\n}\n\n/** A file a tool stored durably, and the path of its copy inside the current run sandbox. */\nexport interface AgentToolFile {\n readonly fileRef: FileRef\n readonly sandboxPath: string\n}\n\n/** The narrow file-writing surface available to an agent tool call. */\nexport interface AgentToolFiles {\n put(input: AgentToolFilePutInput): Promise<AgentToolFile>\n}\n\n/**\n * The files attached to the run that invoked a tool: the messages of a chat's thread, or the input\n * files of a workflow AI task. A child Agent has none.\n */\nexport interface AgentToolAttachments {\n /**\n * Open an attachment by the `key` the Agent sees in `$SIXB_ATTACHMENTS`. Returns null when its\n * stored file is gone, and throws an `AgentToolPublicError` for a key that is not one of this\n * run's attachments.\n */\n open(key: string): Promise<OpenedFileRef | null>\n}\n\nexport type AgentToolTextContent = {\n readonly type: \"text\"\n readonly text: string\n}\n\nexport type AgentToolFileContent = {\n readonly type: \"file\"\n readonly fileRef: FileRef\n}\n\n/** Durable model-facing content returned by a file-aware tool. */\nexport type AgentToolContent = AgentToolTextContent | AgentToolFileContent\n\n/**\n * A file-aware tool result. The tag distinguishes this envelope from an ordinary JSON result while\n * keeping the whole value safe to persist in the durable tool-call trace.\n */\nexport type AgentToolResult = {\n readonly kind: \"agentToolResult\"\n readonly content: readonly AgentToolContent[]\n}\n\n/**\n * The run's domain SDK as an agent tool sees it. Unlike workflow steps and actions, it acts as the\n * run's requester: the signed-in user in a chat, that same user in a child Agent, and the step's\n * groups in a workflow AI task.\n *\n * A structural view of the public `Sixb` SDK, like `WorkflowRuntimeFacade`: the handler receives the\n * run's bound SDK, and this type guides it to what a tool should do. It reads objects and changes\n * them by requesting actions, which validate and record the change. Authority comes from the run,\n * not from this view.\n */\nexport interface AgentToolRuntimeFacade extends ObjectReader {\n readonly actions: ActionsRuntime\n readonly models: ModelsRuntime\n readonly connector: ConnectorRuntime\n readonly users: UsersRuntime\n}\n\n/** The narrow, run-scoped surface passed to an agent tool handler. */\nexport interface AgentToolRunContext<\n TInput extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,\n> {\n readonly input: TInput\n readonly toolCallId: string\n readonly signal: AbortSignal\n readonly run: AgentToolRunInfo\n readonly sixb: AgentToolRuntimeFacade\n readonly logger: Logger\n readonly files: AgentToolFiles\n readonly attachments: AgentToolAttachments\n}\n\n/** Agent tool handlers may return only values safe to persist in agent messages. */\nexport type AgentToolHandlerResult<\n TOutput extends ReadonlyJsonValue | AgentToolResult = ReadonlyJsonValue | AgentToolResult,\n> = TOutput | Promise<TOutput>\n\nexport type AgentToolHandler<\n TInput extends Readonly<Record<string, unknown>>,\n TOutput extends ReadonlyJsonValue | AgentToolResult = ReadonlyJsonValue | AgentToolResult,\n> = (context: AgentToolRunContext<TInput>) => AgentToolHandlerResult<TOutput>\n\n/**\n * Runtime definitions are stored heterogeneously. Keep variance erasure at this\n * boundary only; authoring through `run()` remains strictly contravariant.\n */\ntype StoredAgentToolHandler<TInput extends Readonly<Record<string, unknown>>> = {\n bivarianceHack(context: AgentToolRunContext<TInput>): JsonValue | Promise<JsonValue>\n}[\"bivarianceHack\"]\n\ndeclare const agentToolOutputValueType: unique symbol\n\n/** A reusable, inert model tool definition selected explicitly by an agent. */\nexport interface AgentToolDefinition<\n TName extends string = string,\n TInput extends AgentToolInputSchema = AgentToolInputSchema,\n TOutput extends ReadonlyJsonValue | AgentToolResult = ReadonlyJsonValue | AgentToolResult,\n> {\n readonly kind: \"agentTool\"\n readonly name: TName\n readonly description: string\n readonly input: TInput\n readonly handler: StoredAgentToolHandler<InferAgentToolInputSchema<TInput>>\n readonly [agentToolOutputValueType]?: TOutput\n}\n\n/** Infer the input received by a tool definition's handler. */\nexport type InferAgentToolInput<TTool extends AgentToolDefinition> = InferAgentToolInputSchema<\n TTool[\"input\"]\n>\n\n/**\n * Infer the output a chat receives from a tool: its handler's return value, saved on the message\n * and streamed live as is. A file-aware tool's output is its `AgentToolResult` envelope.\n */\nexport type InferAgentToolOutput<TTool extends AgentToolDefinition> =\n TTool extends AgentToolDefinition<string, AgentToolInputSchema, infer TOutput> ? TOutput : never\n\nexport interface AgentToolRunBuilder<TName extends string, TInput extends AgentToolInputSchema> {\n run<TOutput extends ReadonlyJsonValue | AgentToolResult>(\n handler: AgentToolHandler<InferAgentToolInputSchema<TInput>, TOutput>\n ): AgentToolDefinition<TName, TInput, TOutput>\n}\n\nexport interface AgentToolInputBuilder<TName extends string> {\n input<const TInput extends AgentToolInputSchema>(\n input: TInput\n ): AgentToolRunBuilder<TName, TInput>\n}\n\nexport interface AgentToolDescriptionBuilder<TName extends string> {\n description(description: string): AgentToolInputBuilder<TName>\n}\n"
9
+ ],
10
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBO,MAAM,2BAA0B,MAAM;AAAA,EAIhC;AAAA,EAHF,OAAO;AAAA,EAEhB,WAAW,CACA,MACT,SACA;AAAA,IACA,MAAM,OAAO;AAAA,IAHJ;AAAA;AAKb;;;AC3BA;;;ACAA;AAQO,SAAS,oBAAmB,GAAW;AAAA,EAC5C,OAAO,WAAW,WAAW;AAAA;AAIxB,SAAS,6BAA4B,CAAC,WAAmB,UAA0B;AAAA,EACxF,MAAM,SAAS,WAAW,QAAQ,EAC/B,OAAO,KAAK,UAAU,CAAC,WAAW,UAAU,WAAW,CAAC,CAAC,CAA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I,KAAK,iBAAiB;AAAA,IAAW,IAAI,eAAe,KAAK;AAAA,EAC7D,OAAO,OAAO,KAAK,GAAG,EAAE,SAAS,IAAI,MAAM;AAAA;",
11
+ "debugId": "7F809297D191508464756E2164756E21",
12
+ "names": []
13
+ }
@@ -6,7 +6,7 @@ import {
6
6
  import {
7
7
  normalizeAiModelCallCostRecord2,
8
8
  aiModelCallCostMatchesUsage2
9
- } from "./chunk-zeykm8my.js";
9
+ } from "./chunk-3qtk0070.js";
10
10
  import {
11
11
  AiLimitStorageError2,
12
12
  aiLimitMeterApplies2
@@ -23,7 +23,7 @@ import {
23
23
  } from "./chunk-qttqe1ah.js";
24
24
  import {
25
25
  AiCostStorageError2
26
- } from "./chunk-gjhrz66x.js";
26
+ } from "./chunk-9c9yknwt.js";
27
27
  import {
28
28
  AiUsageStorageError2,
29
29
  normalizeAiModelCallRecord2
@@ -230,6 +230,7 @@ function createAuthOperationScope2(target, scope) {
230
230
  function createAgentOperationScope2(target, scope) {
231
231
  return createOperationScopedFacade2(target, scope, {
232
232
  threads: createOperationScopedFacade2(target.threads, scope),
233
+ reads: createOperationScopedFacade2(target.reads, scope),
233
234
  runs: createOperationScopedFacade2(target.runs, scope),
234
235
  messages: createOperationScopedFacade2(target.messages, scope),
235
236
  checkpoints: createOperationScopedFacade2(target.checkpoints, scope),
@@ -280,4 +281,4 @@ function isAsyncGeneratorFunction(value) {
280
281
 
281
282
  export { StorageTimer2, runWithStorageTimer2, createStorageOperationScope2, createOperationScopedFacade2, decorateOperationScopedMethodForTesting2, createAuthOperationScope2, createAgentOperationScope2, createOntologyOperationScope2, createObjectOperationScope2, createWorkflowRunOperationScope2 };
282
283
 
283
- //# debugId=4884405A8770E0EA64756E2164756E21
284
+ //# debugId=CE0CA30BDB70FCD764756E2164756E21
@@ -2,10 +2,10 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/storage/operation-scope.ts", "../src/storage/objects/guard.ts"],
4
4
  "sourcesContent": [
5
- "import { AsyncLocalStorage } from \"node:async_hooks\"\nimport type { AgentStorage } from \"./agents\"\nimport type { AuthStorage } from \"./auth\"\nimport type { ObjectStorage } from \"./objects\"\nimport { createGuardedObjectReadStorage, requireObjectReadScopeFactory } from \"./objects/guard\"\nimport type { OntologyStorage } from \"./ontology\"\nimport type { WorkflowRunStorage } from \"./workflow-runs\"\n\nexport type StorageOperationRunner = <TResult>(\n run: () => Promise<TResult> | TResult\n) => Promise<TResult>\n\n/** Provider-owned execution boundary for root storage operations. */\nexport interface StorageOperationScope {\n assertAvailable(): void\n run<TResult>(operation: () => Promise<TResult> | TResult): Promise<TResult>\n}\n\n/** How long storage was busy during one piece of work, however many calls overlapped. */\nexport class StorageTimer {\n #active = 0\n #activeSince = 0\n #busyMillis = 0\n #calls = 0\n\n begin(): void {\n this.#calls += 1\n if (this.#active === 0) this.#activeSince = performance.now()\n this.#active += 1\n }\n\n end(): void {\n this.#active -= 1\n if (this.#active === 0) this.#busyMillis += performance.now() - this.#activeSince\n }\n\n get calls(): number {\n return this.#calls\n }\n\n get busyMillis(): number {\n return this.#active === 0\n ? this.#busyMillis\n : this.#busyMillis + performance.now() - this.#activeSince\n }\n}\n\nconst storageTimers = new AsyncLocalStorage<StorageTimer>()\n\n/** Count the root storage operations `work` starts, including those it leaves running. */\nexport function runWithStorageTimer<TResult>(timer: StorageTimer, work: () => TResult): TResult {\n return storageTimers.run(timer, work)\n}\n\nexport function createStorageOperationScope(\n run: StorageOperationRunner,\n assertAvailable: () => void = () => undefined\n): StorageOperationScope {\n const executions = new AsyncLocalStorage<{ active: boolean }>()\n return {\n assertAvailable,\n async run(operation) {\n const inherited = executions.getStore()\n if (inherited?.active) {\n assertAvailable()\n return operation()\n }\n\n const execution = { active: true }\n const timer = storageTimers.getStore()\n timer?.begin()\n try {\n return await executions.run(execution, () => run(operation))\n } finally {\n execution.active = false\n timer?.end()\n }\n },\n }\n}\n\nconst operationScopeTargets = new WeakMap<object, object>()\n\n/**\n * Give every async operation exposed by a store one provider-owned execution scope.\n *\n * Storage contracts use `async` methods for I/O and reserve synchronous methods for local\n * capabilities such as `queryCapabilities()`. Discovering the former from their implementation\n * removes the second, manually synchronized method registry that previously coupled every storage\n * primitive to the SQLite/InMemory lock.\n */\nexport function createOperationScopedFacade<T extends object>(\n target: T,\n scope: StorageOperationScope,\n propertyOverrides: Partial<T> = {}\n): T {\n const methodKinds = discoverMethodKinds(target)\n const overrideKeys = new Set(Reflect.ownKeys(propertyOverrides))\n const methodCache = new Map<\n PropertyKey,\n { implementation: (...args: unknown[]) => unknown; exposed: (...args: unknown[]) => unknown }\n >()\n\n const facade = new Proxy(target, {\n get(current, property) {\n if (overrideKeys.has(property)) {\n return Reflect.get(propertyOverrides, property, propertyOverrides)\n }\n\n const value = Reflect.get(current, property, current)\n const kind = methodKinds.get(property)\n if (!kind || typeof value !== \"function\") return value\n const implementation = value as (...args: unknown[]) => unknown\n\n const cached = methodCache.get(property)\n if (cached?.implementation === implementation) return cached.exposed\n\n const exposed = scopeMethod(implementation, kind, current, scope)\n methodCache.set(property, { implementation, exposed })\n return exposed\n },\n set(current, property, value) {\n if (overrideKeys.has(property)) return false\n return Reflect.set(current, property, value, current)\n },\n defineProperty(current, property, attributes) {\n if (overrideKeys.has(property)) return false\n return Reflect.defineProperty(current, property, attributes)\n },\n deleteProperty(current, property) {\n if (overrideKeys.has(property)) return false\n return Reflect.deleteProperty(current, property)\n },\n })\n operationScopeTargets.set(facade, target)\n return facade\n}\n\ntype StorageMethod = (...args: never[]) => unknown\ntype StorageMethodKey<T> = {\n [TKey in keyof T]-?: T[TKey] extends StorageMethod ? TKey : never\n}[keyof T]\n\n/** Replace a provider method behind its scoped facade without exposing the raw provider. */\nexport function decorateOperationScopedMethodForTesting<\n T extends object,\n TKey extends StorageMethodKey<T>,\n>(\n facade: T,\n property: TKey,\n decorate: (implementation: Extract<T[TKey], StorageMethod>) => Extract<T[TKey], StorageMethod>\n): () => void {\n const target = operationScopeTargets.get(facade)\n if (!target) throw new Error(\"[Sixb] Expected an operation-scoped storage facade.\")\n\n const previousDescriptor = Reflect.getOwnPropertyDescriptor(target, property)\n const implementation = Reflect.get(target, property, target)\n if (typeof implementation !== \"function\") {\n throw new Error(`[Sixb] Storage property '${String(property)}' is not a method.`)\n }\n\n const boundImplementation = ((...args: never[]) =>\n Reflect.apply(implementation, target, args)) as Extract<T[TKey], StorageMethod>\n const decorated = decorate(boundImplementation)\n Reflect.defineProperty(target, property, {\n configurable: true,\n enumerable: previousDescriptor?.enumerable ?? false,\n writable: true,\n value: decorated,\n })\n\n return () => {\n if (previousDescriptor) {\n Reflect.defineProperty(target, property, previousDescriptor)\n } else {\n Reflect.deleteProperty(target, property)\n }\n }\n}\n\ntype StorageMethodKind = \"async\" | \"async-generator\" | \"sync\"\n\nfunction discoverMethodKinds(target: object): ReadonlyMap<PropertyKey, StorageMethodKind> {\n const methodKeys = new Set<PropertyKey>()\n for (\n let current: object | null = target;\n current && current !== Object.prototype;\n current = Object.getPrototypeOf(current)\n ) {\n for (const property of Reflect.ownKeys(current)) {\n if (property !== \"constructor\") methodKeys.add(property)\n }\n }\n\n const methodKinds = new Map<PropertyKey, StorageMethodKind>()\n for (const property of methodKeys) {\n const implementation = Reflect.get(target, property, target)\n if (typeof implementation !== \"function\") continue\n methodKinds.set(property, methodKind(implementation))\n }\n return methodKinds\n}\n\nfunction methodKind(implementation: (...args: unknown[]) => unknown): StorageMethodKind {\n if (isAsyncFunction(implementation)) return \"async\"\n if (isAsyncGeneratorFunction(implementation)) return \"async-generator\"\n return \"sync\"\n}\n\nfunction scopeMethod(\n implementation: (...args: unknown[]) => unknown,\n kind: StorageMethodKind,\n target: object,\n scope: StorageOperationScope\n): (...args: unknown[]) => unknown {\n if (kind === \"async\") {\n return (...args: unknown[]) => scope.run(() => Reflect.apply(implementation, target, args))\n }\n\n if (kind === \"async-generator\") {\n return (...args: unknown[]) => {\n scope.assertAvailable()\n return scopeSteps(\n Reflect.apply(implementation, target, args) as AsyncIterable<unknown>,\n scope\n )\n }\n }\n\n return implementation.bind(target)\n}\n\n/**\n * Each step of a stream runs in its own operation scope, released between steps: a page holds the\n * provider's lock while it reads, never while its consumer works on it.\n */\nfunction scopeSteps<T>(\n stream: AsyncIterable<T>,\n scope: StorageOperationScope\n): AsyncIterableIterator<T> {\n let iterator: AsyncIterator<T> | undefined\n const steps = () => {\n iterator ??= stream[Symbol.asyncIterator]()\n return iterator\n }\n const scoped: AsyncIterableIterator<T> = {\n next: (...args) => scope.run(() => steps().next(...args)),\n return: (value) =>\n scope.run(async () => (await steps().return?.(value)) ?? { done: true, value }),\n throw: (error) =>\n scope.run(async () => {\n const current = steps()\n if (!current.throw) throw error\n return current.throw(error)\n }),\n [Symbol.asyncIterator]: () => scoped,\n }\n return scoped\n}\n\nexport function createAuthOperationScope<T extends AuthStorage>(\n target: T,\n scope: StorageOperationScope\n): T {\n return createOperationScopedFacade<AuthStorage>(target, scope, {\n users: createOperationScopedFacade(target.users, scope),\n identities: createOperationScopedFacade(target.identities, scope),\n serviceAccounts: createOperationScopedFacade(target.serviceAccounts, scope),\n serviceAccountGroupMemberships: createOperationScopedFacade(\n target.serviceAccountGroupMemberships,\n scope\n ),\n sessions: createOperationScopedFacade(target.sessions, scope),\n accessTokens: createOperationScopedFacade(target.accessTokens, scope),\n invitations: createOperationScopedFacade(target.invitations, scope),\n groupMemberships: createOperationScopedFacade(target.groupMemberships, scope),\n magicLinks: createOperationScopedFacade(target.magicLinks, scope),\n oidcAuthorizationAttempts: createOperationScopedFacade(target.oidcAuthorizationAttempts, scope),\n deviceAuthorizations: createOperationScopedFacade(target.deviceAuthorizations, scope),\n }) as T\n}\n\nexport function createAgentOperationScope<T extends AgentStorage>(\n target: T,\n scope: StorageOperationScope\n): T {\n return createOperationScopedFacade<AgentStorage>(target, scope, {\n threads: createOperationScopedFacade(target.threads, scope),\n runs: createOperationScopedFacade(target.runs, scope),\n messages: createOperationScopedFacade(target.messages, scope),\n checkpoints: createOperationScopedFacade(target.checkpoints, scope),\n memory: createOperationScopedFacade(target.memory, scope),\n approvals: createOperationScopedFacade(target.approvals, scope),\n approvalModes: createOperationScopedFacade(target.approvalModes, scope),\n tokenRates: createOperationScopedFacade(target.tokenRates, scope),\n inbox: createOperationScopedFacade(target.inbox, scope),\n computers: createOperationScopedFacade(target.computers, scope),\n }) as T\n}\n\nexport function createOntologyOperationScope<T extends OntologyStorage>(\n target: T,\n scope: StorageOperationScope\n): T {\n return createOperationScopedFacade<OntologyStorage>(target, scope, {\n commits: createOperationScopedFacade(target.commits, scope),\n sources: createOperationScopedFacade(target.sources, scope),\n materializations: createOperationScopedFacade(target.materializations, scope),\n replacementPlans: createOperationScopedFacade(target.replacementPlans, scope),\n outbox: createOperationScopedFacade(target.outbox, scope),\n uniqueValues: createOperationScopedFacade(target.uniqueValues, scope),\n ...(target.vectors ? { vectors: createOperationScopedFacade(target.vectors, scope) } : {}),\n }) as T\n}\n\n/** Keep synchronously created scoped readers inside the provider's root operation scope. */\nexport function createObjectOperationScope<T extends ObjectStorage>(\n target: T,\n scope: StorageOperationScope\n): T {\n const factory = requireObjectReadScopeFactory(target)\n return createOperationScopedFacade<ObjectStorage>(target, scope, {\n createSelectedReadScope: (params) => {\n scope.assertAvailable()\n return createGuardedObjectReadStorage(factory.createSelectedReadScope(params), scope)\n },\n createConditionalReadScope: (params) => {\n scope.assertAvailable()\n return createGuardedObjectReadStorage(factory.createConditionalReadScope(params), scope)\n },\n }) as T\n}\n\nexport function createWorkflowRunOperationScope<T extends WorkflowRunStorage>(\n target: T,\n scope: StorageOperationScope\n): T {\n return createOperationScopedFacade<WorkflowRunStorage>(target, scope, {\n nodes: createOperationScopedFacade(target.nodes, scope),\n agentNodes: createOperationScopedFacade(target.agentNodes, scope),\n }) as T\n}\n\nfunction isAsyncFunction(value: unknown): value is (...args: unknown[]) => Promise<unknown> {\n return typeof value === \"function\" && value.constructor.name === \"AsyncFunction\"\n}\n\nfunction isAsyncGeneratorFunction(value: unknown): boolean {\n return typeof value === \"function\" && value.constructor.name === \"AsyncGeneratorFunction\"\n}\n",
5
+ "import { AsyncLocalStorage } from \"node:async_hooks\"\nimport type { AgentStorage } from \"./agents\"\nimport type { AuthStorage } from \"./auth\"\nimport type { ObjectStorage } from \"./objects\"\nimport { createGuardedObjectReadStorage, requireObjectReadScopeFactory } from \"./objects/guard\"\nimport type { OntologyStorage } from \"./ontology\"\nimport type { WorkflowRunStorage } from \"./workflow-runs\"\n\nexport type StorageOperationRunner = <TResult>(\n run: () => Promise<TResult> | TResult\n) => Promise<TResult>\n\n/** Provider-owned execution boundary for root storage operations. */\nexport interface StorageOperationScope {\n assertAvailable(): void\n run<TResult>(operation: () => Promise<TResult> | TResult): Promise<TResult>\n}\n\n/** How long storage was busy during one piece of work, however many calls overlapped. */\nexport class StorageTimer {\n #active = 0\n #activeSince = 0\n #busyMillis = 0\n #calls = 0\n\n begin(): void {\n this.#calls += 1\n if (this.#active === 0) this.#activeSince = performance.now()\n this.#active += 1\n }\n\n end(): void {\n this.#active -= 1\n if (this.#active === 0) this.#busyMillis += performance.now() - this.#activeSince\n }\n\n get calls(): number {\n return this.#calls\n }\n\n get busyMillis(): number {\n return this.#active === 0\n ? this.#busyMillis\n : this.#busyMillis + performance.now() - this.#activeSince\n }\n}\n\nconst storageTimers = new AsyncLocalStorage<StorageTimer>()\n\n/** Count the root storage operations `work` starts, including those it leaves running. */\nexport function runWithStorageTimer<TResult>(timer: StorageTimer, work: () => TResult): TResult {\n return storageTimers.run(timer, work)\n}\n\nexport function createStorageOperationScope(\n run: StorageOperationRunner,\n assertAvailable: () => void = () => undefined\n): StorageOperationScope {\n const executions = new AsyncLocalStorage<{ active: boolean }>()\n return {\n assertAvailable,\n async run(operation) {\n const inherited = executions.getStore()\n if (inherited?.active) {\n assertAvailable()\n return operation()\n }\n\n const execution = { active: true }\n const timer = storageTimers.getStore()\n timer?.begin()\n try {\n return await executions.run(execution, () => run(operation))\n } finally {\n execution.active = false\n timer?.end()\n }\n },\n }\n}\n\nconst operationScopeTargets = new WeakMap<object, object>()\n\n/**\n * Give every async operation exposed by a store one provider-owned execution scope.\n *\n * Storage contracts use `async` methods for I/O and reserve synchronous methods for local\n * capabilities such as `queryCapabilities()`. Discovering the former from their implementation\n * removes the second, manually synchronized method registry that previously coupled every storage\n * primitive to the SQLite/InMemory lock.\n */\nexport function createOperationScopedFacade<T extends object>(\n target: T,\n scope: StorageOperationScope,\n propertyOverrides: Partial<T> = {}\n): T {\n const methodKinds = discoverMethodKinds(target)\n const overrideKeys = new Set(Reflect.ownKeys(propertyOverrides))\n const methodCache = new Map<\n PropertyKey,\n { implementation: (...args: unknown[]) => unknown; exposed: (...args: unknown[]) => unknown }\n >()\n\n const facade = new Proxy(target, {\n get(current, property) {\n if (overrideKeys.has(property)) {\n return Reflect.get(propertyOverrides, property, propertyOverrides)\n }\n\n const value = Reflect.get(current, property, current)\n const kind = methodKinds.get(property)\n if (!kind || typeof value !== \"function\") return value\n const implementation = value as (...args: unknown[]) => unknown\n\n const cached = methodCache.get(property)\n if (cached?.implementation === implementation) return cached.exposed\n\n const exposed = scopeMethod(implementation, kind, current, scope)\n methodCache.set(property, { implementation, exposed })\n return exposed\n },\n set(current, property, value) {\n if (overrideKeys.has(property)) return false\n return Reflect.set(current, property, value, current)\n },\n defineProperty(current, property, attributes) {\n if (overrideKeys.has(property)) return false\n return Reflect.defineProperty(current, property, attributes)\n },\n deleteProperty(current, property) {\n if (overrideKeys.has(property)) return false\n return Reflect.deleteProperty(current, property)\n },\n })\n operationScopeTargets.set(facade, target)\n return facade\n}\n\ntype StorageMethod = (...args: never[]) => unknown\ntype StorageMethodKey<T> = {\n [TKey in keyof T]-?: T[TKey] extends StorageMethod ? TKey : never\n}[keyof T]\n\n/** Replace a provider method behind its scoped facade without exposing the raw provider. */\nexport function decorateOperationScopedMethodForTesting<\n T extends object,\n TKey extends StorageMethodKey<T>,\n>(\n facade: T,\n property: TKey,\n decorate: (implementation: Extract<T[TKey], StorageMethod>) => Extract<T[TKey], StorageMethod>\n): () => void {\n const target = operationScopeTargets.get(facade)\n if (!target) throw new Error(\"[Sixb] Expected an operation-scoped storage facade.\")\n\n const previousDescriptor = Reflect.getOwnPropertyDescriptor(target, property)\n const implementation = Reflect.get(target, property, target)\n if (typeof implementation !== \"function\") {\n throw new Error(`[Sixb] Storage property '${String(property)}' is not a method.`)\n }\n\n const boundImplementation = ((...args: never[]) =>\n Reflect.apply(implementation, target, args)) as Extract<T[TKey], StorageMethod>\n const decorated = decorate(boundImplementation)\n Reflect.defineProperty(target, property, {\n configurable: true,\n enumerable: previousDescriptor?.enumerable ?? false,\n writable: true,\n value: decorated,\n })\n\n return () => {\n if (previousDescriptor) {\n Reflect.defineProperty(target, property, previousDescriptor)\n } else {\n Reflect.deleteProperty(target, property)\n }\n }\n}\n\ntype StorageMethodKind = \"async\" | \"async-generator\" | \"sync\"\n\nfunction discoverMethodKinds(target: object): ReadonlyMap<PropertyKey, StorageMethodKind> {\n const methodKeys = new Set<PropertyKey>()\n for (\n let current: object | null = target;\n current && current !== Object.prototype;\n current = Object.getPrototypeOf(current)\n ) {\n for (const property of Reflect.ownKeys(current)) {\n if (property !== \"constructor\") methodKeys.add(property)\n }\n }\n\n const methodKinds = new Map<PropertyKey, StorageMethodKind>()\n for (const property of methodKeys) {\n const implementation = Reflect.get(target, property, target)\n if (typeof implementation !== \"function\") continue\n methodKinds.set(property, methodKind(implementation))\n }\n return methodKinds\n}\n\nfunction methodKind(implementation: (...args: unknown[]) => unknown): StorageMethodKind {\n if (isAsyncFunction(implementation)) return \"async\"\n if (isAsyncGeneratorFunction(implementation)) return \"async-generator\"\n return \"sync\"\n}\n\nfunction scopeMethod(\n implementation: (...args: unknown[]) => unknown,\n kind: StorageMethodKind,\n target: object,\n scope: StorageOperationScope\n): (...args: unknown[]) => unknown {\n if (kind === \"async\") {\n return (...args: unknown[]) => scope.run(() => Reflect.apply(implementation, target, args))\n }\n\n if (kind === \"async-generator\") {\n return (...args: unknown[]) => {\n scope.assertAvailable()\n return scopeSteps(\n Reflect.apply(implementation, target, args) as AsyncIterable<unknown>,\n scope\n )\n }\n }\n\n return implementation.bind(target)\n}\n\n/**\n * Each step of a stream runs in its own operation scope, released between steps: a page holds the\n * provider's lock while it reads, never while its consumer works on it.\n */\nfunction scopeSteps<T>(\n stream: AsyncIterable<T>,\n scope: StorageOperationScope\n): AsyncIterableIterator<T> {\n let iterator: AsyncIterator<T> | undefined\n const steps = () => {\n iterator ??= stream[Symbol.asyncIterator]()\n return iterator\n }\n const scoped: AsyncIterableIterator<T> = {\n next: (...args) => scope.run(() => steps().next(...args)),\n return: (value) =>\n scope.run(async () => (await steps().return?.(value)) ?? { done: true, value }),\n throw: (error) =>\n scope.run(async () => {\n const current = steps()\n if (!current.throw) throw error\n return current.throw(error)\n }),\n [Symbol.asyncIterator]: () => scoped,\n }\n return scoped\n}\n\nexport function createAuthOperationScope<T extends AuthStorage>(\n target: T,\n scope: StorageOperationScope\n): T {\n return createOperationScopedFacade<AuthStorage>(target, scope, {\n users: createOperationScopedFacade(target.users, scope),\n identities: createOperationScopedFacade(target.identities, scope),\n serviceAccounts: createOperationScopedFacade(target.serviceAccounts, scope),\n serviceAccountGroupMemberships: createOperationScopedFacade(\n target.serviceAccountGroupMemberships,\n scope\n ),\n sessions: createOperationScopedFacade(target.sessions, scope),\n accessTokens: createOperationScopedFacade(target.accessTokens, scope),\n invitations: createOperationScopedFacade(target.invitations, scope),\n groupMemberships: createOperationScopedFacade(target.groupMemberships, scope),\n magicLinks: createOperationScopedFacade(target.magicLinks, scope),\n oidcAuthorizationAttempts: createOperationScopedFacade(target.oidcAuthorizationAttempts, scope),\n deviceAuthorizations: createOperationScopedFacade(target.deviceAuthorizations, scope),\n }) as T\n}\n\nexport function createAgentOperationScope<T extends AgentStorage>(\n target: T,\n scope: StorageOperationScope\n): T {\n return createOperationScopedFacade<AgentStorage>(target, scope, {\n threads: createOperationScopedFacade(target.threads, scope),\n reads: createOperationScopedFacade(target.reads, scope),\n runs: createOperationScopedFacade(target.runs, scope),\n messages: createOperationScopedFacade(target.messages, scope),\n checkpoints: createOperationScopedFacade(target.checkpoints, scope),\n memory: createOperationScopedFacade(target.memory, scope),\n approvals: createOperationScopedFacade(target.approvals, scope),\n approvalModes: createOperationScopedFacade(target.approvalModes, scope),\n tokenRates: createOperationScopedFacade(target.tokenRates, scope),\n inbox: createOperationScopedFacade(target.inbox, scope),\n computers: createOperationScopedFacade(target.computers, scope),\n }) as T\n}\n\nexport function createOntologyOperationScope<T extends OntologyStorage>(\n target: T,\n scope: StorageOperationScope\n): T {\n return createOperationScopedFacade<OntologyStorage>(target, scope, {\n commits: createOperationScopedFacade(target.commits, scope),\n sources: createOperationScopedFacade(target.sources, scope),\n materializations: createOperationScopedFacade(target.materializations, scope),\n replacementPlans: createOperationScopedFacade(target.replacementPlans, scope),\n outbox: createOperationScopedFacade(target.outbox, scope),\n uniqueValues: createOperationScopedFacade(target.uniqueValues, scope),\n ...(target.vectors ? { vectors: createOperationScopedFacade(target.vectors, scope) } : {}),\n }) as T\n}\n\n/** Keep synchronously created scoped readers inside the provider's root operation scope. */\nexport function createObjectOperationScope<T extends ObjectStorage>(\n target: T,\n scope: StorageOperationScope\n): T {\n const factory = requireObjectReadScopeFactory(target)\n return createOperationScopedFacade<ObjectStorage>(target, scope, {\n createSelectedReadScope: (params) => {\n scope.assertAvailable()\n return createGuardedObjectReadStorage(factory.createSelectedReadScope(params), scope)\n },\n createConditionalReadScope: (params) => {\n scope.assertAvailable()\n return createGuardedObjectReadStorage(factory.createConditionalReadScope(params), scope)\n },\n }) as T\n}\n\nexport function createWorkflowRunOperationScope<T extends WorkflowRunStorage>(\n target: T,\n scope: StorageOperationScope\n): T {\n return createOperationScopedFacade<WorkflowRunStorage>(target, scope, {\n nodes: createOperationScopedFacade(target.nodes, scope),\n agentNodes: createOperationScopedFacade(target.agentNodes, scope),\n }) as T\n}\n\nfunction isAsyncFunction(value: unknown): value is (...args: unknown[]) => Promise<unknown> {\n return typeof value === \"function\" && value.constructor.name === \"AsyncFunction\"\n}\n\nfunction isAsyncGeneratorFunction(value: unknown): boolean {\n return typeof value === \"function\" && value.constructor.name === \"AsyncGeneratorFunction\"\n}\n",
6
6
  "import type { ObjectReadScopeFactory, ObjectReadStorage, ObjectStorage } from \"./types\"\n\nexport interface ObjectReadStorageCallGuard {\n assertAvailable(): void\n run<TResult>(operation: () => Promise<TResult>): Promise<TResult>\n}\n\n/** Validate the required runtime capability before any facade can expose broad object reads. */\nexport function requireObjectReadScopeFactory(storage: ObjectStorage): ObjectReadScopeFactory {\n if (\n typeof storage.createSelectedReadScope !== \"function\" ||\n typeof storage.createConditionalReadScope !== \"function\"\n ) {\n throw new Error(\n \"[Sixb] Object storage provider must implement ObjectReadScopeFactory to create selected and conditional object readers.\"\n )\n }\n return storage\n}\n\n/**\n * Guard every scoped-reader terminal without proxying the provider reader.\n *\n * First-party providers freeze their readers. A Proxy cannot substitute a frozen own method\n * without violating JavaScript's invariants, so operation and lifetime guards use this explicit\n * facade instead.\n */\nexport function createGuardedObjectReadStorage(\n reader: ObjectReadStorage,\n guard: ObjectReadStorageCallGuard\n): ObjectReadStorage {\n const guarded: ObjectReadStorage = {\n queryCapabilities: () => {\n guard.assertAvailable()\n return reader.queryCapabilities()\n },\n getByPrimaryId: (input) => guard.run(() => reader.getByPrimaryId(input)),\n getByUniqueValue: (input) => guard.run(() => reader.getByUniqueValue(input)),\n selectsObjectProperties: (input) => guard.run(() => reader.selectsObjectProperties(input)),\n listLinks: (input) => guard.run(() => reader.listLinks(input)),\n getByPrimaryIdBatch: (input) => guard.run(() => reader.getByPrimaryIdBatch(input)),\n listLinksBatch: (input) => guard.run(() => reader.listLinksBatch(input)),\n queryLinks: (input) => guard.run(() => reader.queryLinks(input)),\n list: (input) => guard.run(() => reader.list(input)),\n }\n if (reader.queryObjects) {\n guarded.queryObjects = (input) => guard.run(() => reader.queryObjects!(input))\n }\n if (reader.countObjects) {\n guarded.countObjects = (input) => guard.run(() => reader.countObjects!(input))\n }\n if (reader.existsObjects) {\n guarded.existsObjects = (input) => guard.run(() => reader.existsObjects!(input))\n }\n if (reader.facetObjects) {\n guarded.facetObjects = (input) => guard.run(() => reader.facetObjects!(input))\n }\n return Object.freeze(guarded)\n}\n"
7
7
  ],
8
- "mappings": ";;AAAA;;;ACQO,SAAS,6BAA6B,CAAC,SAAgD;AAAA,EAC5F,IACE,OAAO,QAAQ,4BAA4B,cAC3C,OAAO,QAAQ,+BAA+B,YAC9C;AAAA,IACA,MAAM,IAAI,MACR,yHACF;AAAA,EACF;AAAA,EACA,OAAO;AAAA;AAUF,SAAS,8BAA8B,CAC5C,QACA,OACmB;AAAA,EACnB,MAAM,UAA6B;AAAA,IACjC,mBAAmB,MAAM;AAAA,MACvB,MAAM,gBAAgB;AAAA,MACtB,OAAO,OAAO,kBAAkB;AAAA;AAAA,IAElC,gBAAgB,CAAC,UAAU,MAAM,IAAI,MAAM,OAAO,eAAe,KAAK,CAAC;AAAA,IACvE,kBAAkB,CAAC,UAAU,MAAM,IAAI,MAAM,OAAO,iBAAiB,KAAK,CAAC;AAAA,IAC3E,yBAAyB,CAAC,UAAU,MAAM,IAAI,MAAM,OAAO,wBAAwB,KAAK,CAAC;AAAA,IACzF,WAAW,CAAC,UAAU,MAAM,IAAI,MAAM,OAAO,UAAU,KAAK,CAAC;AAAA,IAC7D,qBAAqB,CAAC,UAAU,MAAM,IAAI,MAAM,OAAO,oBAAoB,KAAK,CAAC;AAAA,IACjF,gBAAgB,CAAC,UAAU,MAAM,IAAI,MAAM,OAAO,eAAe,KAAK,CAAC;AAAA,IACvE,YAAY,CAAC,UAAU,MAAM,IAAI,MAAM,OAAO,WAAW,KAAK,CAAC;AAAA,IAC/D,MAAM,CAAC,UAAU,MAAM,IAAI,MAAM,OAAO,KAAK,KAAK,CAAC;AAAA,EACrD;AAAA,EACA,IAAI,OAAO,cAAc;AAAA,IACvB,QAAQ,eAAe,CAAC,UAAU,MAAM,IAAI,MAAM,OAAO,aAAc,KA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  normalizeParams,
7
7
  coerceParamsToTyped
8
- } from "./chunk-stmxh0hv.js";
8
+ } from "./chunk-3neam1y5.js";
9
9
  import {
10
10
  isPlainRecord
11
11
  } from "./chunk-wy0qdqfm.js";
@@ -3,7 +3,7 @@ import {
3
3
  isArtifactRefPropertySchema,
4
4
  resolvePropertyQueryCapabilities2,
5
5
  resolveQuerySchema
6
- } from "./chunk-3zagkr6w.js";
6
+ } from "./chunk-7mhbs9yy.js";
7
7
  import {
8
8
  isUserRefPropertySchema
9
9
  } from "./chunk-7j4yydm2.js";
@@ -4,12 +4,12 @@ import {
4
4
  validateObjectQueryWithAdmission,
5
5
  SYSTEM_PRINCIPAL2,
6
6
  principalsEqual2
7
- } from "./chunk-xcrnrpfh.js";
7
+ } from "./chunk-394zjzjs.js";
8
8
  import {
9
9
  resolveRuntimeAuthorizationForProject,
10
10
  AuthorizationError2,
11
11
  isRuntimeAllowed2
12
- } from "./chunk-paxabbqd.js";
12
+ } from "./chunk-tapdssb5.js";
13
13
  import {
14
14
  createArtifactId,
15
15
  createArtifactCommentId
@@ -20,11 +20,11 @@ import {
20
20
  } from "./chunk-wkv3h3q7.js";
21
21
  import {
22
22
  collectArtifactRefIds
23
- } from "./chunk-3zagkr6w.js";
23
+ } from "./chunk-7mhbs9yy.js";
24
24
  import {
25
25
  ArtifactStorageError,
26
26
  turnUndoable2
27
- } from "./chunk-ewqn51gr.js";
27
+ } from "./chunk-88xeh6zx.js";
28
28
  import {
29
29
  ARTIFACT_LIMITS2,
30
30
  ARTIFACT_STATE_LIMITS2,
@@ -36,12 +36,13 @@ import {
36
36
  } from "./chunk-xrmbhap8.js";
37
37
  import {
38
38
  objectBatchKey2
39
- } from "./chunk-gjhrz66x.js";
39
+ } from "./chunk-9c9yknwt.js";
40
40
  import {
41
41
  objectReadersIn,
42
42
  getAuthorizedOntologyView,
43
+ getQueryDiscovery,
43
44
  readerClearance
44
- } from "./chunk-5t9gm5tt.js";
45
+ } from "./chunk-fmgf9h5e.js";
45
46
  import {
46
47
  ArtifactRequestError2,
47
48
  documentData,
@@ -115,6 +116,11 @@ import {
115
116
  } from "./chunk-9wr3yajk.js";
116
117
 
117
118
  // src/agents/thread-access.ts
119
+ function agentRunEndedShort(run) {
120
+ if (run.status === "failed")
121
+ return true;
122
+ return run.finishReason === "timeout" || run.finishReason === "interrupted";
123
+ }
118
124
  function createAgentThreadAccessRule(runtime, authority, agents) {
119
125
  const caller = authority.type === "principal" ? authority.context.principal : SYSTEM_PRINCIPAL2;
120
126
  const blocked = authority.type === "denied" || authority.type === "delegated";
@@ -704,12 +710,19 @@ async function withDocumentHolding(context, artifactId, files, baseRevision, sto
704
710
  }
705
711
  }
706
712
  }
707
- async function undoneTurnDocuments(context, turnRunId) {
713
+ async function undoneTurnDocuments(context, turnRunId, laterTurnRunIds = []) {
708
714
  const { projectId, storage } = context;
709
715
  const documents = {};
710
- for (const write of await storage.listTurnWrites({ projectId, turnRunId })) {
711
- if (write.created)
716
+ const laterWrites = new Map;
717
+ for (const later of laterTurnRunIds) {
718
+ for (const write of await storage.listTurnWrites({ projectId, turnRunId: later })) {
719
+ laterWrites.set(write.artifactId, (laterWrites.get(write.artifactId) ?? 0) + write.writes);
720
+ }
721
+ }
722
+ for (const own of await storage.listTurnWrites({ projectId, turnRunId })) {
723
+ if (own.created)
712
724
  continue;
725
+ const write = { ...own, writes: own.writes + (laterWrites.get(own.artifactId) ?? 0) };
713
726
  const artifact = await storage.get({ projectId, id: write.artifactId });
714
727
  if (!artifact || !keepsDocument2(artifact.kind))
715
728
  continue;
@@ -1496,7 +1509,10 @@ async function runArtifactQuery(runtime, name, query) {
1496
1509
  }
1497
1510
  }
1498
1511
  function describeArtifactQuery(runtime, query) {
1499
- const validated = validateObjectQuery2(query.query, { ontology: runtime.ontology });
1512
+ const validated = validateObjectQuery2(query.query, {
1513
+ ontology: runtime.ontology,
1514
+ discovery: getQueryDiscovery(runtime.objectReader)
1515
+ });
1500
1516
  return {
1501
1517
  resultObjectTypeIds: [...validated.result.objectTypeIds],
1502
1518
  readObjectTypeIds: [...validated.touchedObjectTypeIds],
@@ -3188,6 +3204,6 @@ function notFound3(artifactId) {
3188
3204
  return new ArtifactRequestError2("artifact_not_found", `[Sixb] Artifact '${artifactId}' was not found.`);
3189
3205
  }
3190
3206
 
3191
- export { createAgentThreadAccessRule, assertConversationThread2, conversationThreadId2, agentThreadViews, announceArtifactUpdates, readLiveFiles2, storeLiveFiles2, sameArtifactFiles2, keepsDocument2, loadArtifactDocument2, readDocumentState2, firstArtifactDocument, withMergedWrite, undoneTurnDocuments, answerArtifactQueries2, parseArtifactQueryAnswers2, BOARD_PREVIEW_MEDIA_TYPES2, MAX_BOARD_PREVIEW_BYTES2, boardRenderKey, boardPreviewsOfCopy, boardsReadLiveData2, boardPreviews2, boardPreview2, missingBoardPreviews2, boardPreviewStatuses2, storeBoardPreviews2, MAX_DOCUMENT_PDF_BYTES2, documentPdfKey2, publishArtifact2, prepareArtifactVersion2, storeArtifactVersion2, artifactVersionWarnings2, artifactAccessRule2, artifactTransactionRules, artifactQueryChecker2, artifactPreviewRequester, writeLiveArtifact2, createRuntimeArtifactAccessRule, transactionArtifactAccessRules, updatableArtifactIds, createArtifactsRuntime };
3207
+ export { agentRunEndedShort, createAgentThreadAccessRule, assertConversationThread2, conversationThreadId2, agentThreadViews, announceArtifactUpdates, readLiveFiles2, storeLiveFiles2, sameArtifactFiles2, keepsDocument2, loadArtifactDocument2, readDocumentState2, firstArtifactDocument, withMergedWrite, undoneTurnDocuments, answerArtifactQueries2, parseArtifactQueryAnswers2, BOARD_PREVIEW_MEDIA_TYPES2, MAX_BOARD_PREVIEW_BYTES2, boardRenderKey, boardPreviewsOfCopy, boardsReadLiveData2, boardPreviews2, boardPreview2, missingBoardPreviews2, boardPreviewStatuses2, storeBoardPreviews2, MAX_DOCUMENT_PDF_BYTES2, documentPdfKey2, publishArtifact2, prepareArtifactVersion2, storeArtifactVersion2, artifactVersionWarnings2, artifactAccessRule2, artifactTransactionRules, artifactQueryChecker2, artifactPreviewRequester, writeLiveArtifact2, createRuntimeArtifactAccessRule, transactionArtifactAccessRules, updatableArtifactIds, createArtifactsRuntime };
3192
3208
 
3193
- //# debugId=9B02BA7B361316AF64756E2164756E21
3209
+ //# debugId=1B316407BA72A01964756E2164756E21