@sixb/core 0.1.21 → 0.1.22

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 (1263) hide show
  1. package/dist/actions/commit-edits.d.ts +3 -1
  2. package/dist/actions/commit-edits.d.ts.map +1 -1
  3. package/dist/actions/execution.d.ts.map +1 -1
  4. package/dist/actions/index.js +63 -59
  5. package/dist/actions/index.js.map +1 -1
  6. package/dist/actions/read-facade.d.ts +9 -1
  7. package/dist/actions/read-facade.d.ts.map +1 -1
  8. package/dist/actions/request.d.ts +15 -1
  9. package/dist/actions/request.d.ts.map +1 -1
  10. package/dist/actions/run/context.d.ts +1 -0
  11. package/dist/actions/run/context.d.ts.map +1 -1
  12. package/dist/actions/run/execute.d.ts +2 -3
  13. package/dist/actions/run/execute.d.ts.map +1 -1
  14. package/dist/actions/run/executor.d.ts +3 -0
  15. package/dist/actions/run/executor.d.ts.map +1 -1
  16. package/dist/actions/run/normalize.d.ts +2 -1
  17. package/dist/actions/run/normalize.d.ts.map +1 -1
  18. package/dist/actions/run/signals.d.ts +1 -3
  19. package/dist/actions/run/signals.d.ts.map +1 -1
  20. package/dist/actions/run/types.d.ts +16 -1
  21. package/dist/actions/run/types.d.ts.map +1 -1
  22. package/dist/actions/run-authorization.d.ts +14 -0
  23. package/dist/actions/run-authorization.d.ts.map +1 -1
  24. package/dist/actions/types/context.d.ts +17 -1
  25. package/dist/actions/types/context.d.ts.map +1 -1
  26. package/dist/actions/validators.d.ts.map +1 -1
  27. package/dist/activity/timeline.d.ts +8 -1
  28. package/dist/activity/timeline.d.ts.map +1 -1
  29. package/dist/agents/accounting.d.ts +15 -0
  30. package/dist/agents/accounting.d.ts.map +1 -0
  31. package/dist/agents/adapters.d.ts.map +1 -1
  32. package/dist/agents/agent-mail.d.ts +9 -0
  33. package/dist/agents/agent-mail.d.ts.map +1 -0
  34. package/dist/agents/api-gateway.d.ts +5 -0
  35. package/dist/agents/api-gateway.d.ts.map +1 -1
  36. package/dist/agents/approval-continuation.d.ts +23 -0
  37. package/dist/agents/approval-continuation.d.ts.map +1 -0
  38. package/dist/agents/approval-executor.d.ts +56 -0
  39. package/dist/agents/approval-executor.d.ts.map +1 -0
  40. package/dist/agents/approval-outcome.d.ts +8 -0
  41. package/dist/agents/approval-outcome.d.ts.map +1 -0
  42. package/dist/agents/approvals.d.ts +210 -0
  43. package/dist/agents/approvals.d.ts.map +1 -0
  44. package/dist/agents/authority.d.ts +10 -0
  45. package/dist/agents/authority.d.ts.map +1 -1
  46. package/dist/agents/builders.d.ts.map +1 -1
  47. package/dist/agents/cancel.d.ts +23 -0
  48. package/dist/agents/cancel.d.ts.map +1 -0
  49. package/dist/agents/child-question.d.ts +18 -0
  50. package/dist/agents/child-question.d.ts.map +1 -0
  51. package/dist/agents/children.d.ts +99 -0
  52. package/dist/agents/children.d.ts.map +1 -0
  53. package/dist/agents/context/index.js +1 -1
  54. package/dist/agents/context-compaction.d.ts.map +1 -1
  55. package/dist/agents/errors.d.ts +13 -1
  56. package/dist/agents/errors.d.ts.map +1 -1
  57. package/dist/agents/execution.d.ts +180 -14
  58. package/dist/agents/execution.d.ts.map +1 -1
  59. package/dist/agents/fork.d.ts +16 -0
  60. package/dist/agents/fork.d.ts.map +1 -0
  61. package/dist/agents/ids.d.ts +7 -0
  62. package/dist/agents/ids.d.ts.map +1 -1
  63. package/dist/agents/index.d.ts +19 -8
  64. package/dist/agents/index.d.ts.map +1 -1
  65. package/dist/agents/index.js +159 -86
  66. package/dist/agents/index.js.map +1 -1
  67. package/dist/agents/memory-execution.d.ts +57 -0
  68. package/dist/agents/memory-execution.d.ts.map +1 -0
  69. package/dist/agents/memory.d.ts +49 -0
  70. package/dist/agents/memory.d.ts.map +1 -0
  71. package/dist/agents/message.d.ts +50 -1
  72. package/dist/agents/message.d.ts.map +1 -1
  73. package/dist/agents/model-loop.d.ts +19 -0
  74. package/dist/agents/model-loop.d.ts.map +1 -1
  75. package/dist/agents/model-routing.d.ts +19 -0
  76. package/dist/agents/model-routing.d.ts.map +1 -0
  77. package/dist/agents/participants.d.ts +18 -0
  78. package/dist/agents/participants.d.ts.map +1 -0
  79. package/dist/agents/reference.d.ts.map +1 -1
  80. package/dist/agents/request.d.ts +36 -2
  81. package/dist/agents/request.d.ts.map +1 -1
  82. package/dist/agents/run-scope.d.ts +51 -0
  83. package/dist/agents/run-scope.d.ts.map +1 -0
  84. package/dist/agents/streams/index.d.ts +3 -2
  85. package/dist/agents/streams/index.d.ts.map +1 -1
  86. package/dist/agents/streams/index.js +7 -3
  87. package/dist/agents/streams/index.js.map +1 -1
  88. package/dist/agents/streams/internal.d.ts +1 -1
  89. package/dist/agents/streams/internal.d.ts.map +1 -1
  90. package/dist/agents/streams/internal.js +5 -3
  91. package/dist/agents/streams/internal.js.map +1 -1
  92. package/dist/agents/streams/protocol.d.ts +122 -3
  93. package/dist/agents/streams/protocol.d.ts.map +1 -1
  94. package/dist/agents/subagent-runs.d.ts +12 -0
  95. package/dist/agents/subagent-runs.d.ts.map +1 -0
  96. package/dist/agents/thread-access.d.ts +53 -0
  97. package/dist/agents/thread-access.d.ts.map +1 -0
  98. package/dist/agents/tool-definition.d.ts +5 -4
  99. package/dist/agents/tool-definition.d.ts.map +1 -1
  100. package/dist/agents/types.d.ts +23 -4
  101. package/dist/agents/types.d.ts.map +1 -1
  102. package/dist/agents/validation.d.ts +1 -1
  103. package/dist/agents/validation.d.ts.map +1 -1
  104. package/dist/artifacts/access.d.ts +52 -0
  105. package/dist/artifacts/access.d.ts.map +1 -0
  106. package/dist/artifacts/canvas.d.ts +92 -0
  107. package/dist/artifacts/canvas.d.ts.map +1 -0
  108. package/dist/artifacts/csv.d.ts +5 -0
  109. package/dist/artifacts/csv.d.ts.map +1 -1
  110. package/dist/artifacts/errors.d.ts +7 -2
  111. package/dist/artifacts/errors.d.ts.map +1 -1
  112. package/dist/artifacts/execution.d.ts +102 -7
  113. package/dist/artifacts/execution.d.ts.map +1 -1
  114. package/dist/artifacts/formula/check.d.ts +24 -0
  115. package/dist/artifacts/formula/check.d.ts.map +1 -0
  116. package/dist/artifacts/formula/evaluate.d.ts +32 -0
  117. package/dist/artifacts/formula/evaluate.d.ts.map +1 -0
  118. package/dist/artifacts/formula/index.d.ts +38 -0
  119. package/dist/artifacts/formula/index.d.ts.map +1 -0
  120. package/dist/artifacts/formula/parser.d.ts +67 -0
  121. package/dist/artifacts/formula/parser.d.ts.map +1 -0
  122. package/dist/artifacts/frames/assets.d.ts +11 -9
  123. package/dist/artifacts/frames/assets.d.ts.map +1 -1
  124. package/dist/artifacts/frames/entries.d.ts +19 -0
  125. package/dist/artifacts/frames/entries.d.ts.map +1 -0
  126. package/dist/artifacts/frames/grants.d.ts +6 -6
  127. package/dist/artifacts/frames/grants.d.ts.map +1 -1
  128. package/dist/artifacts/frames/index.d.ts +4 -2
  129. package/dist/artifacts/frames/index.d.ts.map +1 -1
  130. package/dist/artifacts/frames/index.js +444 -51
  131. package/dist/artifacts/frames/index.js.map +10 -8
  132. package/dist/artifacts/frames/kit.d.ts +10 -5
  133. package/dist/artifacts/frames/kit.d.ts.map +1 -1
  134. package/dist/artifacts/frames/probe.d.ts +16 -12
  135. package/dist/artifacts/frames/probe.d.ts.map +1 -1
  136. package/dist/artifacts/frames/protocol.d.ts +79 -10
  137. package/dist/artifacts/frames/protocol.d.ts.map +1 -1
  138. package/dist/artifacts/frames/runtime.d.ts +27 -9
  139. package/dist/artifacts/frames/runtime.d.ts.map +1 -1
  140. package/dist/artifacts/index.d.ts +11 -5
  141. package/dist/artifacts/index.d.ts.map +1 -1
  142. package/dist/artifacts/index.js +128 -6
  143. package/dist/artifacts/index.js.map +3 -3
  144. package/dist/artifacts/kinds.d.ts +1 -1
  145. package/dist/artifacts/kinds.d.ts.map +1 -1
  146. package/dist/artifacts/limits.d.ts +30 -0
  147. package/dist/artifacts/limits.d.ts.map +1 -1
  148. package/dist/artifacts/live-sheet.d.ts +65 -0
  149. package/dist/artifacts/live-sheet.d.ts.map +1 -0
  150. package/dist/artifacts/outline.d.ts +27 -1
  151. package/dist/artifacts/outline.d.ts.map +1 -1
  152. package/dist/artifacts/publish/index.d.ts +2 -0
  153. package/dist/artifacts/publish/index.d.ts.map +1 -1
  154. package/dist/artifacts/publish/index.js +59 -19
  155. package/dist/artifacts/publish/index.js.map +1 -1
  156. package/dist/artifacts/publish/publish.d.ts +43 -11
  157. package/dist/artifacts/publish/publish.d.ts.map +1 -1
  158. package/dist/artifacts/publish/queries.d.ts +33 -0
  159. package/dist/artifacts/publish/queries.d.ts.map +1 -0
  160. package/dist/artifacts/publish/references.d.ts +6 -3
  161. package/dist/artifacts/publish/references.d.ts.map +1 -1
  162. package/dist/artifacts/publish/validate/canvas.d.ts +18 -0
  163. package/dist/artifacts/publish/validate/canvas.d.ts.map +1 -0
  164. package/dist/artifacts/publish/validate/html.d.ts +20 -0
  165. package/dist/artifacts/publish/validate/html.d.ts.map +1 -0
  166. package/dist/artifacts/publish/validate/page.d.ts +15 -0
  167. package/dist/artifacts/publish/validate/page.d.ts.map +1 -0
  168. package/dist/artifacts/publish/validate/sheet.d.ts +11 -3
  169. package/dist/artifacts/publish/validate/sheet.d.ts.map +1 -1
  170. package/dist/artifacts/publish/validate/slides.d.ts +1 -7
  171. package/dist/artifacts/publish/validate/slides.d.ts.map +1 -1
  172. package/dist/artifacts/queries.d.ts +95 -0
  173. package/dist/artifacts/queries.d.ts.map +1 -0
  174. package/dist/artifacts/resolve.d.ts +6 -0
  175. package/dist/artifacts/resolve.d.ts.map +1 -1
  176. package/dist/artifacts/run-query.d.ts +26 -0
  177. package/dist/artifacts/run-query.d.ts.map +1 -0
  178. package/dist/artifacts/serialize-query.d.ts +12 -0
  179. package/dist/artifacts/serialize-query.d.ts.map +1 -0
  180. package/dist/artifacts/sheet-rules.d.ts +26 -0
  181. package/dist/artifacts/sheet-rules.d.ts.map +1 -0
  182. package/dist/artifacts/tones.d.ts +8 -0
  183. package/dist/artifacts/tones.d.ts.map +1 -0
  184. package/dist/artifacts/workbook.d.ts +76 -5
  185. package/dist/artifacts/workbook.d.ts.map +1 -1
  186. package/dist/auth/index.d.ts +1 -1
  187. package/dist/auth/index.d.ts.map +1 -1
  188. package/dist/auth/index.js +14 -11
  189. package/dist/auth/index.js.map +1 -1
  190. package/dist/auth/member-events.d.ts +13 -0
  191. package/dist/auth/member-events.d.ts.map +1 -0
  192. package/dist/auth/profile.d.ts +11 -0
  193. package/dist/auth/profile.d.ts.map +1 -0
  194. package/dist/auth/runtime.d.ts +31 -3
  195. package/dist/auth/runtime.d.ts.map +1 -1
  196. package/dist/auth/strategy.d.ts +3 -1
  197. package/dist/auth/strategy.d.ts.map +1 -1
  198. package/dist/auth/strategy.js +7 -3
  199. package/dist/auth/strategy.js.map +1 -1
  200. package/dist/auth/types.d.ts +30 -1
  201. package/dist/auth/types.d.ts.map +1 -1
  202. package/dist/authorization/decision.d.ts +15 -0
  203. package/dist/authorization/decision.d.ts.map +1 -1
  204. package/dist/authorization/event-visibility.d.ts +5 -1
  205. package/dist/authorization/event-visibility.d.ts.map +1 -1
  206. package/dist/authorization/grant-kinds.d.ts +2 -2
  207. package/dist/authorization/grant-kinds.d.ts.map +1 -1
  208. package/dist/authorization/index.d.ts +2 -2
  209. package/dist/authorization/index.d.ts.map +1 -1
  210. package/dist/authorization/index.js +12 -7
  211. package/dist/authorization/index.js.map +1 -1
  212. package/dist/authorization/resolve.d.ts +19 -1
  213. package/dist/authorization/resolve.d.ts.map +1 -1
  214. package/dist/authorization/run-visibility.d.ts +8 -1
  215. package/dist/authorization/run-visibility.d.ts.map +1 -1
  216. package/dist/authorization/types.d.ts +14 -0
  217. package/dist/authorization/types.d.ts.map +1 -1
  218. package/dist/bootstrap/index.js +69 -65
  219. package/dist/bootstrap/index.js.map +2 -2
  220. package/dist/{chunk-ky3j490c.js → chunk-02bzjgnt.js} +6 -6
  221. package/dist/{chunk-ky3j490c.js.map → chunk-02bzjgnt.js.map} +1 -1
  222. package/dist/{chunk-mfs23znk.js → chunk-07kkp2e1.js} +1 -1
  223. package/dist/{chunk-c1rxbz5y.js → chunk-098anw4f.js} +21 -19
  224. package/dist/chunk-098anw4f.js.map +12 -0
  225. package/dist/{chunk-z58tm0hm.js → chunk-0phpbbvm.js} +3 -3
  226. package/dist/{chunk-ere85b8y.js → chunk-0xmt5p5y.js} +116 -27
  227. package/dist/chunk-0xmt5p5y.js.map +14 -0
  228. package/dist/{chunk-t6f3tdnr.js → chunk-16a9dmfy.js} +33 -2
  229. package/dist/{chunk-t6f3tdnr.js.map → chunk-16a9dmfy.js.map} +5 -4
  230. package/dist/chunk-18sk89cg.js +47 -0
  231. package/dist/chunk-18sk89cg.js.map +10 -0
  232. package/dist/{chunk-e17zdm62.js → chunk-1t6k1avb.js} +1 -1
  233. package/dist/chunk-2626mh4m.js +693 -0
  234. package/dist/chunk-2626mh4m.js.map +19 -0
  235. package/dist/{chunk-qczk96d9.js → chunk-2adz0h75.js} +13 -4
  236. package/dist/chunk-2adz0h75.js.map +11 -0
  237. package/dist/{chunk-kge7k6ey.js → chunk-2fn60nvs.js} +2 -2
  238. package/dist/{chunk-99nd4rc1.js → chunk-2gjj5dx3.js} +5 -4
  239. package/dist/{chunk-99nd4rc1.js.map → chunk-2gjj5dx3.js.map} +3 -3
  240. package/dist/{chunk-mjddfa7k.js → chunk-3fqxbn31.js} +2 -24
  241. package/dist/{chunk-mjddfa7k.js.map → chunk-3fqxbn31.js.map} +3 -4
  242. package/dist/{chunk-y0c4e6ex.js → chunk-3gbefjg5.js} +1 -1
  243. package/dist/{chunk-5hx48dnn.js → chunk-45ngkxkp.js} +52 -31
  244. package/dist/chunk-45ngkxkp.js.map +13 -0
  245. package/dist/{chunk-cy4mbddw.js → chunk-48jezz3j.js} +1 -1
  246. package/dist/{chunk-561r0yc9.js → chunk-4b26qwbg.js} +13 -13
  247. package/dist/{chunk-561r0yc9.js.map → chunk-4b26qwbg.js.map} +1 -1
  248. package/dist/{chunk-9k93ah50.js → chunk-4f3ydv7t.js} +33 -69
  249. package/dist/chunk-4f3ydv7t.js.map +10 -0
  250. package/dist/chunk-4y26vs3v.js +97 -0
  251. package/dist/chunk-4y26vs3v.js.map +10 -0
  252. package/dist/{chunk-4as3wt1c.js → chunk-4ymrcdbm.js} +7 -3
  253. package/dist/chunk-4ymrcdbm.js.map +12 -0
  254. package/dist/{chunk-hcbyfxbe.js → chunk-5grk14e5.js} +76 -2
  255. package/dist/{chunk-hcbyfxbe.js.map → chunk-5grk14e5.js.map} +4 -3
  256. package/dist/{chunk-8frc8a4j.js → chunk-65pyhyas.js} +90 -83
  257. package/dist/chunk-65pyhyas.js.map +20 -0
  258. package/dist/{chunk-hwksyjks.js → chunk-661ezhks.js} +182 -6
  259. package/dist/chunk-661ezhks.js.map +11 -0
  260. package/dist/{chunk-447a5c0p.js → chunk-6n69k945.js} +2 -2
  261. package/dist/{chunk-0bphap9y.js → chunk-6p0pastb.js} +5 -5
  262. package/dist/{chunk-9j4jw7as.js → chunk-6rrtzea3.js} +18 -5
  263. package/dist/chunk-6rrtzea3.js.map +14 -0
  264. package/dist/{chunk-431pyp2c.js → chunk-6y0mkhex.js} +2 -2
  265. package/dist/{chunk-f4pamkt9.js → chunk-73v685wb.js} +10 -10
  266. package/dist/{chunk-f4pamkt9.js.map → chunk-73v685wb.js.map} +3 -3
  267. package/dist/{chunk-akzryx9h.js → chunk-7gr4j2eq.js} +7836 -5047
  268. package/dist/chunk-7gr4j2eq.js.map +120 -0
  269. package/dist/{chunk-bk9svbcq.js → chunk-7mc2wkre.js} +386 -86
  270. package/dist/chunk-7mc2wkre.js.map +50 -0
  271. package/dist/{chunk-6rqgmkde.js → chunk-7z5p905k.js} +335 -703
  272. package/dist/chunk-7z5p905k.js.map +22 -0
  273. package/dist/{chunk-yxd3nnqt.js → chunk-9mab3dvg.js} +26 -2
  274. package/dist/chunk-9mab3dvg.js.map +11 -0
  275. package/dist/chunk-9wr3yajk.js +42 -0
  276. package/dist/chunk-9wr3yajk.js.map +10 -0
  277. package/dist/chunk-az47zep4.js +41 -0
  278. package/dist/chunk-az47zep4.js.map +10 -0
  279. package/dist/{chunk-s7jg7pmn.js → chunk-bab05bhg.js} +1 -1
  280. package/dist/{chunk-858emn8m.js → chunk-bktev1ds.js} +14 -11
  281. package/dist/{chunk-858emn8m.js.map → chunk-bktev1ds.js.map} +3 -3
  282. package/dist/{chunk-dhcv7yxc.js → chunk-c0vk1djt.js} +5 -3
  283. package/dist/chunk-c0vk1djt.js.map +11 -0
  284. package/dist/chunk-c69nj7se.js +3 -0
  285. package/dist/{chunk-7n30ybym.js.map → chunk-c69nj7se.js.map} +1 -1
  286. package/dist/{chunk-q5e5tv4b.js → chunk-c844dkwd.js} +1 -1
  287. package/dist/{chunk-g257jwnc.js → chunk-cdk3egjj.js} +17 -4
  288. package/dist/chunk-cdk3egjj.js.map +12 -0
  289. package/dist/chunk-cswhawa2.js +113 -0
  290. package/dist/chunk-cswhawa2.js.map +10 -0
  291. package/dist/{chunk-cfj9dfbb.js → chunk-d2m879s4.js} +2 -2
  292. package/dist/{chunk-arns890k.js → chunk-d7vyc7k6.js} +2 -2
  293. package/dist/chunk-d7vyc7k6.js.map +10 -0
  294. package/dist/{chunk-q7gn29y3.js → chunk-dp0cdtj2.js} +2 -2
  295. package/dist/{chunk-6x0pqh32.js → chunk-e5wf5vz0.js} +3 -1
  296. package/dist/chunk-e5wf5vz0.js.map +10 -0
  297. package/dist/{chunk-cn0fwwhy.js → chunk-efmm01gj.js} +108 -1045
  298. package/dist/chunk-efmm01gj.js.map +18 -0
  299. package/dist/{chunk-918wwnaa.js → chunk-ezne9wc9.js} +1224 -430
  300. package/dist/chunk-ezne9wc9.js.map +71 -0
  301. package/dist/{chunk-tbc1ngpd.js → chunk-fe8zwt8b.js} +58 -12
  302. package/dist/{chunk-tbc1ngpd.js.map → chunk-fe8zwt8b.js.map} +5 -4
  303. package/dist/{chunk-br3k6qbf.js → chunk-fm62y49k.js} +1 -1
  304. package/dist/{chunk-nq6gpjt7.js → chunk-fntqb7qy.js} +30 -4
  305. package/dist/{chunk-nq6gpjt7.js.map → chunk-fntqb7qy.js.map} +5 -5
  306. package/dist/{chunk-1cc1xaf3.js → chunk-fp2kq35z.js} +26 -10
  307. package/dist/{chunk-1cc1xaf3.js.map → chunk-fp2kq35z.js.map} +5 -5
  308. package/dist/{chunk-vvxtn22d.js → chunk-g663fahq.js} +2 -2
  309. package/dist/{chunk-k43ct2ke.js → chunk-gvj5cd3b.js} +16 -9
  310. package/dist/chunk-gvj5cd3b.js.map +12 -0
  311. package/dist/{chunk-rmakanzx.js → chunk-h33shhq6.js} +5 -5
  312. package/dist/{chunk-nn5xnx3s.js → chunk-h3pbv7n8.js} +1738 -38
  313. package/dist/chunk-h3pbv7n8.js.map +48 -0
  314. package/dist/chunk-hn2r7z41.js.map +1 -1
  315. package/dist/{chunk-pbcbn83d.js → chunk-hqsp2sx4.js} +54 -8
  316. package/dist/chunk-hqsp2sx4.js.map +14 -0
  317. package/dist/{chunk-d09e3rax.js → chunk-hwarjrgf.js} +1 -1
  318. package/dist/{chunk-vf57cr4t.js → chunk-hyesv9dv.js} +1 -1
  319. package/dist/chunk-hz5d43gn.js +45 -0
  320. package/dist/chunk-hz5d43gn.js.map +10 -0
  321. package/dist/{chunk-91mg3nj9.js → chunk-j936th07.js} +86 -41
  322. package/dist/chunk-j936th07.js.map +12 -0
  323. package/dist/chunk-kcqpk9w1.js +75 -0
  324. package/dist/chunk-kcqpk9w1.js.map +10 -0
  325. package/dist/{chunk-5vems3nx.js → chunk-m2nevja0.js} +2 -2
  326. package/dist/{chunk-x9v4cx1d.js → chunk-m36fw8ft.js} +1 -1
  327. package/dist/{chunk-a40ad1ft.js → chunk-mbsbxarb.js} +1 -1
  328. package/dist/chunk-mzx71snp.js +129 -0
  329. package/dist/chunk-mzx71snp.js.map +10 -0
  330. package/dist/{chunk-6aawea28.js → chunk-n8q5j6y5.js} +1 -1
  331. package/dist/{chunk-d7dnxdep.js → chunk-n9zpx9c6.js} +4 -4
  332. package/dist/{chunk-xvsc5m8n.js → chunk-npcr0228.js} +1 -1
  333. package/dist/chunk-nydf3dbe.js +663 -0
  334. package/dist/chunk-nydf3dbe.js.map +13 -0
  335. package/dist/chunk-pdt5cw8z.js +233 -0
  336. package/dist/chunk-pdt5cw8z.js.map +11 -0
  337. package/dist/{chunk-rj69qcrd.js → chunk-pgrf64hp.js} +55 -7
  338. package/dist/chunk-pgrf64hp.js.map +12 -0
  339. package/dist/{chunk-y5tah2kf.js → chunk-q4pmvkg0.js} +1 -1
  340. package/dist/chunk-qhqgp4jf.js +1418 -0
  341. package/dist/chunk-qhqgp4jf.js.map +22 -0
  342. package/dist/{chunk-48qjhh6v.js → chunk-qx00vjrj.js} +19 -60
  343. package/dist/chunk-qx00vjrj.js.map +13 -0
  344. package/dist/{chunk-5948n82c.js → chunk-r6szek0x.js} +184 -7
  345. package/dist/chunk-r6szek0x.js.map +10 -0
  346. package/dist/{chunk-v4jbb3rs.js → chunk-rap5w0x0.js} +156 -2
  347. package/dist/chunk-rap5w0x0.js.map +10 -0
  348. package/dist/{chunk-pfp1txq2.js → chunk-sgx82nnt.js} +5 -31
  349. package/dist/{chunk-pfp1txq2.js.map → chunk-sgx82nnt.js.map} +3 -4
  350. package/dist/{chunk-bkpke1sg.js → chunk-t5608tkq.js} +3 -1
  351. package/dist/{chunk-bkpke1sg.js.map → chunk-t5608tkq.js.map} +3 -3
  352. package/dist/{chunk-29yx306f.js → chunk-tdxfsg1c.js} +507 -265
  353. package/dist/chunk-tdxfsg1c.js.map +23 -0
  354. package/dist/{chunk-d5rjr8c0.js → chunk-vabga7fk.js} +1 -1
  355. package/dist/{chunk-dhdha526.js → chunk-vhbw5sqm.js} +26 -2
  356. package/dist/chunk-vhbw5sqm.js.map +10 -0
  357. package/dist/{chunk-e6k4thh5.js → chunk-vpgwq5nf.js} +98 -12
  358. package/dist/chunk-vpgwq5nf.js.map +21 -0
  359. package/dist/{chunk-61y5xs4p.js → chunk-vyt322b6.js} +69 -50
  360. package/dist/{chunk-61y5xs4p.js.map → chunk-vyt322b6.js.map} +4 -4
  361. package/dist/chunk-waqk73p1.js +2380 -0
  362. package/dist/chunk-waqk73p1.js.map +23 -0
  363. package/dist/chunk-wsc1brye.js +27 -0
  364. package/dist/chunk-wsc1brye.js.map +10 -0
  365. package/dist/{chunk-96yw3pwd.js → chunk-y7dbmaqh.js} +28 -2
  366. package/dist/chunk-y7dbmaqh.js.map +10 -0
  367. package/dist/{chunk-6vb4st8k.js → chunk-yc9ners4.js} +120 -19
  368. package/dist/{chunk-6vb4st8k.js.map → chunk-yc9ners4.js.map} +8 -8
  369. package/dist/{chunk-dvd2fp9q.js → chunk-zbc929zg.js} +28 -4
  370. package/dist/chunk-zbc929zg.js.map +13 -0
  371. package/dist/chunk-zrvhsq7f.js +37 -0
  372. package/dist/chunk-zrvhsq7f.js.map +10 -0
  373. package/dist/datasets/write.js +5 -5
  374. package/dist/error-reporting/internal.js +3 -3
  375. package/dist/errors/catalog.d.ts +26 -0
  376. package/dist/errors/catalog.d.ts.map +1 -1
  377. package/dist/errors/internal.d.ts.map +1 -1
  378. package/dist/errors/internal.js +1 -1
  379. package/dist/events/definitions.d.ts +7 -0
  380. package/dist/events/definitions.d.ts.map +1 -1
  381. package/dist/events/execution.d.ts.map +1 -1
  382. package/dist/events/index.d.ts +2 -3
  383. package/dist/events/index.d.ts.map +1 -1
  384. package/dist/events/index.js +8 -10
  385. package/dist/events/index.js.map +1 -1
  386. package/dist/events/scope.d.ts.map +1 -1
  387. package/dist/events/scope.js +1 -1
  388. package/dist/events/selectors/builder.d.ts +12 -1
  389. package/dist/events/selectors/builder.d.ts.map +1 -1
  390. package/dist/events/selectors/index.d.ts +2 -2
  391. package/dist/events/selectors/index.d.ts.map +1 -1
  392. package/dist/events/selectors/index.js +2 -2
  393. package/dist/events/selectors/types.d.ts +19 -3
  394. package/dist/events/selectors/types.d.ts.map +1 -1
  395. package/dist/events/service.d.ts +17 -2
  396. package/dist/events/service.d.ts.map +1 -1
  397. package/dist/events/types/index.d.ts +3 -1
  398. package/dist/events/types/index.d.ts.map +1 -1
  399. package/dist/events/types/users.d.ts +63 -0
  400. package/dist/events/types/users.d.ts.map +1 -0
  401. package/dist/events/view-conditions.d.ts +34 -0
  402. package/dist/events/view-conditions.d.ts.map +1 -0
  403. package/dist/execution/agent.d.ts +15 -0
  404. package/dist/execution/agent.d.ts.map +1 -1
  405. package/dist/execution/agent.js +63 -57
  406. package/dist/execution/agent.js.map +1 -1
  407. package/dist/execution/authorization.d.ts.map +1 -1
  408. package/dist/execution/authorized-object-reader.d.ts +51 -2
  409. package/dist/execution/authorized-object-reader.d.ts.map +1 -1
  410. package/dist/execution/lineage.d.ts +7 -0
  411. package/dist/execution/lineage.d.ts.map +1 -0
  412. package/dist/execution/object-reader-ontology.d.ts +2 -2
  413. package/dist/execution/object-reader-ontology.d.ts.map +1 -1
  414. package/dist/execution/object-reader-security.d.ts +24 -3
  415. package/dist/execution/object-reader-security.d.ts.map +1 -1
  416. package/dist/execution/object-reader-users.d.ts +20 -0
  417. package/dist/execution/object-reader-users.d.ts.map +1 -0
  418. package/dist/execution/preparation.d.ts +23 -0
  419. package/dist/execution/preparation.d.ts.map +1 -0
  420. package/dist/execution/primitive.js +61 -57
  421. package/dist/execution/primitive.js.map +1 -1
  422. package/dist/execution/request.d.ts +2 -1
  423. package/dist/execution/request.d.ts.map +1 -1
  424. package/dist/execution/request.js +64 -56
  425. package/dist/execution/request.js.map +3 -3
  426. package/dist/execution/unique-lookup.d.ts +14 -0
  427. package/dist/execution/unique-lookup.d.ts.map +1 -0
  428. package/dist/execution/visible-objects.d.ts +12 -0
  429. package/dist/execution/visible-objects.d.ts.map +1 -0
  430. package/dist/http/api-routes.d.ts +17 -0
  431. package/dist/http/api-routes.d.ts.map +1 -1
  432. package/dist/http/index.js +1 -1
  433. package/dist/index.d.ts +32 -15
  434. package/dist/index.d.ts.map +1 -1
  435. package/dist/index.js +137 -126
  436. package/dist/index.js.map +1 -1
  437. package/dist/lake-storage/index.js +5 -5
  438. package/dist/materialization/errors.d.ts +25 -0
  439. package/dist/materialization/errors.d.ts.map +1 -1
  440. package/dist/materialization/event-envelopes.d.ts +5 -0
  441. package/dist/materialization/event-envelopes.d.ts.map +1 -1
  442. package/dist/materialization/index.d.ts +1 -1
  443. package/dist/materialization/index.d.ts.map +1 -1
  444. package/dist/materialization/index.js +14 -8
  445. package/dist/materialization/index.js.map +1 -1
  446. package/dist/materialization/model.d.ts +20 -2
  447. package/dist/materialization/model.d.ts.map +1 -1
  448. package/dist/materializer/edits/commit.d.ts.map +1 -1
  449. package/dist/materializer/edits/load-state.d.ts +5 -1
  450. package/dist/materializer/edits/load-state.d.ts.map +1 -1
  451. package/dist/materializer/edits/plan.d.ts.map +1 -1
  452. package/dist/materializer/edits/unique-values.d.ts +47 -0
  453. package/dist/materializer/edits/unique-values.d.ts.map +1 -0
  454. package/dist/materializer/edits/working-state.d.ts +6 -1
  455. package/dist/materializer/edits/working-state.d.ts.map +1 -1
  456. package/dist/materializer/execution/work-records.d.ts +7 -1
  457. package/dist/materializer/execution/work-records.d.ts.map +1 -1
  458. package/dist/materializer/index.js +45 -41
  459. package/dist/materializer/index.js.map +1 -1
  460. package/dist/materializer/projections/replacement-plan.d.ts.map +1 -1
  461. package/dist/materializer/projections/source-materialization.d.ts +1 -0
  462. package/dist/materializer/projections/source-materialization.d.ts.map +1 -1
  463. package/dist/materializer/shared/normalize.d.ts.map +1 -1
  464. package/dist/materializer/shared/projection-run.d.ts +0 -1
  465. package/dist/materializer/shared/projection-run.d.ts.map +1 -1
  466. package/dist/materializer/telemetry/plan.d.ts.map +1 -1
  467. package/dist/models/audio/catalog.d.ts +13 -1
  468. package/dist/models/audio/catalog.d.ts.map +1 -1
  469. package/dist/models/audio/errors.d.ts +6 -1
  470. package/dist/models/audio/errors.d.ts.map +1 -1
  471. package/dist/models/audio/runtime.d.ts.map +1 -1
  472. package/dist/models/audio/speech.d.ts +8 -0
  473. package/dist/models/audio/speech.d.ts.map +1 -0
  474. package/dist/models/audio/types.d.ts +93 -0
  475. package/dist/models/audio/types.d.ts.map +1 -1
  476. package/dist/models/calls.d.ts +27 -0
  477. package/dist/models/calls.d.ts.map +1 -0
  478. package/dist/models/catalog-index.d.ts +7 -4
  479. package/dist/models/catalog-index.d.ts.map +1 -1
  480. package/dist/models/catalog.d.ts +55 -3
  481. package/dist/models/catalog.d.ts.map +1 -1
  482. package/dist/models/decision/runtime.d.ts +6 -1
  483. package/dist/models/decision/runtime.d.ts.map +1 -1
  484. package/dist/models/decision/validation.d.ts +4 -1
  485. package/dist/models/decision/validation.d.ts.map +1 -1
  486. package/dist/models/definitions.d.ts +23 -1
  487. package/dist/models/definitions.d.ts.map +1 -1
  488. package/dist/models/events.d.ts +12 -1
  489. package/dist/models/events.d.ts.map +1 -1
  490. package/dist/models/execution/binding.d.ts +3 -1
  491. package/dist/models/execution/binding.d.ts.map +1 -1
  492. package/dist/models/execution/index.d.ts +1 -0
  493. package/dist/models/execution/index.d.ts.map +1 -1
  494. package/dist/models/execution/index.js +44 -34
  495. package/dist/models/execution/index.js.map +1 -1
  496. package/dist/models/execution/model-call-accounting.d.ts.map +1 -1
  497. package/dist/models/execution/model-call-recorder.d.ts +3 -0
  498. package/dist/models/execution/model-call-recorder.d.ts.map +1 -1
  499. package/dist/models/execution/usage.d.ts.map +1 -1
  500. package/dist/models/execution.d.ts +4 -2
  501. package/dist/models/execution.d.ts.map +1 -1
  502. package/dist/models/generation-types.d.ts +8 -1
  503. package/dist/models/generation-types.d.ts.map +1 -1
  504. package/dist/models/image/catalog.d.ts +13 -0
  505. package/dist/models/image/catalog.d.ts.map +1 -0
  506. package/dist/models/image/errors.d.ts +8 -0
  507. package/dist/models/image/errors.d.ts.map +1 -0
  508. package/dist/models/image/runtime.d.ts +8 -0
  509. package/dist/models/image/runtime.d.ts.map +1 -0
  510. package/dist/models/image/types.d.ts +103 -0
  511. package/dist/models/image/types.d.ts.map +1 -0
  512. package/dist/models/index.d.ts +12 -8
  513. package/dist/models/index.d.ts.map +1 -1
  514. package/dist/models/index.js +17 -7
  515. package/dist/models/index.js.map +1 -1
  516. package/dist/models/input-file.d.ts +9 -0
  517. package/dist/models/input-file.d.ts.map +1 -0
  518. package/dist/models/language-model.d.ts +13 -0
  519. package/dist/models/language-model.d.ts.map +1 -1
  520. package/dist/models/pricing.d.ts +25 -10
  521. package/dist/models/pricing.d.ts.map +1 -1
  522. package/dist/models/rate-card.d.ts +44 -6
  523. package/dist/models/rate-card.d.ts.map +1 -1
  524. package/dist/objects/conditional-writes.d.ts +37 -0
  525. package/dist/objects/conditional-writes.d.ts.map +1 -0
  526. package/dist/objects/execution.d.ts +2 -0
  527. package/dist/objects/execution.d.ts.map +1 -1
  528. package/dist/objects/index.d.ts +1 -0
  529. package/dist/objects/index.d.ts.map +1 -1
  530. package/dist/objects/index.js +68 -58
  531. package/dist/objects/index.js.map +1 -1
  532. package/dist/objects/link/authorization.d.ts +3 -0
  533. package/dist/objects/link/authorization.d.ts.map +1 -1
  534. package/dist/objects/link/endpoints.d.ts +21 -2
  535. package/dist/objects/link/endpoints.d.ts.map +1 -1
  536. package/dist/objects/link/remove.d.ts.map +1 -1
  537. package/dist/objects/link/upsert-batch.d.ts.map +1 -1
  538. package/dist/objects/link/upsert.d.ts.map +1 -1
  539. package/dist/objects/materializer-adapter.d.ts +13 -4
  540. package/dist/objects/materializer-adapter.d.ts.map +1 -1
  541. package/dist/objects/object/delete.d.ts +3 -0
  542. package/dist/objects/object/delete.d.ts.map +1 -1
  543. package/dist/objects/object/upsert-batch.d.ts.map +1 -1
  544. package/dist/objects/object/upsert.d.ts.map +1 -1
  545. package/dist/objects/query/current-user.d.ts +17 -0
  546. package/dist/objects/query/current-user.d.ts.map +1 -0
  547. package/dist/objects/query/executor.d.ts +14 -0
  548. package/dist/objects/query/executor.d.ts.map +1 -1
  549. package/dist/objects/query/index.d.ts +2 -2
  550. package/dist/objects/query/index.d.ts.map +1 -1
  551. package/dist/objects/query/index.js +49 -44
  552. package/dist/objects/query/index.js.map +1 -1
  553. package/dist/objects/query/ir.d.ts +19 -1
  554. package/dist/objects/query/ir.d.ts.map +1 -1
  555. package/dist/objects/query/matches-predicate.d.ts +9 -0
  556. package/dist/objects/query/matches-predicate.d.ts.map +1 -0
  557. package/dist/objects/query/normalize.d.ts.map +1 -1
  558. package/dist/objects/query/user-expansions.d.ts +27 -0
  559. package/dist/objects/query/user-expansions.d.ts.map +1 -0
  560. package/dist/objects/query/validate.d.ts.map +1 -1
  561. package/dist/objects/runtime-batch.d.ts +3 -1
  562. package/dist/objects/runtime-batch.d.ts.map +1 -1
  563. package/dist/objects/sdk/object-set.d.ts.map +1 -1
  564. package/dist/objects/sdk/query-executor.d.ts +6 -0
  565. package/dist/objects/sdk/query-executor.d.ts.map +1 -1
  566. package/dist/objects/serialize.d.ts +39 -0
  567. package/dist/objects/serialize.d.ts.map +1 -0
  568. package/dist/objects/unique-violation.d.ts +22 -0
  569. package/dist/objects/unique-violation.d.ts.map +1 -0
  570. package/dist/ontology/builders.d.ts +3 -1
  571. package/dist/ontology/builders.d.ts.map +1 -1
  572. package/dist/ontology/index.d.ts +2 -2
  573. package/dist/ontology/index.d.ts.map +1 -1
  574. package/dist/ontology/index.js +11 -7
  575. package/dist/ontology/index.js.map +1 -1
  576. package/dist/ontology/internal.js +7 -5
  577. package/dist/ontology/internal.js.map +3 -3
  578. package/dist/ontology/json-schema.d.ts.map +1 -1
  579. package/dist/ontology/primitives.d.ts +3 -0
  580. package/dist/ontology/primitives.d.ts.map +1 -1
  581. package/dist/ontology/registry.d.ts +6 -0
  582. package/dist/ontology/registry.d.ts.map +1 -1
  583. package/dist/ontology/types.d.ts +9 -0
  584. package/dist/ontology/types.d.ts.map +1 -1
  585. package/dist/ontology/unique-values.d.ts +26 -0
  586. package/dist/ontology/unique-values.d.ts.map +1 -0
  587. package/dist/ontology/user-ref.d.ts +23 -0
  588. package/dist/ontology/user-ref.d.ts.map +1 -1
  589. package/dist/ontology/validation/properties.d.ts.map +1 -1
  590. package/dist/ontology/validation/schema.d.ts.map +1 -1
  591. package/dist/pipelines/index.js +43 -40
  592. package/dist/pipelines/index.js.map +1 -1
  593. package/dist/projections/internal.js +36 -33
  594. package/dist/projections/internal.js.map +1 -1
  595. package/dist/projections/registry.d.ts +4 -0
  596. package/dist/projections/registry.d.ts.map +1 -1
  597. package/dist/projections/revision.d.ts +15 -0
  598. package/dist/projections/revision.d.ts.map +1 -1
  599. package/dist/projections/run-dispatch.d.ts.map +1 -1
  600. package/dist/projections/types.d.ts +2 -0
  601. package/dist/projections/types.d.ts.map +1 -1
  602. package/dist/query.d.ts +4 -2
  603. package/dist/query.d.ts.map +1 -1
  604. package/dist/query.js +2 -2
  605. package/dist/rules/execution.d.ts.map +1 -1
  606. package/dist/runtime/ai-cost.d.ts +2 -0
  607. package/dist/runtime/ai-cost.d.ts.map +1 -1
  608. package/dist/runtime/ai-usage.d.ts +7 -0
  609. package/dist/runtime/ai-usage.d.ts.map +1 -1
  610. package/dist/runtime/host.d.ts.map +1 -1
  611. package/dist/runtime/index.d.ts +1 -1
  612. package/dist/runtime/index.d.ts.map +1 -1
  613. package/dist/runtime/internal.js +42 -38
  614. package/dist/runtime/internal.js.map +1 -1
  615. package/dist/runtime/resolve-definitions.d.ts.map +1 -1
  616. package/dist/runtime/sixb.d.ts +2 -0
  617. package/dist/runtime/sixb.d.ts.map +1 -1
  618. package/dist/runtime/types.d.ts +66 -8
  619. package/dist/runtime/types.d.ts.map +1 -1
  620. package/dist/sandboxes/index.js +7 -6
  621. package/dist/sandboxes/index.js.map +1 -1
  622. package/dist/schedules/builders.d.ts.map +1 -1
  623. package/dist/schedules/index.js +3 -3
  624. package/dist/schedules/runtime.d.ts.map +1 -1
  625. package/dist/schedules/validation.d.ts.map +1 -1
  626. package/dist/security/grants.d.ts +12 -4
  627. package/dist/security/grants.d.ts.map +1 -1
  628. package/dist/security/index.d.ts +1 -1
  629. package/dist/security/index.d.ts.map +1 -1
  630. package/dist/security/internal.js +1 -1
  631. package/dist/security/project.d.ts +4 -1
  632. package/dist/security/project.d.ts.map +1 -1
  633. package/dist/security/public.js +2 -2
  634. package/dist/security/registry.d.ts +6 -0
  635. package/dist/security/registry.d.ts.map +1 -1
  636. package/dist/security/types.d.ts +47 -9
  637. package/dist/security/types.d.ts.map +1 -1
  638. package/dist/security/validation.d.ts.map +1 -1
  639. package/dist/security/view-conditions.d.ts +37 -0
  640. package/dist/security/view-conditions.d.ts.map +1 -0
  641. package/dist/shares/execution.d.ts.map +1 -1
  642. package/dist/shares/internal.js +34 -31
  643. package/dist/shares/internal.js.map +2 -2
  644. package/dist/storage/action-runs/failure.js +2 -2
  645. package/dist/storage/action-runs/provider.js +1 -1
  646. package/dist/storage/action-runs/types.d.ts +1 -1
  647. package/dist/storage/action-runs/types.d.ts.map +1 -1
  648. package/dist/storage/agents/errors.d.ts +3 -1
  649. package/dist/storage/agents/errors.d.ts.map +1 -1
  650. package/dist/storage/agents/in-memory.d.ts +120 -3
  651. package/dist/storage/agents/in-memory.d.ts.map +1 -1
  652. package/dist/storage/agents/index.d.ts +2 -2
  653. package/dist/storage/agents/index.d.ts.map +1 -1
  654. package/dist/storage/agents/provider.d.ts +154 -4
  655. package/dist/storage/agents/provider.d.ts.map +1 -1
  656. package/dist/storage/agents/provider.js +60 -5
  657. package/dist/storage/agents/provider.js.map +1 -1
  658. package/dist/storage/agents/types.d.ts +565 -13
  659. package/dist/storage/agents/types.d.ts.map +1 -1
  660. package/dist/storage/ai-cost/analytics.d.ts +10 -1
  661. package/dist/storage/ai-cost/analytics.d.ts.map +1 -1
  662. package/dist/storage/ai-cost/groups.d.ts +9 -0
  663. package/dist/storage/ai-cost/groups.d.ts.map +1 -1
  664. package/dist/storage/ai-cost/index.d.ts +1 -1
  665. package/dist/storage/ai-cost/index.d.ts.map +1 -1
  666. package/dist/storage/ai-cost/provider.d.ts +2 -1
  667. package/dist/storage/ai-cost/provider.d.ts.map +1 -1
  668. package/dist/storage/ai-cost/provider.js +11 -5
  669. package/dist/storage/ai-cost/provider.js.map +1 -1
  670. package/dist/storage/ai-cost/types.d.ts +14 -2
  671. package/dist/storage/ai-cost/types.d.ts.map +1 -1
  672. package/dist/storage/ai-cost/validation.d.ts.map +1 -1
  673. package/dist/storage/ai-limits/enforcement.js +5 -4
  674. package/dist/storage/ai-limits/enforcement.js.map +1 -1
  675. package/dist/storage/ai-limits/provider.d.ts +1 -1
  676. package/dist/storage/ai-limits/provider.d.ts.map +1 -1
  677. package/dist/storage/ai-limits/provider.js +3 -2
  678. package/dist/storage/ai-limits/provider.js.map +1 -1
  679. package/dist/storage/ai-usage/in-memory.d.ts +5 -1
  680. package/dist/storage/ai-usage/in-memory.d.ts.map +1 -1
  681. package/dist/storage/ai-usage/index.d.ts +2 -2
  682. package/dist/storage/ai-usage/index.d.ts.map +1 -1
  683. package/dist/storage/ai-usage/record.d.ts +5 -1
  684. package/dist/storage/ai-usage/record.d.ts.map +1 -1
  685. package/dist/storage/ai-usage/types.d.ts +33 -0
  686. package/dist/storage/ai-usage/types.d.ts.map +1 -1
  687. package/dist/storage/ai-usage/usage.d.ts +2 -0
  688. package/dist/storage/ai-usage/usage.d.ts.map +1 -1
  689. package/dist/storage/artifacts/errors.d.ts +12 -2
  690. package/dist/storage/artifacts/errors.d.ts.map +1 -1
  691. package/dist/storage/artifacts/in-memory.d.ts +23 -2
  692. package/dist/storage/artifacts/in-memory.d.ts.map +1 -1
  693. package/dist/storage/artifacts/index.d.ts +2 -2
  694. package/dist/storage/artifacts/index.d.ts.map +1 -1
  695. package/dist/storage/artifacts/record.d.ts +19 -2
  696. package/dist/storage/artifacts/record.d.ts.map +1 -1
  697. package/dist/storage/artifacts/types.d.ts +87 -8
  698. package/dist/storage/artifacts/types.d.ts.map +1 -1
  699. package/dist/storage/auth/in-memory/auth-storage.d.ts +3 -2
  700. package/dist/storage/auth/in-memory/auth-storage.d.ts.map +1 -1
  701. package/dist/storage/auth/in-memory/users.d.ts +7 -3
  702. package/dist/storage/auth/in-memory/users.d.ts.map +1 -1
  703. package/dist/storage/auth/index.d.ts +1 -1
  704. package/dist/storage/auth/index.d.ts.map +1 -1
  705. package/dist/storage/auth/types.d.ts +40 -9
  706. package/dist/storage/auth/types.d.ts.map +1 -1
  707. package/dist/storage/connector-connections/provider.js +1 -1
  708. package/dist/storage/executions/in-memory.d.ts +2 -1
  709. package/dist/storage/executions/in-memory.d.ts.map +1 -1
  710. package/dist/storage/executions/index.d.ts +1 -1
  711. package/dist/storage/executions/index.d.ts.map +1 -1
  712. package/dist/storage/executions/types.d.ts +15 -0
  713. package/dist/storage/executions/types.d.ts.map +1 -1
  714. package/dist/storage/file-upload-sessions/provider.js +15 -12
  715. package/dist/storage/file-upload-sessions/provider.js.map +1 -1
  716. package/dist/storage/index.d.ts +13 -11
  717. package/dist/storage/index.d.ts.map +1 -1
  718. package/dist/storage/index.js +50 -39
  719. package/dist/storage/index.js.map +1 -1
  720. package/dist/storage/internal.d.ts +2 -2
  721. package/dist/storage/internal.d.ts.map +1 -1
  722. package/dist/storage/internal.js +19 -8
  723. package/dist/storage/internal.js.map +1 -1
  724. package/dist/storage/migrations/migrate-storage.d.ts +4 -1
  725. package/dist/storage/migrations/migrate-storage.d.ts.map +1 -1
  726. package/dist/storage/migrations/prepare-unique-properties.d.ts +18 -0
  727. package/dist/storage/migrations/prepare-unique-properties.d.ts.map +1 -0
  728. package/dist/storage/objects/guard.d.ts +1 -1
  729. package/dist/storage/objects/guard.d.ts.map +1 -1
  730. package/dist/storage/objects/in-memory/conditional-reader.d.ts +5 -0
  731. package/dist/storage/objects/in-memory/conditional-reader.d.ts.map +1 -0
  732. package/dist/storage/objects/in-memory/query.d.ts.map +1 -1
  733. package/dist/storage/objects/in-memory/read-scope.d.ts +3 -9
  734. package/dist/storage/objects/in-memory/read-scope.d.ts.map +1 -1
  735. package/dist/storage/objects/in-memory/read-source.d.ts +10 -1
  736. package/dist/storage/objects/in-memory/read-source.d.ts.map +1 -1
  737. package/dist/storage/objects/in-memory/scoped-reader.d.ts +14 -0
  738. package/dist/storage/objects/in-memory/scoped-reader.d.ts.map +1 -0
  739. package/dist/storage/objects/in-memory/selected-reader.d.ts.map +1 -1
  740. package/dist/storage/objects/in-memory/storage.d.ts +36 -1
  741. package/dist/storage/objects/in-memory/storage.d.ts.map +1 -1
  742. package/dist/storage/objects/index.d.ts +2 -2
  743. package/dist/storage/objects/index.d.ts.map +1 -1
  744. package/dist/storage/objects/read-scope.d.ts +9 -1
  745. package/dist/storage/objects/read-scope.d.ts.map +1 -1
  746. package/dist/storage/objects/types.d.ts +64 -1
  747. package/dist/storage/objects/types.d.ts.map +1 -1
  748. package/dist/storage/ontology/in-memory/index.d.ts +2 -0
  749. package/dist/storage/ontology/in-memory/index.d.ts.map +1 -1
  750. package/dist/storage/ontology/in-memory/materializations.d.ts +1 -0
  751. package/dist/storage/ontology/in-memory/materializations.d.ts.map +1 -1
  752. package/dist/storage/ontology/in-memory/replacement-plans.d.ts.map +1 -1
  753. package/dist/storage/ontology/in-memory/unique-values.d.ts +32 -0
  754. package/dist/storage/ontology/in-memory/unique-values.d.ts.map +1 -0
  755. package/dist/storage/ontology/index.d.ts +4 -1
  756. package/dist/storage/ontology/index.d.ts.map +1 -1
  757. package/dist/storage/ontology/materializations.d.ts +34 -1
  758. package/dist/storage/ontology/materializations.d.ts.map +1 -1
  759. package/dist/storage/ontology/provider-work.d.ts +15 -2
  760. package/dist/storage/ontology/provider-work.d.ts.map +1 -1
  761. package/dist/storage/ontology/provider.d.ts +1 -1
  762. package/dist/storage/ontology/provider.d.ts.map +1 -1
  763. package/dist/storage/ontology/provider.js +9 -4
  764. package/dist/storage/ontology/provider.js.map +1 -1
  765. package/dist/storage/ontology/unique-values.d.ts +54 -0
  766. package/dist/storage/ontology/unique-values.d.ts.map +1 -0
  767. package/dist/storage/operation-scope.d.ts +1 -1
  768. package/dist/storage/operation-scope.d.ts.map +1 -1
  769. package/dist/storage/operation-scope.js +1 -1
  770. package/dist/storage/projection-runs/in-memory.d.ts +0 -6
  771. package/dist/storage/projection-runs/in-memory.d.ts.map +1 -1
  772. package/dist/storage/projection-runs/provider.js +2 -2
  773. package/dist/storage/share-grants/provider.js +4 -3
  774. package/dist/storage/share-grants/provider.js.map +1 -1
  775. package/dist/storage/types.d.ts +2 -2
  776. package/dist/storage/types.d.ts.map +1 -1
  777. package/dist/storage/workflow-runs/provider.js +15 -12
  778. package/dist/storage/workflow-runs/provider.js.map +1 -1
  779. package/dist/syncs/index.js +42 -39
  780. package/dist/syncs/index.js.map +1 -1
  781. package/dist/testing/agent-approval-storage-contract.d.ts +17 -0
  782. package/dist/testing/agent-approval-storage-contract.d.ts.map +1 -0
  783. package/dist/testing/agent-memory-storage-contract.d.ts +12 -0
  784. package/dist/testing/agent-memory-storage-contract.d.ts.map +1 -0
  785. package/dist/testing/agent-storage-contract.d.ts.map +1 -1
  786. package/dist/testing/ai-cost-storage-contract.d.ts.map +1 -1
  787. package/dist/testing/ai-limit-storage-contract.d.ts +0 -1
  788. package/dist/testing/ai-limit-storage-contract.d.ts.map +1 -1
  789. package/dist/testing/ai-model-call-groups-contract.d.ts.map +1 -1
  790. package/dist/testing/ai-usage-storage-contract.d.ts.map +1 -1
  791. package/dist/testing/artifact-storage-contract.d.ts.map +1 -1
  792. package/dist/testing/auth-storage-contract.d.ts +13 -0
  793. package/dist/testing/auth-storage-contract.d.ts.map +1 -1
  794. package/dist/testing/broker-contract.d.ts +5 -0
  795. package/dist/testing/broker-contract.d.ts.map +1 -1
  796. package/dist/testing/effective-storage-contract.d.ts.map +1 -1
  797. package/dist/testing/execution-storage-contract.d.ts.map +1 -1
  798. package/dist/testing/file-upload-session-storage-contract.d.ts.map +1 -1
  799. package/dist/testing/index.d.ts +9 -5
  800. package/dist/testing/index.d.ts.map +1 -1
  801. package/dist/testing/index.js +7938 -3743
  802. package/dist/testing/index.js.map +29 -25
  803. package/dist/testing/lake-storage-contract.d.ts.map +1 -1
  804. package/dist/testing/materializer-storage-contract.d.ts.map +1 -1
  805. package/dist/testing/object-conditional-read-scope-contract.d.ts +11 -0
  806. package/dist/testing/object-conditional-read-scope-contract.d.ts.map +1 -0
  807. package/dist/testing/object-query-contract.d.ts +0 -2
  808. package/dist/testing/object-query-contract.d.ts.map +1 -1
  809. package/dist/testing/ontology-storage-contract.d.ts.map +1 -1
  810. package/dist/testing/projection-run-storage-contract.d.ts.map +1 -1
  811. package/dist/testing/queues-contract.d.ts +5 -0
  812. package/dist/testing/queues-contract.d.ts.map +1 -1
  813. package/dist/testing/sandboxes-contract.d.ts.map +1 -1
  814. package/dist/testing/share-grant-storage-contract.d.ts.map +1 -1
  815. package/dist/testing/share-session-storage-contract.d.ts.map +1 -1
  816. package/dist/testing/unique-values-contract.d.ts +21 -0
  817. package/dist/testing/unique-values-contract.d.ts.map +1 -0
  818. package/dist/testing/webhook-execution.d.ts +0 -8
  819. package/dist/testing/webhook-execution.d.ts.map +1 -1
  820. package/dist/testing/webhook-run-storage-contract.d.ts.map +1 -1
  821. package/dist/users/execution.d.ts +40 -0
  822. package/dist/users/execution.d.ts.map +1 -0
  823. package/dist/users/index.d.ts +3 -0
  824. package/dist/users/index.d.ts.map +1 -0
  825. package/dist/webhooks/internal.js +34 -31
  826. package/dist/webhooks/internal.js.map +2 -2
  827. package/dist/workers/index.js +4 -6
  828. package/dist/workers/index.js.map +4 -4
  829. package/dist/workers/queue-worker.d.ts +0 -2
  830. package/dist/workers/queue-worker.d.ts.map +1 -1
  831. package/dist/workers/worker.d.ts +0 -2
  832. package/dist/workers/worker.d.ts.map +1 -1
  833. package/dist/workflows/builders.d.ts.map +1 -1
  834. package/dist/workflows/index.js +67 -63
  835. package/dist/workflows/index.js.map +1 -1
  836. package/dist/workflows/request.d.ts +12 -1
  837. package/dist/workflows/request.d.ts.map +1 -1
  838. package/dist/workflows/types.d.ts +6 -2
  839. package/dist/workflows/types.d.ts.map +1 -1
  840. package/dist/workflows/validation.d.ts.map +1 -1
  841. package/package.json +1 -1
  842. package/src/actions/commit-edits.ts +6 -1
  843. package/src/actions/execution.ts +42 -15
  844. package/src/actions/read-facade.ts +33 -0
  845. package/src/actions/request.ts +224 -71
  846. package/src/actions/run/context.ts +47 -1
  847. package/src/actions/run/execute.ts +13 -6
  848. package/src/actions/run/executor.ts +11 -2
  849. package/src/actions/run/normalize.ts +12 -2
  850. package/src/actions/run/phases.ts +2 -0
  851. package/src/actions/run/run-action.ts +12 -3
  852. package/src/actions/run/signals.ts +3 -9
  853. package/src/actions/run/types.ts +17 -1
  854. package/src/actions/run-authorization.ts +72 -0
  855. package/src/actions/types/context.ts +20 -3
  856. package/src/actions/validators.ts +19 -8
  857. package/src/activity/README.md +5 -2
  858. package/src/activity/timeline.ts +39 -78
  859. package/src/agents/accounting.ts +59 -0
  860. package/src/agents/adapters.ts +10 -0
  861. package/src/agents/agent-mail.ts +29 -0
  862. package/src/agents/api-gateway.ts +14 -3
  863. package/src/agents/approval-continuation.ts +48 -0
  864. package/src/agents/approval-executor.ts +318 -0
  865. package/src/agents/approval-outcome.ts +59 -0
  866. package/src/agents/approvals.ts +566 -0
  867. package/src/agents/authority.ts +24 -1
  868. package/src/agents/builders.ts +5 -3
  869. package/src/agents/cancel.ts +103 -0
  870. package/src/agents/child-question.ts +46 -0
  871. package/src/agents/children.ts +404 -0
  872. package/src/agents/context-compaction.ts +12 -0
  873. package/src/agents/errors.ts +31 -0
  874. package/src/agents/execution.ts +788 -90
  875. package/src/agents/fork.ts +158 -0
  876. package/src/agents/ids.ts +18 -6
  877. package/src/agents/index.ts +55 -0
  878. package/src/agents/memory-execution.ts +186 -0
  879. package/src/agents/memory.ts +178 -0
  880. package/src/agents/message.ts +57 -0
  881. package/src/agents/model-loop.ts +93 -6
  882. package/src/agents/model-routing.ts +193 -0
  883. package/src/agents/participants.ts +213 -0
  884. package/src/agents/reference.ts +2 -0
  885. package/src/agents/request.ts +398 -69
  886. package/src/agents/run-scope.ts +134 -0
  887. package/src/agents/streams/index.ts +5 -0
  888. package/src/agents/streams/internal.ts +1 -0
  889. package/src/agents/streams/protocol.ts +385 -7
  890. package/src/agents/subagent-runs.ts +41 -0
  891. package/src/agents/thread-access.ts +137 -0
  892. package/src/agents/tool-definition.ts +5 -3
  893. package/src/agents/types.ts +35 -10
  894. package/src/agents/validation.ts +2 -0
  895. package/src/artifacts/access.ts +125 -0
  896. package/src/artifacts/canvas.ts +369 -0
  897. package/src/artifacts/csv.ts +10 -0
  898. package/src/artifacts/errors.ts +12 -1
  899. package/src/artifacts/execution.ts +436 -36
  900. package/src/artifacts/formula/check.ts +171 -0
  901. package/src/artifacts/formula/evaluate.ts +288 -0
  902. package/src/artifacts/formula/index.ts +199 -0
  903. package/src/artifacts/formula/parser.ts +357 -0
  904. package/src/artifacts/frames/assets.ts +35 -19
  905. package/src/artifacts/frames/entries.ts +35 -0
  906. package/src/artifacts/frames/grants.ts +10 -9
  907. package/src/artifacts/frames/index.ts +8 -2
  908. package/src/artifacts/frames/kit.ts +191 -14
  909. package/src/artifacts/frames/probe.ts +66 -18
  910. package/src/artifacts/frames/protocol.ts +164 -10
  911. package/src/artifacts/frames/runtime.ts +273 -28
  912. package/src/artifacts/index.ts +66 -2
  913. package/src/artifacts/kinds.ts +1 -1
  914. package/src/artifacts/limits.ts +31 -0
  915. package/src/artifacts/live-sheet.ts +345 -0
  916. package/src/artifacts/outline.ts +34 -1
  917. package/src/artifacts/publish/index.ts +2 -0
  918. package/src/artifacts/publish/publish.ts +120 -34
  919. package/src/artifacts/publish/queries.ts +336 -0
  920. package/src/artifacts/publish/references.ts +18 -13
  921. package/src/artifacts/publish/validate/canvas.ts +118 -0
  922. package/src/artifacts/publish/validate/html.ts +78 -0
  923. package/src/artifacts/publish/validate/page.ts +65 -0
  924. package/src/artifacts/publish/validate/sheet.ts +115 -69
  925. package/src/artifacts/publish/validate/slides.ts +11 -63
  926. package/src/artifacts/queries.ts +512 -0
  927. package/src/artifacts/resolve.ts +20 -5
  928. package/src/artifacts/run-query.ts +212 -0
  929. package/src/artifacts/serialize-query.ts +25 -0
  930. package/src/artifacts/sheet-rules.ts +180 -0
  931. package/src/artifacts/tones.ts +20 -0
  932. package/src/artifacts/workbook.ts +374 -15
  933. package/src/auth/index.ts +4 -0
  934. package/src/auth/member-events.ts +114 -0
  935. package/src/auth/profile.ts +118 -0
  936. package/src/auth/runtime.ts +190 -9
  937. package/src/auth/strategy.ts +3 -0
  938. package/src/auth/types.ts +32 -0
  939. package/src/authorization/decision.ts +47 -0
  940. package/src/authorization/event-visibility.ts +17 -16
  941. package/src/authorization/grant-kinds.ts +32 -0
  942. package/src/authorization/index.ts +6 -1
  943. package/src/authorization/resolve.ts +58 -1
  944. package/src/authorization/run-visibility.ts +8 -1
  945. package/src/authorization/types.ts +14 -0
  946. package/src/errors/catalog.ts +26 -1
  947. package/src/errors/internal.ts +17 -8
  948. package/src/events/definitions.ts +26 -0
  949. package/src/events/execution.ts +43 -6
  950. package/src/events/index.ts +10 -1
  951. package/src/events/scope.ts +2 -0
  952. package/src/events/selectors/builder.ts +50 -0
  953. package/src/events/selectors/index.ts +4 -0
  954. package/src/events/selectors/types.ts +32 -1
  955. package/src/events/service.ts +55 -2
  956. package/src/events/types/index.ts +10 -0
  957. package/src/events/types/users.ts +73 -0
  958. package/src/events/view-conditions.ts +241 -0
  959. package/src/execution/agent.ts +25 -0
  960. package/src/execution/authorization.ts +70 -0
  961. package/src/execution/authorized-object-reader.ts +238 -32
  962. package/src/execution/lineage.ts +14 -0
  963. package/src/execution/object-reader-ontology.ts +11 -14
  964. package/src/execution/object-reader-security.ts +134 -10
  965. package/src/execution/object-reader-users.ts +122 -0
  966. package/src/execution/preparation.ts +78 -0
  967. package/src/execution/request.ts +2 -0
  968. package/src/execution/unique-lookup.ts +55 -0
  969. package/src/execution/visible-objects.ts +26 -0
  970. package/src/http/api-routes.ts +206 -7
  971. package/src/index.ts +99 -2
  972. package/src/materialization/errors.ts +37 -0
  973. package/src/materialization/event-envelopes.ts +11 -3
  974. package/src/materialization/index.ts +1 -0
  975. package/src/materialization/model.ts +24 -4
  976. package/src/materializer/README.md +7 -1
  977. package/src/materializer/edits/commit.ts +56 -12
  978. package/src/materializer/edits/load-state.ts +15 -7
  979. package/src/materializer/edits/operations.ts +12 -0
  980. package/src/materializer/edits/plan.ts +2 -0
  981. package/src/materializer/edits/unique-values.ts +255 -0
  982. package/src/materializer/edits/working-state.ts +8 -1
  983. package/src/materializer/execution/work-records.ts +47 -0
  984. package/src/materializer/projections/finish-run.ts +0 -1
  985. package/src/materializer/projections/replace.ts +1 -1
  986. package/src/materializer/projections/replacement-plan.ts +4 -1
  987. package/src/materializer/projections/source-materialization.ts +2 -1
  988. package/src/materializer/shared/normalize.ts +37 -6
  989. package/src/materializer/shared/projection-run.ts +1 -2
  990. package/src/materializer/telemetry/append.ts +14 -17
  991. package/src/materializer/telemetry/plan.ts +2 -0
  992. package/src/models/audio/catalog.ts +89 -10
  993. package/src/models/audio/errors.ts +18 -1
  994. package/src/models/audio/runtime.ts +10 -13
  995. package/src/models/audio/speech.ts +261 -0
  996. package/src/models/audio/types.ts +97 -0
  997. package/src/models/calls.ts +100 -0
  998. package/src/models/catalog-index.ts +21 -2
  999. package/src/models/catalog.ts +211 -35
  1000. package/src/models/decision/runtime.ts +21 -22
  1001. package/src/models/decision/validation.ts +4 -1
  1002. package/src/models/definitions.ts +57 -8
  1003. package/src/models/events.ts +72 -1
  1004. package/src/models/execution/README.md +34 -5
  1005. package/src/models/execution/binding.ts +3 -1
  1006. package/src/models/execution/embedding.ts +1 -0
  1007. package/src/models/execution/index.ts +5 -0
  1008. package/src/models/execution/model-call-accounting.ts +3 -1
  1009. package/src/models/execution/model-call-recorder.ts +29 -1
  1010. package/src/models/execution/usage.ts +8 -0
  1011. package/src/models/execution.ts +20 -22
  1012. package/src/models/generation-types.ts +8 -1
  1013. package/src/models/image/catalog.ts +89 -0
  1014. package/src/models/image/errors.ts +19 -0
  1015. package/src/models/image/runtime.ts +335 -0
  1016. package/src/models/image/types.ts +111 -0
  1017. package/src/models/index.ts +38 -4
  1018. package/src/models/{audio/file.ts → input-file.ts} +22 -13
  1019. package/src/models/language-model.ts +13 -0
  1020. package/src/models/pricing.ts +263 -42
  1021. package/src/models/rate-card.ts +161 -12
  1022. package/src/objects/authorized-ontology-view.ts +1 -0
  1023. package/src/objects/conditional-writes.ts +109 -0
  1024. package/src/objects/execution.ts +4 -0
  1025. package/src/objects/index.ts +8 -0
  1026. package/src/objects/link/authorization.ts +12 -3
  1027. package/src/objects/link/endpoints.ts +42 -11
  1028. package/src/objects/link/remove.ts +25 -10
  1029. package/src/objects/link/upsert-batch.ts +2 -0
  1030. package/src/objects/link/upsert.ts +18 -12
  1031. package/src/objects/materializer-adapter.ts +55 -18
  1032. package/src/objects/object/delete.ts +24 -7
  1033. package/src/objects/object/upsert-batch.ts +44 -14
  1034. package/src/objects/object/upsert.ts +23 -5
  1035. package/src/objects/query/current-user.ts +76 -0
  1036. package/src/objects/query/executor.ts +39 -103
  1037. package/src/objects/query/explain.ts +20 -7
  1038. package/src/objects/query/index.ts +2 -0
  1039. package/src/objects/query/ir.ts +20 -0
  1040. package/src/objects/query/links.ts +8 -0
  1041. package/src/objects/query/matches-predicate.ts +108 -0
  1042. package/src/objects/query/normalize.ts +50 -19
  1043. package/src/objects/query/scalar-values.ts +19 -3
  1044. package/src/objects/query/user-expansions.ts +65 -0
  1045. package/src/objects/query/validate.ts +248 -10
  1046. package/src/objects/runtime-batch.ts +8 -2
  1047. package/src/objects/sdk/object-set.ts +12 -1
  1048. package/src/objects/sdk/query-builder.ts +39 -8
  1049. package/src/objects/sdk/query-executor.ts +6 -0
  1050. package/src/objects/serialize.ts +79 -0
  1051. package/src/objects/unique-violation.ts +59 -0
  1052. package/src/objects/vectors/handle.ts +3 -3
  1053. package/src/ontology/builders.ts +3 -0
  1054. package/src/ontology/docs-markdown.ts +1 -0
  1055. package/src/ontology/index.ts +2 -2
  1056. package/src/ontology/json-schema.ts +4 -0
  1057. package/src/ontology/primitives.ts +21 -8
  1058. package/src/ontology/registry.ts +16 -0
  1059. package/src/ontology/types.ts +9 -0
  1060. package/src/ontology/unique-values.ts +84 -0
  1061. package/src/ontology/user-ref.ts +39 -0
  1062. package/src/ontology/validation/properties.ts +43 -0
  1063. package/src/ontology/validation/schema.ts +9 -1
  1064. package/src/projections/registry.ts +16 -10
  1065. package/src/projections/revision.ts +112 -45
  1066. package/src/projections/run-dispatch.ts +38 -25
  1067. package/src/projections/types.ts +2 -0
  1068. package/src/query.ts +5 -0
  1069. package/src/rules/execution.ts +43 -11
  1070. package/src/runtime/ai-cost.ts +30 -0
  1071. package/src/runtime/ai-usage.ts +32 -1
  1072. package/src/runtime/host.ts +18 -1
  1073. package/src/runtime/index.ts +2 -0
  1074. package/src/runtime/resolve-definitions.ts +3 -0
  1075. package/src/runtime/sixb.ts +35 -8
  1076. package/src/runtime/types.ts +99 -9
  1077. package/src/schedules/builders.ts +3 -1
  1078. package/src/schedules/runtime.ts +6 -0
  1079. package/src/schedules/validation.ts +23 -1
  1080. package/src/security/README.md +62 -0
  1081. package/src/security/grants.ts +155 -10
  1082. package/src/security/index.ts +3 -1
  1083. package/src/security/project.ts +6 -1
  1084. package/src/security/registry.ts +32 -7
  1085. package/src/security/types.ts +54 -9
  1086. package/src/security/validation.ts +27 -11
  1087. package/src/security/view-conditions.ts +215 -0
  1088. package/src/shares/execution.ts +43 -10
  1089. package/src/storage/action-runs/types.ts +2 -0
  1090. package/src/storage/agents/errors.ts +3 -0
  1091. package/src/storage/agents/in-memory.ts +779 -32
  1092. package/src/storage/agents/index.ts +42 -0
  1093. package/src/storage/agents/provider.ts +733 -8
  1094. package/src/storage/agents/types.ts +620 -12
  1095. package/src/storage/ai-cost/analytics.ts +60 -7
  1096. package/src/storage/ai-cost/codec.ts +6 -1
  1097. package/src/storage/ai-cost/groups.ts +44 -1
  1098. package/src/storage/ai-cost/index.ts +1 -0
  1099. package/src/storage/ai-cost/provider.ts +2 -0
  1100. package/src/storage/ai-cost/types.ts +18 -1
  1101. package/src/storage/ai-cost/validation.ts +39 -12
  1102. package/src/storage/ai-limits/provider.ts +4 -7
  1103. package/src/storage/ai-usage/in-memory.ts +28 -1
  1104. package/src/storage/ai-usage/index.ts +9 -1
  1105. package/src/storage/ai-usage/record.ts +44 -7
  1106. package/src/storage/ai-usage/types.ts +38 -0
  1107. package/src/storage/ai-usage/usage.ts +15 -1
  1108. package/src/storage/artifacts/errors.ts +13 -1
  1109. package/src/storage/artifacts/in-memory.ts +156 -8
  1110. package/src/storage/artifacts/index.ts +6 -1
  1111. package/src/storage/artifacts/record.ts +61 -1
  1112. package/src/storage/artifacts/types.ts +92 -8
  1113. package/src/storage/auth/in-memory/auth-storage.ts +27 -2
  1114. package/src/storage/auth/in-memory/users.ts +40 -6
  1115. package/src/storage/auth/index.ts +1 -0
  1116. package/src/storage/auth/types.ts +43 -7
  1117. package/src/storage/executions/in-memory.ts +32 -0
  1118. package/src/storage/executions/index.ts +2 -0
  1119. package/src/storage/executions/types.ts +17 -0
  1120. package/src/storage/index.ts +69 -1
  1121. package/src/storage/internal.ts +9 -1
  1122. package/src/storage/migrations/migrate-storage.ts +8 -1
  1123. package/src/storage/migrations/prepare-unique-properties.ts +161 -0
  1124. package/src/storage/objects/guard.ts +7 -3
  1125. package/src/storage/objects/in-memory/conditional-reader.ts +72 -0
  1126. package/src/storage/objects/in-memory/query.ts +4 -105
  1127. package/src/storage/objects/in-memory/read-scope.ts +15 -14
  1128. package/src/storage/objects/in-memory/read-source.ts +11 -1
  1129. package/src/storage/objects/in-memory/scoped-reader.ts +243 -0
  1130. package/src/storage/objects/in-memory/selected-reader.ts +6 -231
  1131. package/src/storage/objects/in-memory/storage.ts +183 -1
  1132. package/src/storage/objects/index.ts +9 -1
  1133. package/src/storage/objects/read-scope.ts +191 -0
  1134. package/src/storage/objects/types.ts +68 -1
  1135. package/src/storage/ontology/in-memory/index.ts +3 -0
  1136. package/src/storage/ontology/in-memory/materializations.ts +35 -0
  1137. package/src/storage/ontology/in-memory/replacement-plans.ts +4 -0
  1138. package/src/storage/ontology/in-memory/unique-values.ts +62 -0
  1139. package/src/storage/ontology/index.ts +10 -0
  1140. package/src/storage/ontology/materializations.ts +35 -1
  1141. package/src/storage/ontology/provider-work.ts +76 -0
  1142. package/src/storage/ontology/provider.ts +3 -0
  1143. package/src/storage/ontology/unique-values.ts +56 -0
  1144. package/src/storage/operation-scope.ts +9 -1
  1145. package/src/storage/projection-runs/in-memory.ts +3 -35
  1146. package/src/storage/types.ts +2 -0
  1147. package/src/testing/agent-approval-storage-contract.ts +1117 -0
  1148. package/src/testing/agent-memory-storage-contract.ts +400 -0
  1149. package/src/testing/agent-storage-contract.ts +1188 -33
  1150. package/src/testing/ai-cost-storage-contract.ts +31 -1
  1151. package/src/testing/ai-limit-storage-contract.ts +9 -7
  1152. package/src/testing/ai-model-call-groups-contract.ts +76 -0
  1153. package/src/testing/ai-usage-storage-contract.ts +120 -13
  1154. package/src/testing/artifact-storage-contract.ts +338 -4
  1155. package/src/testing/auth-storage-contract.ts +550 -73
  1156. package/src/testing/broker-contract.ts +28 -23
  1157. package/src/testing/effective-storage-contract.ts +3 -8
  1158. package/src/testing/execution-storage-contract.ts +53 -0
  1159. package/src/testing/file-upload-session-storage-contract.ts +12 -24
  1160. package/src/testing/index.ts +17 -4
  1161. package/src/testing/lake-storage-contract.ts +22 -28
  1162. package/src/testing/materializer-storage-contract.ts +36 -9
  1163. package/src/testing/object-conditional-read-scope-contract.ts +634 -0
  1164. package/src/testing/object-query-contract.ts +386 -186
  1165. package/src/testing/ontology-storage-contract.ts +230 -21
  1166. package/src/testing/projection-run-storage-contract.ts +8 -18
  1167. package/src/testing/queues-contract.ts +39 -70
  1168. package/src/testing/sandboxes-contract.ts +3 -14
  1169. package/src/testing/share-grant-storage-contract.ts +13 -16
  1170. package/src/testing/share-session-storage-contract.ts +4 -14
  1171. package/src/testing/unique-values-contract.ts +907 -0
  1172. package/src/testing/webhook-execution.ts +1 -1
  1173. package/src/testing/webhook-run-storage-contract.ts +6 -9
  1174. package/src/users/execution.ts +131 -0
  1175. package/src/users/index.ts +2 -0
  1176. package/src/workers/queue-worker.ts +1 -3
  1177. package/src/workers/worker.ts +1 -3
  1178. package/src/workflows/builders.ts +6 -0
  1179. package/src/workflows/request.ts +46 -8
  1180. package/src/workflows/types.ts +6 -2
  1181. package/src/workflows/validation.ts +23 -9
  1182. package/dist/chunk-29yx306f.js.map +0 -22
  1183. package/dist/chunk-3jms7je7.js +0 -14
  1184. package/dist/chunk-3jms7je7.js.map +0 -10
  1185. package/dist/chunk-3qct2mdc.js +0 -297
  1186. package/dist/chunk-3qct2mdc.js.map +0 -12
  1187. package/dist/chunk-48qjhh6v.js.map +0 -13
  1188. package/dist/chunk-4as3wt1c.js.map +0 -12
  1189. package/dist/chunk-5948n82c.js.map +0 -10
  1190. package/dist/chunk-5hx48dnn.js.map +0 -14
  1191. package/dist/chunk-6rqgmkde.js.map +0 -29
  1192. package/dist/chunk-6x0pqh32.js.map +0 -10
  1193. package/dist/chunk-7n30ybym.js +0 -3
  1194. package/dist/chunk-7n440zgt.js +0 -261
  1195. package/dist/chunk-7n440zgt.js.map +0 -12
  1196. package/dist/chunk-7q8t23v4.js +0 -467
  1197. package/dist/chunk-7q8t23v4.js.map +0 -14
  1198. package/dist/chunk-8frc8a4j.js.map +0 -20
  1199. package/dist/chunk-918wwnaa.js.map +0 -68
  1200. package/dist/chunk-91mg3nj9.js.map +0 -12
  1201. package/dist/chunk-96yw3pwd.js.map +0 -10
  1202. package/dist/chunk-9j4jw7as.js.map +0 -14
  1203. package/dist/chunk-9k93ah50.js.map +0 -11
  1204. package/dist/chunk-9kgkfg6v.js +0 -502
  1205. package/dist/chunk-9kgkfg6v.js.map +0 -14
  1206. package/dist/chunk-akzryx9h.js.map +0 -100
  1207. package/dist/chunk-arns890k.js.map +0 -10
  1208. package/dist/chunk-bk9svbcq.js.map +0 -49
  1209. package/dist/chunk-c06hmxyy.js +0 -31
  1210. package/dist/chunk-c06hmxyy.js.map +0 -10
  1211. package/dist/chunk-c1rxbz5y.js.map +0 -12
  1212. package/dist/chunk-cn0fwwhy.js.map +0 -19
  1213. package/dist/chunk-dhcv7yxc.js.map +0 -11
  1214. package/dist/chunk-dhdha526.js.map +0 -10
  1215. package/dist/chunk-dvd2fp9q.js.map +0 -13
  1216. package/dist/chunk-e6k4thh5.js.map +0 -19
  1217. package/dist/chunk-ere85b8y.js.map +0 -15
  1218. package/dist/chunk-g257jwnc.js.map +0 -12
  1219. package/dist/chunk-hwksyjks.js.map +0 -11
  1220. package/dist/chunk-k43ct2ke.js.map +0 -12
  1221. package/dist/chunk-nn5xnx3s.js.map +0 -40
  1222. package/dist/chunk-pbcbn83d.js.map +0 -14
  1223. package/dist/chunk-pqajwytd.js +0 -68
  1224. package/dist/chunk-pqajwytd.js.map +0 -11
  1225. package/dist/chunk-qczk96d9.js.map +0 -11
  1226. package/dist/chunk-rdghfsss.js +0 -39
  1227. package/dist/chunk-rdghfsss.js.map +0 -10
  1228. package/dist/chunk-rj69qcrd.js.map +0 -11
  1229. package/dist/chunk-v4jbb3rs.js.map +0 -10
  1230. package/dist/chunk-yxd3nnqt.js.map +0 -11
  1231. package/dist/events/toStoredEvent.d.ts +0 -9
  1232. package/dist/events/toStoredEvent.d.ts.map +0 -1
  1233. package/dist/models/audio/file.d.ts +0 -9
  1234. package/dist/models/audio/file.d.ts.map +0 -1
  1235. package/src/events/toStoredEvent.ts +0 -33
  1236. /package/dist/{chunk-mfs23znk.js.map → chunk-07kkp2e1.js.map} +0 -0
  1237. /package/dist/{chunk-z58tm0hm.js.map → chunk-0phpbbvm.js.map} +0 -0
  1238. /package/dist/{chunk-e17zdm62.js.map → chunk-1t6k1avb.js.map} +0 -0
  1239. /package/dist/{chunk-kge7k6ey.js.map → chunk-2fn60nvs.js.map} +0 -0
  1240. /package/dist/{chunk-y0c4e6ex.js.map → chunk-3gbefjg5.js.map} +0 -0
  1241. /package/dist/{chunk-cy4mbddw.js.map → chunk-48jezz3j.js.map} +0 -0
  1242. /package/dist/{chunk-twe4dx8p.js → chunk-5tfev0fv.js} +0 -0
  1243. /package/dist/{chunk-twe4dx8p.js.map → chunk-5tfev0fv.js.map} +0 -0
  1244. /package/dist/{chunk-447a5c0p.js.map → chunk-6n69k945.js.map} +0 -0
  1245. /package/dist/{chunk-0bphap9y.js.map → chunk-6p0pastb.js.map} +0 -0
  1246. /package/dist/{chunk-431pyp2c.js.map → chunk-6y0mkhex.js.map} +0 -0
  1247. /package/dist/{chunk-s7jg7pmn.js.map → chunk-bab05bhg.js.map} +0 -0
  1248. /package/dist/{chunk-q5e5tv4b.js.map → chunk-c844dkwd.js.map} +0 -0
  1249. /package/dist/{chunk-cfj9dfbb.js.map → chunk-d2m879s4.js.map} +0 -0
  1250. /package/dist/{chunk-q7gn29y3.js.map → chunk-dp0cdtj2.js.map} +0 -0
  1251. /package/dist/{chunk-br3k6qbf.js.map → chunk-fm62y49k.js.map} +0 -0
  1252. /package/dist/{chunk-vvxtn22d.js.map → chunk-g663fahq.js.map} +0 -0
  1253. /package/dist/{chunk-rmakanzx.js.map → chunk-h33shhq6.js.map} +0 -0
  1254. /package/dist/{chunk-d09e3rax.js.map → chunk-hwarjrgf.js.map} +0 -0
  1255. /package/dist/{chunk-vf57cr4t.js.map → chunk-hyesv9dv.js.map} +0 -0
  1256. /package/dist/{chunk-5vems3nx.js.map → chunk-m2nevja0.js.map} +0 -0
  1257. /package/dist/{chunk-x9v4cx1d.js.map → chunk-m36fw8ft.js.map} +0 -0
  1258. /package/dist/{chunk-a40ad1ft.js.map → chunk-mbsbxarb.js.map} +0 -0
  1259. /package/dist/{chunk-6aawea28.js.map → chunk-n8q5j6y5.js.map} +0 -0
  1260. /package/dist/{chunk-d7dnxdep.js.map → chunk-n9zpx9c6.js.map} +0 -0
  1261. /package/dist/{chunk-xvsc5m8n.js.map → chunk-npcr0228.js.map} +0 -0
  1262. /package/dist/{chunk-y5tah2kf.js.map → chunk-q4pmvkg0.js.map} +0 -0
  1263. /package/dist/{chunk-d5rjr8c0.js.map → chunk-vabga7fk.js.map} +0 -0
@@ -0,0 +1,120 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/models/execution/binding.ts", "../src/actions/descriptor.ts", "../src/shared/params/user-refs.ts", "../src/actions/delegated-admission.ts", "../src/actions/run-persistence.ts", "../src/actions/run-id.ts", "../src/execution/primitive.ts", "../src/actions/read-facade.ts", "../src/actions/run/context.ts", "../src/objects/unique-violation.ts", "../src/actions/run/signals.ts", "../src/actions/run/normalize.ts", "../src/actions/run/effects.ts", "../src/actions/validators.ts", "../src/edits/recorder.ts", "../src/edits/properties.ts", "../src/actions/commit-edits.ts", "../src/actions/run/edits-commit.ts", "../src/actions/run/writeback.ts", "../src/actions/run/phases.ts", "../src/actions/run/state.ts", "../src/actions/run/run-action.ts", "../src/actions/run/execute.ts", "../src/actions/run/executor.ts", "../src/actions/request.ts", "../src/actions/execution.ts", "../src/runtime/ai-usage.ts", "../src/agents/accounting.ts", "../src/agents/approval-continuation.ts", "../src/agents/approval-executor.ts", "../src/agents/approvals.ts", "../src/agents/run-scope.ts", "../src/agents/cancel.ts", "../src/agents/child-question.ts", "../src/agents/subagent-runs.ts", "../src/agents/children.ts", "../src/agents/sandbox.ts", "../src/agents/fork.ts", "../src/agents/memory.ts", "../src/agents/memory-execution.ts", "../src/agents/model-routing.ts", "../src/agents/participants.ts", "../src/agents/request.ts", "../src/runtime/locale.ts", "../src/agents/context-resolution.ts", "../src/agents/dispatch.ts", "../src/agents/retired-config.ts", "../src/agents/execution.ts", "../src/ai-usage/execution.ts", "../src/blob-storage/execution.ts", "../src/connectors/connections/execution.ts", "../src/datasets/execution.ts", "../src/execution/visible-objects.ts", "../src/events/view-conditions.ts", "../src/events/execution.ts", "../src/workflows/errors.ts", "../src/workflows/run-dispatch.ts", "../src/actions/builders/define-action.ts", "../src/shared/params/builders.ts", "../src/actions/registry.ts", "../src/workflows/validation.ts", "../src/workflows/snapshot.ts", "../src/workflows/request.ts", "../src/execution/preparation.ts", "../src/logging/execution.ts", "../src/models/decision/runtime.ts", "../src/agents/model-loop.ts", "../src/models/audio/runtime.ts", "../src/models/input-file.ts", "../src/models/audio/speech.ts", "../src/models/calls.ts", "../src/models/image/runtime.ts", "../src/models/output.ts", "../src/models/execution.ts", "../src/objects/action/request.ts", "../src/objects/materializer-adapter.ts", "../src/objects/errors.ts", "../src/objects/conditional-writes.ts", "../src/objects/link/authorization.ts", "../src/objects/link/endpoints.ts", "../src/objects/link/remove.ts", "../src/objects/link/upsert.ts", "../src/objects/runtime-batch.ts", "../src/objects/link/upsert-batch.ts", "../src/objects/object/delete.ts", "../src/objects/object/upsert.ts", "../src/objects/object/upsert-batch.ts", "../src/objects/vectors/handle.ts", "../src/objects/sdk/file-handle.ts", "../src/objects/telemetry/write-batch.ts", "../src/objects/telemetry/append-batch.ts", "../src/objects/telemetry/history.ts", "../src/objects/sdk/telemetry-channel.ts", "../src/objects/sdk/object-handle.ts", "../src/objects/context/resolve.ts", "../src/objects/sdk/runtime-query-executor.ts", "../src/objects/sdk/object-set.ts", "../src/objects/service/link-service.ts", "../src/objects/service/list-service.ts", "../src/objects/service/object-service.ts", "../src/objects/service/telemetry-service.ts", "../src/objects/execution.ts", "../src/pipelines/execution.ts", "../src/projections/execution.ts", "../src/rules/execution.ts", "../src/schedules/execution.ts", "../src/shares/execution.ts", "../src/syncs/execution.ts", "../src/workflows/execution.ts", "../src/runtime/sixb.ts", "../src/execution/agent.ts"],
4
+ "sourcesContent": [
5
+ "import type { ModelsRuntime } from \"../generation-types\"\nimport type { AiModelCallRecorder } from \"./model-call-recorder\"\n\nexport interface ModelExecutionAttempt {\n readonly attempt: number\n readonly signal: AbortSignal\n /** Internal durable fence around admission; it must invoke admit exactly once to proceed. */\n readonly embeddingAdmission?: (admit: () => Promise<void>) => Promise<void>\n /**\n * Accounting the execution attempt already owns, such as an Agent run's. Calls then share its\n * admission and failure state instead of opening a second recorder for the same attempt. Without\n * it, the binding opens its own recorder — as an agent API gateway request does on the run's\n * attempt, outside the run's in-memory failure state and cancellation.\n */\n readonly accounting?: AiModelCallRecorder\n}\n\nconst bindings = new WeakMap<ModelsRuntime, (input: ModelExecutionAttempt) => void>()\n\nexport function registerModelExecutionBinding(\n models: ModelsRuntime,\n bind: (input: ModelExecutionAttempt) => void\n): void {\n bindings.set(models, bind)\n}\n\n/** Called once on a fresh facade at the request or worker delivery boundary. */\nexport function bindModelExecutionAttempt(\n models: ModelsRuntime,\n input: ModelExecutionAttempt\n): void {\n const bind = bindings.get(models)\n if (!bind) throw new Error(\"[SixbModels] Model runtime has no execution binding.\")\n if (!Number.isSafeInteger(input.attempt) || input.attempt < 1) {\n throw new TypeError(\"[SixbModels] Execution attempt must be a positive safe integer.\")\n }\n bind(input)\n bindings.delete(models)\n}\n",
6
+ "import type { ActionDefinition, ActionParamsConfig } from \"./types\"\n\ntype DeepReadonly<T> = T extends object ? { readonly [TKey in keyof T]: DeepReadonly<T[TKey]> } : T\n\nexport type ActionDescriptorBinding =\n | { readonly kind: \"global\" }\n | { readonly kind: \"object\"; readonly objectTypeId: string }\n\nexport type ActionParamDescriptor = DeepReadonly<ActionParamsConfig[string]>\n\nexport interface ActionPhaseDescriptor {\n readonly validate: boolean\n readonly writeback: boolean\n readonly edits: boolean\n readonly effects: boolean\n}\n\n/** Immutable metadata exposed by the execution-bound Actions catalog. */\nexport interface ActionDescriptor<TId extends string = string> {\n readonly id: TId\n readonly description?: string\n readonly binding: ActionDescriptorBinding\n readonly params: Readonly<Record<string, ActionParamDescriptor>>\n readonly phases: ActionPhaseDescriptor\n}\n\n/** Project an executable definition into inert, detached public metadata. */\nexport function snapshotActionDescriptor(action: ActionDefinition): ActionDescriptor {\n const params = Object.fromEntries(\n Object.entries(action.params).map(([id, config]) => [id, structuredClone(config)])\n ) as Record<string, ActionParamDescriptor>\n\n return deepFreeze({\n id: action.id,\n ...(action.description === undefined ? {} : { description: action.description }),\n binding:\n action.binding.kind === \"global\"\n ? { kind: \"global\" as const }\n : { kind: \"object\" as const, objectTypeId: action.binding.objectType.id },\n params,\n phases: {\n validate: action.phases.validate.length > 0,\n writeback: action.phases.writeback !== undefined,\n edits: action.phases.edits !== undefined,\n effects: action.phases.effects !== undefined,\n },\n })\n}\n\nfunction deepFreeze<T>(value: T, seen: Set<object> = new Set()): T {\n if (typeof value !== \"object\" || value === null || seen.has(value)) return value\n seen.add(value)\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key)\n if (descriptor && \"value\" in descriptor) deepFreeze(descriptor.value, seen)\n }\n return Object.freeze(value)\n}\n",
7
+ "import type { SchemaOrRef, ValueType } from \"../../ontology\"\nimport { isObjectRefSchema } from \"../../ontology/refs\"\nimport { collectUserRefIds, userReferenceProblem } from \"../../ontology/user-ref\"\nimport type { AuthStorage } from \"../../storage/auth/types\"\n\n/**\n * Reject params that reference a user who does not exist or is not active.\n *\n * Callers run it only when a new run is created: replaying an existing run keeps the params it was\n * accepted with, even if a referenced user was suspended since.\n */\nexport async function assertParamUsersActive(input: {\n readonly auth: AuthStorage | undefined\n readonly projectId: string\n readonly schemas: Readonly<Record<string, SchemaOrRef>>\n readonly values: Readonly<Record<string, unknown>>\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n /** Names one param in error messages, for example `Action param 'task.assign.assignee'`. */\n readonly describe: (paramId: string) => string\n readonly invalid: (message: string) => Error\n}): Promise<void> {\n const references: { readonly paramId: string; readonly id: string }[] = []\n for (const [paramId, schema] of Object.entries(input.schemas)) {\n if (isObjectRefSchema(schema)) continue\n const ids = collectUserRefIds(schema, input.values[paramId], input.valueTypesById, new Set())\n for (const id of ids) references.push({ paramId, id })\n }\n if (references.length === 0) return\n\n const users = input.auth?.users\n const statuses = new Map(\n await Promise.all(\n [...new Set(references.map((reference) => reference.id))].map(\n async (id) =>\n [\n id,\n users\n ? ((await users.getById({ projectId: input.projectId, id }))?.status ?? null)\n : \"unverifiable\",\n ] as const\n )\n )\n )\n for (const { paramId, id } of references) {\n const problem = userReferenceProblem(input.describe(paramId), id, statuses.get(id) ?? null)\n if (problem) throw input.invalid(problem)\n }\n}\n",
8
+ "import { AuthorizationError } from \"../authorization\"\nimport type { ResolvedRuntimeAuthorization } from \"../execution/authorization\"\nimport {\n type AuthorizedObjectReader,\n assertAuthorizedObjectReaderBinding,\n} from \"../execution/authorized-object-reader\"\nimport type { ExecutionContext, RuntimeAuthorization } from \"../execution/types\"\nimport type { ActionDefinition, ActionObjectSubject, ActionSubject } from \"./types\"\n\ntype DelegatedAuthorization = Extract<ResolvedRuntimeAuthorization, { readonly type: \"delegated\" }>\n\n/** Reject ungranted tuples before Action lookup can become a metadata oracle. */\nexport function assertDelegatedActionTarget(input: {\n readonly authorization: DelegatedAuthorization\n readonly actionId: string\n readonly subject: ActionSubject\n}): ActionObjectSubject {\n const { actionId, authorization, subject } = input\n if (\n subject.kind !== \"object\" ||\n !authorization.actionApply.some(\n (target) =>\n target.actionId === actionId &&\n target.subject.objectTypeId === subject.objectTypeId &&\n target.subject.primaryId === subject.primaryId\n )\n ) {\n throw denied(actionId, subject)\n }\n return subject\n}\n\n/** Admit an exact tuple against its definition and current selected-read visibility. */\nexport async function admitDelegatedObjectAction(input: {\n readonly objectReader: AuthorizedObjectReader\n readonly runtimeAuthorization: RuntimeAuthorization\n readonly execution: ExecutionContext\n readonly authorization: DelegatedAuthorization\n readonly action: ActionDefinition\n readonly subject: ActionObjectSubject\n}): Promise<void> {\n const { action, authorization, execution, objectReader, runtimeAuthorization, subject } = input\n assertDelegatedActionTarget({ authorization, actionId: action.id, subject })\n if (action.binding.kind !== \"object\" || action.binding.objectType.id !== subject.objectTypeId) {\n throw denied(action.id, subject)\n }\n\n assertAuthorizedObjectReaderBinding({\n reader: objectReader,\n scope: { execution, authorization: runtimeAuthorization },\n })\n\n try {\n const visible = await objectReader.getByPrimaryId({\n objectTypeId: subject.objectTypeId,\n primaryId: subject.primaryId,\n })\n if (!visible) throw denied(action.id, subject)\n } catch (error) {\n if (error instanceof AuthorizationError) throw denied(action.id, subject)\n throw error\n }\n}\n\nfunction denied(actionId: string, subject: ActionSubject): AuthorizationError {\n const target =\n subject.kind === \"object\" ? `${subject.objectTypeId}:${subject.primaryId}` : \"global\"\n return new AuthorizationError(\n `apply:action:${actionId}:${target}`,\n `[Sixb] Delegated authority cannot apply Action '${actionId}' to '${target}'.`\n )\n}\n",
9
+ "import { randomUUID } from \"node:crypto\"\nimport type { ActionRunParams, ActionRunRecord, CreateExecutionInput, Storage } from \"../storage\"\nimport { ActionRunError } from \"../storage\"\nimport { actionRunRequestsEqual } from \"../storage/action-runs/idempotency\"\nimport type { ExecutionRecord } from \"../storage/executions\"\nimport type { PendingActionRun } from \"./run/types\"\nimport { createActionRunIdempotencyKey } from \"./run-id\"\nimport type { ActionSubject } from \"./types\"\n\n/** What a request asks its run id to run. */\nexport interface ActionRunRequestPayload {\n readonly actionId: string\n readonly subject: ActionSubject\n readonly params: ActionRunParams\n}\n\n/** A run that already exists under a requested run id, recorded or still executing. */\nexport type ExistingActionRun = Pick<\n ActionRunRecord,\n \"id\" | \"executionId\" | \"actionId\" | \"subject\" | \"params\"\n>\n\n/** Refuses an existing run the requesting caller may not have. */\nexport type AssertCanReuseActionRun = (run: ExistingActionRun) => void | Promise<void>\n\n/**\n * Answer a request with the run that already exists under its run id only when its caller may have\n * that run, and only for the same request.\n *\n * The caller's right to the run is checked first, so that a refused caller learns nothing about it,\n * not even whether it carries the same request.\n */\nexport async function assertCanReuseActionRun(\n run: ExistingActionRun,\n request: {\n readonly payload: ActionRunRequestPayload\n readonly assertCanReuse: AssertCanReuseActionRun\n }\n): Promise<void> {\n await request.assertCanReuse(run)\n if (!actionRunRequestsEqual(run, request.payload)) {\n throw new ActionRunError(\n `[Sixb] Action run '${run.id}' already exists with a different request payload.`\n )\n }\n}\n\ninterface PersistActionRunInput {\n readonly projectId: string\n readonly storage: Storage\n readonly runId: string\n readonly payload: ActionRunRequestPayload\n readonly createExecution: (executionId: string, runId: string) => Promise<CreateExecutionInput>\n readonly assertCanReuse: AssertCanReuseActionRun\n /** Checks that hold only for a run this call creates; a replayed run keeps its accepted params. */\n readonly assertNewRun?: () => Promise<void>\n}\n\n/** A run this request is to execute, or the record of an earlier request with the same run id. */\nexport type PersistedActionRun =\n | {\n readonly kind: \"new\"\n readonly run: PendingActionRun\n readonly execution: ExecutionRecord\n }\n | { readonly kind: \"recorded\"; readonly run: ActionRunRecord }\n\n/**\n * Persist what a requested run needs before it executes: the durable execution it runs under.\n *\n * Nothing else is stored before the run ends. A run id that is already recorded must carry the same\n * request, and its record answers this request without running anything.\n */\nexport async function persistActionRun(input: PersistActionRunInput): Promise<PersistedActionRun> {\n const { projectId, runId, payload } = input\n if (!input.storage.actionRuns) {\n throw new ActionRunError(\"[Sixb] Action run storage is not configured.\")\n }\n\n const recorded = await input.storage.actionRuns.getById({ projectId, id: runId })\n if (recorded) {\n await assertCanReuseActionRun(recorded, input)\n return { kind: \"recorded\", run: recorded }\n }\n\n await input.assertNewRun?.()\n // The execution is immutable provenance, created before the run executes: its record references\n // it, and so do the commit of its edits and the model calls it makes.\n const execution = await input.storage.executions.create(\n await input.createExecution(`exec_${randomUUID()}`, runId)\n )\n return {\n kind: \"new\",\n run: {\n id: runId,\n projectId,\n executionId: execution.id,\n actionId: payload.actionId,\n subject: payload.subject,\n params: payload.params,\n idempotencyKey: createActionRunIdempotencyKey(projectId, runId),\n },\n execution,\n }\n}\n",
10
+ "import { randomUUID } from \"node:crypto\"\nimport { OntologyValidationError } from \"../ontology/errors\"\n\nexport function createActionRunId(runId: string | undefined): string {\n if (runId !== undefined) {\n if (!runId.trim()) {\n throw new OntologyValidationError(\"[Sixb] Action run id must not be empty\")\n }\n return runId\n }\n\n return `act_${randomUUID()}`\n}\n\nexport function createActionRunIdempotencyKey(projectId: string, runId: string): string {\n return `action:${projectId}:${runId}`\n}\n",
11
+ "import { bindModelExecutionAttempt, type ModelExecutionAttempt } from \"../models/execution/binding\"\nimport type { OntologyMutationRuntime } from \"../runtime/ontology-mutations\"\nimport { getOntologyMutationRuntime } from \"../runtime/ontology-mutations\"\nimport { isBoundSixb, type Sixb } from \"../runtime/sixb\"\nimport type { ExecutionRecord } from \"../storage/executions\"\nimport { restoreTrustedPrimitiveExecutionScope } from \"./durable\"\nimport type { ExecutionScope, TrustedPrimitiveRef } from \"./types\"\n\n/** Minimal host boundary required by trusted primitive workers. */\nexport interface PrimitiveExecutionHost {\n readonly id: string\n withScope(scope: ExecutionScope): object\n}\n\nexport interface BoundPrimitiveExecution {\n readonly sixb: Sixb\n /** Internal mutation port guarded by the same runtime authority as `sixb`. */\n readonly ontologyMutations: OntologyMutationRuntime\n}\n\n/** Bind a worker to the immutable execution already owned by its durable primitive run. */\nexport function bindDurablePrimitiveExecution(\n host: PrimitiveExecutionHost,\n input: {\n readonly execution: ExecutionRecord\n readonly primitive: TrustedPrimitiveRef\n readonly modelExecution?: ModelExecutionAttempt\n }\n): BoundPrimitiveExecution {\n const bound = bindPrimitiveScope(host, restoreTrustedPrimitiveExecutionScope(input))\n if (input.modelExecution) bindModelExecutionAttempt(bound.sixb.models, input.modelExecution)\n return bound\n}\n\nfunction bindPrimitiveScope(\n host: PrimitiveExecutionHost,\n scope: ExecutionScope\n): BoundPrimitiveExecution {\n let ontologyMutations: OntologyMutationRuntime | undefined\n\n const sixb = host.withScope(scope)\n if (!isBoundSixb(sixb)) {\n throw new Error(\"[Sixb] Primitive execution host returned an invalid bound SDK.\")\n }\n const bound: BoundPrimitiveExecution = {\n sixb,\n get ontologyMutations() {\n ontologyMutations ??= getOntologyMutationRuntime(sixb)\n return ontologyMutations\n },\n }\n return Object.freeze(bound)\n}\n",
12
+ "import { linkRefKey, linkScopeKey, objectRefKey } from \"../materialization/refs\"\nimport type {\n EffectiveLinkSnapshot,\n ExpectedLinkRevision,\n ExpectedLinkScopeRevision,\n ExpectedObjectRevision,\n OntologyLinkRef,\n OntologyObjectRef,\n} from \"../materializer\"\nimport { createLinkScopeFingerprint } from \"../materializer\"\nimport { decorateObjectQueryExecutor } from \"../objects/sdk/query-builder\"\nimport type { ObjectQueryExecutor } from \"../objects/sdk/query-executor\"\nimport { OntologyValidationError } from \"../ontology/errors\"\nimport type { ObjectTypeWithPropertyTokens } from \"../ontology/tokens\"\nimport {\n assertPropertyTokenBelongsToObjectType,\n assertTelemetryProperty,\n} from \"../ontology/validation\"\nimport { RuntimeError } from \"../runtime/errors\"\nimport type { ObjectReader, ObjectReadSet } from \"../runtime/types\"\nimport type {\n ExpandedLinkValue,\n ExpandedObjectRow,\n ObjectLinkRow,\n ObjectRow,\n TimeseriesHistoryBatchInput,\n TimeseriesHistoryBatchResult,\n UniqueValueRef,\n} from \"../storage\"\nimport type { ActionReadDependencies } from \"./commit-edits\"\nimport type {\n ActionReadFacade,\n ActionTelemetryHistorySeriesInput,\n ActionTelemetryReadFacade,\n} from \"./types\"\n\n/** Runtime leaves used by the Action telemetry read adapter. */\nexport interface ActionTelemetryReadSource {\n readonly resolveObjectType: (objectTypeId: string) => ObjectTypeWithPropertyTokens\n readonly getHistoryBatch: (\n input: Omit<TimeseriesHistoryBatchInput, \"projectId\">\n ) => Promise<readonly TimeseriesHistoryBatchResult[]>\n}\n\n/**\n * Records the exact state an Action handler observed while reading.\n *\n * A handler that reads one dependency twice keeps the first observation: the commit must fail when\n * current state no longer matches what the decision was made against, and the later read may already\n * reflect the handler's own intent. Objects returned by `list()` and `query()` are fenced like\n * concrete reads, but query membership is not yet: an object that starts matching a query after the\n * read, and aggregate results (`count()`, `exists()`, `facets()`), stay unfenced. Telemetry history\n * and file content are also call-level snapshots, not edit dependencies.\n */\nexport class ActionReadRecorder {\n private readonly objects = new Map<string, ExpectedObjectRevision>()\n private readonly links = new Map<string, ExpectedLinkRevision>()\n private readonly linkScopes = new Map<string, ExpectedLinkScopeRevision>()\n private readonly unclaimedValues = new Map<string, UniqueValueRef>()\n\n /** Records a concrete object read, including exact absence. */\n observeObject(ref: OntologyObjectRef, row: ObjectRow | null): void {\n const key = objectRefKey(ref)\n if (this.objects.has(key)) return\n if (!row) {\n this.objects.set(key, { ref, exists: false })\n return\n }\n // Rows without materializer provenance predate the commit ledger and cannot be fenced.\n if (row.lastCommitId === undefined) return\n this.objects.set(key, {\n ref,\n exists: true,\n version: row.version,\n lastCommitId: row.lastCommitId,\n })\n }\n\n /**\n * Records every object a listing or query returned, including the objects its expansions attached.\n *\n * Rows are keyed by their own type: a traversal or subtype query returns objects of a type other\n * than the one the query started from, and the commit checks each row under its exact identity.\n */\n observeObjectRows(rows: readonly ObjectRow[]): void {\n for (const row of rows) {\n this.observeObject({ objectTypeId: row.objectTypeId, primaryId: row.primaryId }, row)\n for (const value of Object.values(row.links ?? {})) {\n this.observeObjectRows(expandedRows(value))\n }\n }\n }\n\n /**\n * Records the complete `(source, linkId)` scopes a link listing observed.\n *\n * `linkIds` names every scope the read covered so an empty scope is recorded as an empty\n * fingerprint rather than being silently omitted.\n */\n observeLinkScopes(\n source: OntologyObjectRef,\n linkIds: readonly string[],\n rows: readonly ObjectLinkRow[]\n ): void {\n const snapshotsByLinkId = new Map<string, EffectiveLinkSnapshot[]>()\n for (const linkId of linkIds) snapshotsByLinkId.set(linkId, [])\n /** Scopes holding a row that cannot be fenced, so no expectation may be recorded for them. */\n const unfenceable = new Set<string>()\n\n for (const row of rows) {\n if (row.sourceTypeId !== source.objectTypeId || row.sourceId !== source.primaryId) continue\n const snapshots = snapshotsByLinkId.get(row.linkId)\n if (!snapshots) continue\n const snapshot = toLinkSnapshot(row)\n if (!snapshot) {\n // Same rule `observeObject` applies to rows without materializer provenance: record no\n // expectation at all. A fingerprint computed over the remaining rows would describe a scope\n // the store can never reproduce, turning every such read into a guaranteed conflict.\n unfenceable.add(row.linkId)\n continue\n }\n snapshots.push(snapshot)\n this.observeLink(snapshot.ref, snapshot)\n }\n\n for (const [linkId, snapshots] of snapshotsByLinkId) {\n if (unfenceable.has(linkId)) continue\n const key = linkScopeKey(source, linkId)\n if (this.linkScopes.has(key)) continue\n this.linkScopes.set(key, {\n source,\n linkId,\n fingerprint: createLinkScopeFingerprint(snapshots),\n })\n }\n }\n\n /** Records a concrete link read, including exact absence. */\n observeLink(ref: OntologyLinkRef, snapshot: EffectiveLinkSnapshot | null): void {\n const key = linkRefKey(ref)\n if (this.links.has(key)) return\n this.links.set(\n key,\n snapshot ? { ref, exists: true, lastCommitId: snapshot.lastCommitId } : { ref, exists: false }\n )\n }\n\n /**\n * Records a unique value no object held. A holder that appears before the commit, such as one a\n * concurrent run created, replays the Action instead of failing its own create on the duplicate.\n */\n observeUnclaimedValue(value: UniqueValueRef): void {\n this.unclaimedValues.set(\n JSON.stringify([value.objectTypeId, value.propertyId, value.valueKey]),\n {\n objectTypeId: value.objectTypeId,\n propertyId: value.propertyId,\n valueKey: value.valueKey,\n }\n )\n }\n\n dependencies(): ActionReadDependencies {\n return {\n objects: [...this.objects.values()],\n links: [...this.links.values()],\n linkScopes: [...this.linkScopes.values()],\n unclaimedValues: [...this.unclaimedValues.values()],\n }\n }\n}\n\nexport interface ActionReadFacadeOptions {\n /** Records what the handler observed, so the commit can be fenced against it. */\n readonly recorder: ActionReadRecorder\n /**\n * Every link the object type carries, inherited links included.\n *\n * Inheritance is resolved by the Ontology registry, not by the imported definition, so an\n * `extends` type would otherwise report only its own links and drop inherited ones from the\n * recorded scopes.\n */\n readonly resolveLinkIds: (objectTypeId: string) => readonly string[]\n /** The key a unique value is stored under, as `getBy` computes it. */\n readonly uniqueValueKey: (objectTypeId: string, propertyId: string, value: unknown) => string\n /** Canonical authorized telemetry history leaf. Omitted only by isolated facade consumers. */\n readonly telemetry?: ActionTelemetryReadSource\n}\n\n/** Exposes `reader`'s object reads to an Action handler; with `options`, each read is recorded. */\nexport function createActionReadFacade(\n reader: ObjectReader,\n options?: ActionReadFacadeOptions\n): ActionReadFacade {\n return {\n telemetry: createActionTelemetryReadFacade(options?.telemetry),\n objects<const TObjectType extends ObjectTypeWithPropertyTokens>(objectType: TObjectType) {\n const objectSet = reader.objects(objectType)\n return options ? recordObjectReads(objectType, objectSet, options) : objectSet\n },\n }\n}\n\nfunction createActionTelemetryReadFacade(\n source: ActionTelemetryReadSource | undefined\n): ActionTelemetryReadFacade {\n const facade = {\n async historyBatch(input: {\n readonly series: readonly ActionTelemetryHistorySeriesInput[]\n readonly from?: Date\n readonly to?: Date\n readonly limitPerSeries?: number\n readonly order?: \"asc\" | \"desc\"\n }) {\n if (!source) {\n throw new RuntimeError(\n \"[Sixb] Action telemetry history requires a configured telemetry read source.\"\n )\n }\n if (input.series.length === 0) {\n return []\n }\n\n const requestedSeries = input.series.map((entry) => {\n const objectType = source.resolveObjectType(entry.property.objectTypeId)\n assertPropertyTokenBelongsToObjectType(objectType, entry.property)\n const registeredProperty = objectType.properties.find(\n (property) => property.id === entry.property.id\n )\n if (!registeredProperty) {\n throw new OntologyValidationError(\n `[Sixb] Unknown property '${entry.property.id}' for object type '${objectType.id}'`\n )\n }\n assertTelemetryProperty(registeredProperty)\n return {\n objectTypeId: objectType.id,\n objectId: entry.objectId,\n propertyId: registeredProperty.id,\n }\n })\n\n const results = await source.getHistoryBatch({\n series: requestedSeries,\n ...(input.from !== undefined ? { from: input.from } : {}),\n ...(input.to !== undefined ? { to: input.to } : {}),\n ...(input.limitPerSeries !== undefined ? { limitPerSeries: input.limitPerSeries } : {}),\n ...(input.order !== undefined ? { order: input.order } : {}),\n })\n assertTelemetryBatchResultMatchesRequest(requestedSeries, results)\n\n return input.series.map((entry, index) => ({\n objectId: entry.objectId,\n property: entry.property,\n points: results[index].points.map((point) => ({\n value: point.value,\n at: point.at,\n ...(point.unit !== undefined ? { unit: point.unit } : {}),\n })),\n }))\n },\n }\n\n // Cast needed at the generic token boundary: the implementation deliberately manipulates raw\n // provider values while the public facade maps every tuple position back to its property token.\n return facade as unknown as ActionTelemetryReadFacade\n}\n\nfunction assertTelemetryBatchResultMatchesRequest(\n requested: readonly {\n readonly objectTypeId: string\n readonly objectId: string\n readonly propertyId: string\n }[],\n results: readonly TimeseriesHistoryBatchResult[]\n): void {\n if (results.length !== requested.length) {\n throw new RuntimeError(\n `[Sixb] Telemetry history provider returned ${results.length} batch results for ${requested.length} requested series.`\n )\n }\n\n for (let index = 0; index < requested.length; index += 1) {\n const expected = requested[index]\n const actual = results[index]\n if (\n actual.objectTypeId !== expected.objectTypeId ||\n actual.objectId !== expected.objectId ||\n actual.propertyId !== expected.propertyId\n ) {\n throw new RuntimeError(\n `[Sixb] Telemetry history provider returned an unexpected series at batch index ${index}.`\n )\n }\n }\n}\n\nfunction recordObjectReads<TObjectType extends ObjectTypeWithPropertyTokens>(\n objectType: TObjectType,\n objectSet: ObjectReadSet<TObjectType>,\n options: ActionReadFacadeOptions\n): ObjectReadSet<TObjectType> {\n const { recorder } = options\n const ref = (primaryId: string): OntologyObjectRef => ({\n objectTypeId: objectType.id,\n primaryId,\n })\n\n return {\n async get(id) {\n const row = await objectSet.get(id)\n recorder.observeObject(ref(id), row && storageRow(row))\n return row\n },\n async getBy(property, value) {\n const row = await objectSet.getBy(property, value)\n if (row) {\n recorder.observeObject(ref(row.primaryId), storageRow(row))\n } else {\n recorder.observeUnclaimedValue({\n objectTypeId: objectType.id,\n propertyId: property.id,\n valueKey: options.uniqueValueKey(objectType.id, property.id, value),\n })\n }\n return row\n },\n query() {\n // Recording at the executor covers every terminal of every refinement, present and future.\n return decorateObjectQueryExecutor(objectSet.query(), (executor) =>\n recordingExecutor(executor, recorder)\n )\n },\n async list(input) {\n const result = await objectSet.list(input)\n recorder.observeObjectRows(result.objects.map(storageRow))\n return result\n },\n byId(id) {\n const handle = objectSet.byId(id)\n return {\n async get() {\n const row = await handle.get()\n recorder.observeObject(ref(id), row && storageRow(row))\n return row\n },\n async listLinks(link) {\n const rows = await handle.listLinks(link)\n recorder.observeLinkScopes(\n ref(id),\n link ? [link.id] : options.resolveLinkIds(objectType.id),\n rows\n )\n return rows\n },\n file: handle.file,\n }\n },\n }\n}\n\n/**\n * Delegates to `executor` and records the objects its row queries return.\n *\n * Aggregates (`count()`, `exists()`, `facets()`) return no rows to fence; protecting their result\n * needs query-level dependencies.\n */\nfunction recordingExecutor(\n executor: ObjectQueryExecutor,\n recorder: ActionReadRecorder\n): ObjectQueryExecutor {\n return {\n async list(query, listOptions) {\n const result = await executor.list(query, listOptions)\n recorder.observeObjectRows(result.objects.map(storageRow))\n return result\n },\n count: (query) => executor.count(query),\n exists: (query) => executor.exists(query),\n facets: (query, facets) => executor.facets(query, facets),\n validate: executor.validate?.bind(executor),\n explain: executor.explain?.bind(executor),\n }\n}\n\n/**\n * Runtime reads return storage rows; the SDK row types only leave out the commit fields a fence\n * needs.\n */\nfunction storageRow(row: object): ObjectRow {\n return row as ObjectRow\n}\n\nfunction expandedRows(value: ExpandedLinkValue): readonly ObjectRow[] {\n if (value === null) return []\n return isExpandedRowList(value) ? value : [value]\n}\n\n// `Array.isArray` does not narrow a readonly array out of a union.\nfunction isExpandedRowList(value: ExpandedLinkValue): value is readonly ExpandedObjectRow[] {\n return Array.isArray(value)\n}\n\nfunction toLinkSnapshot(row: ObjectLinkRow): EffectiveLinkSnapshot | null {\n // Rows without materializer provenance predate the commit ledger and cannot be fenced.\n if (row.lastCommitId === undefined) return null\n return {\n ref: {\n source: { objectTypeId: row.sourceTypeId, primaryId: row.sourceId },\n linkId: row.linkId,\n target: { objectTypeId: row.targetTypeId, primaryId: row.targetId },\n },\n ...(row.properties !== undefined\n ? { properties: row.properties as EffectiveLinkSnapshot[\"properties\"] }\n : {}),\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n lastCommitId: row.lastCommitId,\n }\n}\n",
13
+ "import { createSixbError } from \"../../errors/internal\"\nimport { uniqueLookupKeyOf } from \"../../execution/unique-lookup\"\nimport type { Logger } from \"../../logging\"\nimport type { ObjectTypeWithPropertyTokens } from \"../../ontology/tokens\"\nimport { ObjectNotFoundError, type ObjectRow } from \"../../storage\"\nimport type { ActionReadRecorder } from \"../read-facade\"\nimport { createActionReadFacade } from \"../read-facade\"\nimport type {\n ActionDefinition,\n ActionObjectSubject,\n ActionReadFacade,\n ActionRuntimeFacade,\n ActionSubject,\n ActionTargetObject,\n} from \"../types\"\nimport { coerceActionParamsToTyped, isObjectActionDefinition } from \"../validation\"\nimport type { LoadedObjectTarget } from \"./phase-types\"\nimport type { ActionRunState } from \"./state\"\nimport type { ActionRunContext, PendingActionRun } from \"./types\"\n\nexport function toActionRuntimeFacade(runtime: ActionRunContext): ActionRuntimeFacade {\n return {\n blobs: {\n put(input) {\n return runtime.sixb.blobs.put(input)\n },\n open(blobId) {\n return runtime.sixb.blobs.open(blobId)\n },\n stat(blobId) {\n return runtime.sixb.blobs.stat(blobId)\n },\n createDownloadUrl(file, options) {\n return runtime.sixb.blobs.createDownloadUrl(file, options)\n },\n revokeDownloadUrl(id) {\n return runtime.sixb.blobs.revokeDownloadUrl(id)\n },\n },\n connector: runtime.sixb.connector,\n models: runtime.sixb.models,\n users: runtime.sixb.users,\n objects(objectType) {\n return {\n appendTelemetryBatch(items) {\n return runtime.sixb.objects.appendTelemetry(objectType.id, items)\n },\n }\n },\n }\n}\n\nexport function toActionReadFacade(\n runtime: ActionRunContext,\n recorder: ActionReadRecorder\n): ActionReadFacade {\n return createActionReadFacade(runtime.sixb, {\n recorder,\n resolveLinkIds: (objectTypeId) =>\n runtime.sixb.objects.resolveType(objectTypeId).links.map((definition) => definition.id),\n uniqueValueKey: (objectTypeId, propertyId, value) =>\n uniqueLookupKeyOf(\n runtime.sixb.objects.resolveType(objectTypeId),\n propertyId,\n value,\n runtime.sixb.objects.getValueTypesById()\n ),\n telemetry: {\n resolveObjectType: (objectTypeId) => runtime.sixb.objects.resolveType(objectTypeId),\n getHistoryBatch: (input) => runtime.sixb.objects.getTelemetryHistoryBatch(input),\n },\n })\n}\n\nfunction toActionTargetObject(\n row: {\n primaryId: string\n objectTypeId: string\n properties: Record<string, unknown>\n createdAt: Date\n updatedAt: Date\n },\n declaredObjectTypeId: string\n): ActionTargetObject {\n return {\n primaryId: row.primaryId,\n objectTypeId: declaredObjectTypeId,\n properties: row.properties,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n }\n}\n\n/** The handler context every phase shares. Each phase adds the `signal` it runs under. */\nexport function createBasePhaseContext(input: {\n readonly runtime: ActionRunContext\n readonly action: ActionDefinition\n readonly state: ActionRunState\n readonly logger: Logger\n}) {\n const { run, startedAt } = input.state\n return {\n run: {\n id: run.id,\n startedAt,\n idempotencyKey: run.idempotencyKey,\n },\n logger: input.logger,\n // Params are stored as JSON (date/timestamp -> ISO string); handler types\n // promise `Date`, so re-hydrate them before the handler sees them.\n params: coerceActionParamsToTyped(\n input.action.params,\n run.params,\n input.runtime.sixb.objects.getValueTypesById()\n ),\n subject: run.subject,\n requestedBy: input.runtime.requestedBy,\n }\n}\n\nexport type BasePhaseContext = ReturnType<typeof createBasePhaseContext>\n\nexport async function loadObjectTarget(input: {\n readonly runtime: ActionRunContext\n readonly action: ActionDefinition\n readonly run: PendingActionRun\n}): Promise<LoadedObjectTarget | null> {\n if (!isObjectActionDefinition(input.action)) {\n if (input.run.subject.kind !== \"none\") {\n throw createSixbError(\n \"internal.unexpected\",\n `[Sixb] Action '${input.action.id}' does not accept a subject.`,\n { details: { actionId: input.action.id, runId: input.run.id } }\n )\n }\n return null\n }\n\n const subject = requireObjectSubject(input.run.subject, {\n actionId: input.action.id,\n runId: input.run.id,\n })\n const subjectObjectType = input.runtime.sixb.objects.resolveType(subject.objectTypeId)\n const actionAppliesToSubject = input.runtime.sixb.actions\n .listForType(subjectObjectType)\n .some((candidate) => candidate.id === input.action.id)\n if (!actionAppliesToSubject) {\n throw createSixbError(\n \"internal.unexpected\",\n `[Sixb] Action '${input.action.id}' is not valid for object type '${subjectObjectType.id}'.`,\n { details: { actionId: input.action.id, runId: input.run.id } }\n )\n }\n\n const targetRow = await input.runtime.storage.objects.getByPrimaryId({\n projectId: input.runtime.id,\n objectTypeId: subjectObjectType.id,\n primaryId: subject.primaryId,\n })\n if (!targetRow) {\n throw new ObjectNotFoundError(\n subject.objectTypeId,\n subject.primaryId,\n \"Object not found for action run\"\n )\n }\n\n await assertRequesterSees(input.runtime, targetRow, {\n actionId: input.action.id,\n runId: input.run.id,\n })\n\n return {\n subjectObjectType,\n snapshot: toActionTargetObject(targetRow, input.action.binding.objectType.id),\n row: targetRow,\n }\n}\n\n/**\n * Handlers run on, and the commit fences on, the state just read. A requester that views the type\n * through a condition must see that very state: hidden, it is not found, as a missing subject is,\n * and on a replay too. A state that changed between the two reads conflicts, and the run replays\n * on what it finds then.\n */\nasync function assertRequesterSees(\n runtime: ActionRunContext,\n row: ObjectRow,\n ids: { readonly actionId: string; readonly runId: string }\n): Promise<void> {\n if (!runtime.readSubjectAsRequester) return\n\n const seen = await runtime.readSubjectAsRequester(row)\n if (!seen) {\n throw new ObjectNotFoundError(\n row.objectTypeId,\n row.primaryId,\n \"Object not found for action run\"\n )\n }\n\n if (seen.version !== row.version) {\n throw createSixbError(\n \"action.read_conflict\",\n `[Sixb] Action run '${ids.runId}' read its subject while it changed.`,\n { details: ids }\n )\n }\n}\n\nexport function requireObjectSubject<\n TObjectType extends ObjectTypeWithPropertyTokens = ObjectTypeWithPropertyTokens,\n>(\n subject: ActionSubject,\n input: { readonly actionId: string; readonly runId: string }\n): ActionObjectSubject<TObjectType> {\n if (subject.kind !== \"object\") {\n throw createSixbError(\n \"internal.unexpected\",\n `[Sixb] Action '${input.actionId}' requires an object subject.`,\n { details: input }\n )\n }\n return subject as ActionObjectSubject<TObjectType>\n}\n\nexport function requireObjectTarget(\n target: LoadedObjectTarget | null,\n input: { readonly actionId: string; readonly runId: string }\n): LoadedObjectTarget {\n if (!target) {\n throw createSixbError(\n \"internal.unexpected\",\n `[Sixb] Action '${input.actionId}' requires an object target.`,\n { details: input }\n )\n }\n return target\n}\n",
14
+ "import { createSixbError, type SixbCodedError, withFailureMessage } from \"../errors/internal\"\nimport type { ReadonlyJsonValue } from \"../json\"\nimport { UniqueValueViolationError } from \"../materialization/errors\"\n\n/**\n * The coded error a write reports when it would give a unique value to a second object, or\n * `undefined` for any other error. Like its message, it names only the type and the property:\n * never the value, nor the object that holds it.\n */\nexport function uniqueViolationError(\n error: unknown,\n details?: ReadonlyJsonValue\n): SixbCodedError | undefined {\n if (!(error instanceof UniqueValueViolationError)) return undefined\n\n return codedViolation(error.objectTypeId, error.propertyId, error.message, {\n cause: error,\n details,\n })\n}\n\n/** The same coded error for a batch item that a continue-mode commit refused. */\nexport function uniqueViolationItemError(item: UniqueViolation): SixbCodedError {\n return codedViolation(item.objectTypeId, item.propertyId, item.message)\n}\n\ninterface UniqueViolation {\n readonly objectTypeId: string\n readonly propertyId: string\n readonly message: string\n}\n\n/**\n * The error a create meets on a primary id an object its writer cannot see holds. It tells that the\n * id is taken, as a unique value is, and nothing about the object.\n */\nexport function primaryIdTakenError(\n objectTypeId: string,\n primaryPropertyId: string\n): SixbCodedError {\n return codedViolation(\n objectTypeId,\n primaryPropertyId,\n `[Sixb] Another '${objectTypeId}' object already has this '${primaryPropertyId}'.`\n )\n}\n\nfunction codedViolation(\n objectTypeId: string,\n propertyId: string,\n message: string,\n options: { readonly cause?: unknown; readonly details?: ReadonlyJsonValue } = {}\n): SixbCodedError {\n const coded = createSixbError(\"object.unique_violation\", message, {\n ...(options.cause === undefined ? {} : { cause: options.cause }),\n details: options.details ?? { objectTypeId, propertyId },\n })\n return withFailureMessage(coded, `Property '${objectTypeId}.${propertyId}' is unique.`)\n}\n",
15
+ "import { createSixbError, isSixbError } from \"../../errors/internal\"\n\n/** How long an Action run has to reach its irreversible boundary, and its effects after commit. */\nexport const ACTION_TIMEOUT_MS = 30_000\n\n/**\n * How long a stopping process waits for its in-flight Action runs and their effects: a run's\n * deadline, then its effects' deadline, plus a margin.\n *\n * It does not bound a whole run. Edits past the boundary are uninterruptible, and effects start\n * only once they committed, so a run or its effects can still be executing when the wait ends. A\n * deployment's kill timeout must exceed this bound.\n */\nexport const ACTION_RUN_DRAIN_TIMEOUT_MS = 2 * ACTION_TIMEOUT_MS + 5_000\n\nexport interface ActionRunSignalsInput {\n readonly actionId: string\n readonly runId: string\n /** The caller's cancellation. It applies before the boundary only. */\n readonly caller?: AbortSignal\n}\n\n/**\n * The cancellation one Action run observes, phase by phase.\n *\n * The irreversible boundary is a succeeded writeback, or the commit of an Action without one. Before\n * it, validation, writeback and edits run under {@link beforeBoundary}, which aborts when the run's\n * deadline elapses or its caller aborts. After it, edits and commit run under\n * {@link uninterruptible}: abandoning them would strand an external change that the ontology never\n * records. Effects run after the commit under a deadline of their own, which\n * {@link startEffects} starts.\n *\n * Cancellation is cooperative: a handler stops early only when it forwards its `signal` to what it\n * awaits. The run stops waiting for one that does not, wherever abandoning it loses nothing:\n * validation, edits before the boundary, and effects (`untilAborted`). A writeback is always waited\n * for, since only its result says whether the external change happened.\n */\nexport class ActionRunSignals {\n readonly beforeBoundary: AbortSignal\n /**\n * Never aborts, for the work that must run to completion once it starts. One per run: whatever\n * listens to it is released with the run, not kept for the life of the process.\n */\n readonly uninterruptible: AbortSignal = new AbortController().signal\n\n private readonly input: ActionRunSignalsInput\n private readonly deadline: ActionDeadline\n\n constructor(input: ActionRunSignalsInput) {\n this.input = input\n this.deadline = new ActionDeadline(input, \"run\")\n this.beforeBoundary = input.caller\n ? AbortSignal.any([this.deadline.signal, input.caller])\n : this.deadline.signal\n }\n\n /**\n * Why the run stopped before its boundary: its deadline's `action.timeout` when the deadline\n * elapsed first, or else a `runtime.cancelled` error caused by what its caller aborted with.\n */\n stopReason(): unknown {\n const reason = this.beforeBoundary.reason\n if (isActionTimeout(reason)) return reason\n return createSixbError(\n \"runtime.cancelled\",\n `[Sixb] Action run '${this.input.runId}' was cancelled by its caller.`,\n { cause: reason, details: { actionId: this.input.actionId, runId: this.input.runId } }\n )\n }\n\n /**\n * Start the deadline the run's effects run under. It is independent of the run's own: effects\n * start after the run is recorded, and the caller of the deadline disposes it once they end.\n */\n startEffects(): ActionDeadline {\n return new ActionDeadline(this.input, \"effects\")\n }\n\n /** Release the run's deadline timer. */\n dispose(): void {\n this.deadline.dispose()\n }\n}\n\n/** A signal that aborts with `action.timeout` once its scope's deadline elapses. */\nexport class ActionDeadline {\n readonly signal: AbortSignal\n private readonly timer: ReturnType<typeof setTimeout>\n\n constructor(input: Pick<ActionRunSignalsInput, \"actionId\" | \"runId\">, scope: \"run\" | \"effects\") {\n const controller = new AbortController()\n this.signal = controller.signal\n this.timer = setTimeout(() => {\n controller.abort(\n createSixbError(\n \"action.timeout\",\n `[Sixb] Action run '${input.runId}' exceeded its ${ACTION_TIMEOUT_MS} ms ${scope} deadline.`,\n { details: { actionId: input.actionId, runId: input.runId } }\n )\n )\n }, ACTION_TIMEOUT_MS)\n }\n\n /** Release the deadline timer. */\n dispose(): void {\n clearTimeout(this.timer)\n }\n}\n\nexport function isActionTimeout(error: unknown): boolean {\n return isSixbError(error) && error.code === \"action.timeout\"\n}\n",
16
+ "import {\n createSixbError,\n isSixbError,\n type SixbCodedError,\n summarizeErrorMessage,\n toSixbFailure,\n} from \"../../errors/internal\"\nimport { isMaterializationConflictError } from \"../../materialization/errors\"\nimport { ActionValidationError } from \"../../objects/action/errors\"\nimport { uniqueViolationError } from \"../../objects/unique-violation\"\nimport { ACTION_RUN_FAILURE_CODES, type ActionRunFailure, type ActionRunPhase } from \"../../storage\"\nimport { parseActionRunFailure } from \"../../storage/action-runs/failure\"\nimport { isActionTimeout } from \"./signals\"\n\nexport function throwIfAborted(signal: AbortSignal): void {\n if (signal.aborted) throw abortReason(signal)\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason instanceof Error\n ? signal.reason\n : new DOMException(\"[Sixb] Action run was cancelled.\", \"AbortError\")\n}\n\n/**\n * Wait for a handler until the signal of its phase aborts, then reject with the abort's reason.\n *\n * A handler stops early only when it forwards its `signal` to what it awaits. One that does not\n * keeps running after the abort, but the run no longer waits for it: nothing it does from then on\n * reaches the run, and what it throws is dropped.\n */\nexport async function untilAborted<T>(work: () => Promise<T>, signal: AbortSignal): Promise<T> {\n throwIfAborted(signal)\n const aborted = Promise.withResolvers<never>()\n const abort = () => aborted.reject(abortReason(signal))\n signal.addEventListener(\"abort\", abort, { once: true })\n const running = (async () => work())()\n try {\n return await Promise.race([running, aborted.promise])\n } finally {\n signal.removeEventListener(\"abort\", abort)\n running.catch(() => undefined)\n }\n}\n\n/**\n * Translate work performed by an Action phase without misclassifying its bookkeeping.\n *\n * Whatever a handler throws once its phase's signal aborted is that abort's doing: the run failed\n * with `action.timeout` when its deadline elapsed, and with `runtime.cancelled` when its caller\n * aborted. The handler's own error stays the cause reported to `onError`. Every expectation an\n * Action commit carries comes from the Action's own reads, so an expectation conflict at commit is\n * a read conflict: the run can be requested again against current state. A validator's returned\n * error is a rejection, not a crash.\n */\nexport function translateActionPhaseError(\n error: unknown,\n phase: ActionRunPhase,\n input: {\n readonly actionId: string\n readonly runId: string\n /** The signal the work ran under. Omit it for work that nothing interrupts, like a commit. */\n readonly signal?: AbortSignal\n }\n): unknown {\n const details = { actionId: input.actionId, runId: input.runId, phase }\n if (input.signal?.aborted) {\n if (isActionTimeout(input.signal.reason)) {\n return isActionTimeout(error)\n ? error\n : createSixbError(\n \"action.timeout\",\n `[Sixb] Action run '${input.runId}' exceeded its deadline during ${phase}.`,\n { cause: error, details }\n )\n }\n return isSixbError(error) && error.code === \"runtime.cancelled\"\n ? error\n : createSixbError(\n \"runtime.cancelled\",\n `[Sixb] Action run '${input.runId}' was cancelled by its caller during ${phase}.`,\n { cause: error, details }\n )\n }\n if (isSixbError(error) && error.code === \"internal.unexpected\") {\n return error\n }\n if (error instanceof ActionValidationError) {\n return createSixbError(\"action.rejected\", error.message, { cause: error, details })\n }\n if (phase === \"commit\" && isMaterializationConflictError(error) && error.kind === \"expectation\") {\n return createSixbError(\"action.read_conflict\", error.message, { cause: error, details })\n }\n const uniqueViolation = phase === \"commit\" ? uniqueViolationError(error, details) : undefined\n if (uniqueViolation) return uniqueViolation\n\n return createSixbError(\n \"action.phase_failed\",\n summarizeErrorMessage(error, \"Action phase execution failed.\"),\n { cause: error, details }\n )\n}\n\n/** Whether a phase classified this error as the phase's own failure, rather than as an abort. */\nexport function isActionPhaseFailure(error: unknown): error is SixbCodedError {\n return (\n isSixbError(error) &&\n (error.code === \"action.phase_failed\" ||\n error.code === \"action.read_conflict\" ||\n error.code === \"action.rejected\")\n )\n}\n\n/** Recover the native phase error for direct callers and error-monitoring integrations. */\nexport function unwrapActionPhaseError(error: unknown): unknown {\n return isActionPhaseFailure(error) && error.cause !== undefined ? error.cause : error\n}\n\nexport function toActionRunFailure<TPhase extends ActionRunPhase>(\n error: unknown,\n phase: TPhase,\n input: {\n readonly actionId: string\n readonly runId: string\n readonly at: Date\n }\n): ActionRunFailure<TPhase> {\n const code =\n isSixbError(error) && (ACTION_RUN_FAILURE_CODES as readonly string[]).includes(error.code)\n ? (error.code as ActionRunFailure<TPhase>[\"code\"])\n : \"internal.unexpected\"\n const normalized = createSixbError(\n code,\n summarizeErrorMessage(error, \"Action execution failed.\"),\n {\n cause: unwrapActionPhaseError(error),\n details: {\n actionId: input.actionId,\n runId: input.runId,\n phase,\n },\n }\n )\n\n return parseActionRunFailure(\n toSixbFailure(normalized, {\n allowedCodes: ACTION_RUN_FAILURE_CODES,\n at: input.at,\n }),\n phase\n )\n}\n",
17
+ "import { reportActionPhaseFailure } from \"../../error-reporting/capability\"\nimport type { Logger } from \"../../logging\"\nimport { resolveLoggingService } from \"../../logging/service\"\nimport type { RecordActionEffectsInput } from \"../../storage\"\nimport type { ActionEditCommitResult } from \"../commit-edits\"\nimport type { ActionDefinition } from \"../types\"\nimport { isObjectActionDefinition } from \"../validation\"\nimport { createBasePhaseContext, requireObjectSubject, toActionRuntimeFacade } from \"./context\"\nimport { toActionRunFailure, translateActionPhaseError, untilAborted } from \"./normalize\"\nimport type { ActionDeadline } from \"./signals\"\nimport type { ActionRunState } from \"./state\"\nimport type { ActionRunContext } from \"./types\"\n\nexport interface RunActionEffectsInput {\n readonly runtime: ActionRunContext\n readonly action: ActionDefinition\n /** The run, recorded as succeeded with the commit its effects receive. */\n readonly state: ActionRunState\n readonly commit: ActionEditCommitResult\n /** Starts the effects' deadline. */\n readonly startDeadline: () => ActionDeadline\n}\n\n/**\n * Run a recorded run's effects and record their outcome on it.\n *\n * Effects run after the run's record is returned, and nothing waits for them but a stopping\n * process. They are best-effort: their failure does not reject this, it is recorded on the run and\n * reported to `onError`, and the run stays succeeded.\n */\nexport async function runActionEffects(input: RunActionEffectsInput): Promise<void> {\n const { runtime, action, state } = input\n const ids = { actionId: action.id, runId: state.run.id }\n const logSession = resolveLoggingService(runtime.id, runtime.logging).startExecution({\n kind: \"action\",\n id: state.run.id,\n })\n const deadline = input.startDeadline()\n\n try {\n const outcome = await callEffects(\n input,\n deadline.signal,\n logSession.withContext({ phase: \"effects\" })\n )\n try {\n await runtime.actionRunsStorage.recordEffects(outcome)\n } catch (error) {\n console.error(\n `[Sixb] Action run '${ids.runId}' ran its effects, but their outcome could not be recorded:`,\n error\n )\n }\n } finally {\n deadline.dispose()\n await logSession.flush()\n }\n}\n\n/** Call the effects handler, and describe how it ended. A failure is reported here, once. */\nasync function callEffects(\n input: RunActionEffectsInput,\n signal: AbortSignal,\n logger: Logger\n): Promise<RecordActionEffectsInput> {\n const { runtime, action, state } = input\n const ids = { actionId: action.id, runId: state.run.id }\n const effects = { id: state.run.id, projectId: runtime.id }\n\n try {\n const context = {\n ...createBasePhaseContext({ runtime, action, state, logger }),\n signal,\n sixb: toActionRuntimeFacade(runtime),\n writeback: state.writebackValue,\n commit: input.commit,\n }\n await untilAborted(async () => {\n if (isObjectActionDefinition(action)) {\n await action.phases.effects?.({\n ...context,\n subject: requireObjectSubject(state.run.subject, ids),\n })\n } else {\n await action.phases.effects?.(context)\n }\n }, signal)\n } catch (error) {\n const completedAt = new Date()\n const failure = toActionRunFailure(\n translateActionPhaseError(error, \"effects\", { ...ids, signal }),\n \"effects\",\n { ...ids, at: completedAt }\n )\n reportActionPhaseFailure(runtime.errorReporterHost, error, {\n projectId: runtime.id,\n ...ids,\n phase: \"effects\",\n failure,\n })\n return { ...effects, status: \"failed\", completedAt, error: failure }\n }\n\n return { ...effects, status: \"succeeded\", completedAt: new Date() }\n}\n",
18
+ "import { withFailureMessage } from \"../errors/failure-message\"\nimport { ActionValidationError } from \"../objects/action/errors\"\nimport type { ActionDefinition, ActionSubject, ActionTargetObject } from \"./types\"\nimport { isObjectActionDefinition } from \"./validation\"\n\ntype RuntimePhaseHandler = (ctx: unknown) => unknown | Promise<unknown>\n\nexport async function runActionValidators<TBaseContext extends object>(input: {\n readonly action: ActionDefinition\n readonly subject: ActionSubject\n readonly baseContext: TBaseContext\n readonly target?: ActionTargetObject | null\n}): Promise<void> {\n const validators = input.action.phases.validate as readonly RuntimePhaseHandler[]\n if (validators.length === 0) {\n return\n }\n\n if (!isObjectActionDefinition(input.action)) {\n for (const validator of validators) {\n const result = await validator(input.baseContext)\n if (isValidatorErrorResult(result)) {\n throw validatorRejection(input, result.error)\n }\n }\n return\n }\n\n if (!input.target) {\n throw new Error(`[Sixb] Action '${input.action.id}' requires an object target.`)\n }\n\n for (const validator of validators) {\n const result = await validator({\n ...input.baseContext,\n target: input.target,\n })\n if (isValidatorErrorResult(result)) {\n throw validatorRejection(input, result.error)\n }\n }\n}\n\n/**\n * The run fails with `action.rejected` and this message, which the author wrote for the caller. A\n * thrown error's message stays private: it can come from anything the handler called.\n */\nfunction validatorRejection(\n input: { readonly action: ActionDefinition; readonly subject: ActionSubject },\n message: string\n): ActionValidationError {\n const rejection = new ActionValidationError(message, {\n actionId: input.action.id,\n subject: input.subject,\n })\n\n return withFailureMessage(rejection, message)\n}\n\nfunction isValidatorErrorResult(value: unknown): value is { readonly error: string } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"error\" in value &&\n typeof value.error === \"string\"\n )\n}\n",
19
+ "import { createHash } from \"node:crypto\"\nimport type { ObjectLink, ValueType } from \"../ontology\"\nimport { OntologyValidationError } from \"../ontology/errors\"\nimport type { ObjectTypeWithPropertyTokens } from \"../ontology/tokens\"\nimport { assertRequiredProperties } from \"../ontology/validation\"\nimport { EditBatchError } from \"./errors\"\nimport {\n assertPrimaryPropertyNotUpdated,\n getPrimaryProperty,\n normalizeEditablePropertyIds,\n normalizeLinkEditProperties,\n normalizeObjectEditProperties,\n} from \"./properties\"\nimport type {\n EditBatch,\n EditObjectHandle,\n EditObjectProperties,\n EditObjectRef,\n EditOperation,\n RecordEditsContext,\n RecordEditsHandler,\n RecordEditsOptions,\n} from \"./types\"\n\nexport type { RecordEditsHandler, RecordEditsOptions } from \"./types\"\n\nconst EMPTY_VALUE_TYPES = new Map<string, ValueType>()\n\ntype RuntimeEditRecorder = {\n readonly objects: (objectType: ObjectTypeWithPropertyTokens) => unknown\n toEditBatch(): EditBatch\n}\n\nexport async function recordEdits(\n options: RecordEditsOptions,\n handler: RecordEditsHandler\n): Promise<EditBatch> {\n const recorder = createEditRecorder(options)\n await handler({ objects: recorder.objects } as RecordEditsContext)\n return recorder.toEditBatch()\n}\n\nfunction createEditRecorder(options: RecordEditsOptions): RuntimeEditRecorder {\n if (!options.runId.trim()) {\n throw new EditBatchError(\"[Sixb] recordEdits requires a non-empty runId.\")\n }\n\n const operations: EditOperation[] = []\n const valueTypesById = options.valueTypesById ?? EMPTY_VALUE_TYPES\n\n function objects(objectType: ObjectTypeWithPropertyTokens) {\n return {\n byId(primaryId: string) {\n return createObjectHandle(objectType, createRef(objectType.id, primaryId))\n },\n\n create(properties: unknown) {\n const operationPath = String(operations.length)\n const primaryProperty = getPrimaryProperty(objectType)\n const rawProperties = assertRecord(properties, `${objectType.id}.create.properties`)\n const primaryValue =\n rawProperties[primaryProperty.id] ??\n generatePrimaryId({\n runId: options.runId,\n operationPath,\n objectTypeId: objectType.id,\n })\n\n if (typeof primaryValue !== \"string\" || !primaryValue.trim()) {\n throw new EditBatchError(\n `[Sixb] EditBatch create '${objectType.id}' primary property '${primaryProperty.id}' must be a non-empty string.`\n )\n }\n\n const normalizedProperties = normalizeObjectEditProperties({\n objectType,\n properties: {\n ...rawProperties,\n [primaryProperty.id]: primaryValue,\n },\n valueTypesById,\n path: `${objectType.id}.create`,\n })\n assertRequiredProperties(objectType, normalizedProperties)\n\n operations.push({\n kind: \"object.create\",\n objectTypeId: objectType.id,\n primaryId: primaryValue,\n properties: withoutPrimaryProperty(normalizedProperties, primaryProperty.id),\n })\n return createObjectHandle(objectType, {\n objectTypeId: objectType.id,\n primaryId: primaryValue,\n })\n },\n }\n }\n\n function toEditBatch(): EditBatch {\n return { operations: [...operations] }\n }\n\n function createObjectHandle(\n objectType: ObjectTypeWithPropertyTokens,\n ref: EditObjectRef\n ): EditObjectHandle<ObjectTypeWithPropertyTokens> {\n const handle = {\n objectTypeId: ref.objectTypeId,\n primaryId: ref.primaryId,\n }\n\n Object.defineProperties(handle, {\n objectType: {\n value: objectType,\n },\n update: {\n value(properties: Readonly<Record<string, unknown>>) {\n const normalizedProperties = normalizeObjectEditProperties({\n objectType,\n properties: assertRecord(properties, `${objectType.id}.update.properties`),\n valueTypesById,\n path: `${objectType.id}.update`,\n })\n assertPrimaryPropertyNotUpdated(objectType, normalizedProperties)\n // An empty patch resolves to a null override and commits as `unchanged`, so a handler\n // that built its update conditionally would report a successful run that wrote nothing.\n if (Object.keys(normalizedProperties).length === 0) {\n throw new EditBatchError(\n `[Sixb] EditBatch update '${objectType.id}:${ref.primaryId}' must set at least one property.`\n )\n }\n\n operations.push({\n kind: \"object.update\",\n objectTypeId: ref.objectTypeId,\n primaryId: ref.primaryId,\n properties: normalizedProperties,\n })\n },\n },\n unset: {\n value(...propertyIds: readonly unknown[]) {\n operations.push({\n kind: \"object.unset\",\n objectTypeId: ref.objectTypeId,\n primaryId: ref.primaryId,\n propertyIds: normalizeEditablePropertyIds({\n objectType,\n propertyIds,\n operation: \"unset\",\n }),\n })\n },\n },\n reset: {\n value(...propertyIds: readonly unknown[]) {\n operations.push({\n kind: \"object.reset\",\n objectTypeId: ref.objectTypeId,\n primaryId: ref.primaryId,\n propertyIds: normalizeEditablePropertyIds({\n objectType,\n propertyIds,\n operation: \"reset\",\n }),\n })\n },\n },\n delete: {\n value() {\n operations.push({\n kind: \"object.delete\",\n objectTypeId: ref.objectTypeId,\n primaryId: ref.primaryId,\n })\n },\n },\n restore: {\n value() {\n operations.push({\n kind: \"object.restore\",\n objectTypeId: ref.objectTypeId,\n primaryId: ref.primaryId,\n })\n },\n },\n link: {\n value(\n link: { objectTypeId: string; id: string; link: ObjectLink },\n target: EditObjectRef,\n linkOptions?: { readonly properties?: Readonly<Record<string, unknown>> }\n ) {\n assertLinkTokenSource(ref, link)\n\n const properties =\n linkOptions?.properties === undefined\n ? undefined\n : normalizeLinkEditProperties({\n sourceObjectTypeId: ref.objectTypeId,\n linkId: link.id,\n linkDefinition: link.link,\n properties: linkOptions.properties,\n valueTypesById,\n })\n\n operations.push({\n kind: \"link.upsert\",\n source: toPlainRef(ref),\n linkId: link.id,\n target: toPlainRef(target),\n ...(properties !== undefined ? { properties } : {}),\n })\n },\n },\n unlink: {\n value(link: { objectTypeId: string; id: string; link: ObjectLink }, target: EditObjectRef) {\n assertLinkTokenSource(ref, link)\n\n operations.push({\n kind: \"link.delete\",\n source: toPlainRef(ref),\n linkId: link.id,\n target: toPlainRef(target),\n })\n },\n },\n resetLink: {\n value(link: { objectTypeId: string; id: string; link: ObjectLink }, target: EditObjectRef) {\n assertLinkTokenSource(ref, link)\n\n operations.push({\n kind: \"link.reset\",\n source: toPlainRef(ref),\n linkId: link.id,\n target: toPlainRef(target),\n })\n },\n },\n })\n\n return handle as EditObjectHandle<ObjectTypeWithPropertyTokens>\n }\n\n return {\n objects,\n toEditBatch,\n }\n}\n\nfunction assertLinkTokenSource(\n source: EditObjectRef,\n link: { readonly objectTypeId: string; readonly id: string }\n): void {\n if (source.objectTypeId !== link.objectTypeId) {\n throw new OntologyValidationError(\n `[Sixb] Link token ${link.objectTypeId}.${link.id} cannot be used with ${source.objectTypeId}`\n )\n }\n}\n\nfunction createRef<TObjectTypeId extends string>(\n objectTypeId: TObjectTypeId,\n primaryId: string\n): EditObjectRef<TObjectTypeId> {\n return {\n objectTypeId: assertNonEmptyString(objectTypeId, \"objectTypeId\") as TObjectTypeId,\n primaryId: assertNonEmptyString(primaryId, `${objectTypeId}.primaryId`),\n }\n}\n\nfunction generatePrimaryId(params: {\n readonly runId: string\n readonly operationPath: string\n readonly objectTypeId: string\n}): string {\n const hash = createHash(\"sha256\")\n .update(`${params.runId}:${params.operationPath}:${params.objectTypeId}`)\n .digest(\"hex\")\n .slice(0, 24)\n return `edit_${hash}`\n}\n\n/** Primary identity lives in the object ref; managed authority never stores it as a property. */\nfunction withoutPrimaryProperty(\n properties: EditObjectProperties,\n primaryPropertyId: string\n): EditObjectProperties {\n const { [primaryPropertyId]: _primary, ...rest } = properties\n return rest\n}\n\nfunction assertRecord(value: unknown, label: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new EditBatchError(`[Sixb] EditBatch ${label} must be an object.`)\n }\n return value as Record<string, unknown>\n}\n\nfunction assertNonEmptyString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !value.trim()) {\n throw new EditBatchError(`[Sixb] EditBatch ${label} must be a non-empty string.`)\n }\n return value\n}\n\nfunction toPlainRef(ref: EditObjectRef): EditObjectRef {\n return {\n objectTypeId: ref.objectTypeId,\n primaryId: ref.primaryId,\n }\n}\n",
20
+ "import type { ObjectLink, Property, ValueType } from \"../ontology\"\nimport { OntologyValidationError } from \"../ontology/errors\"\nimport type { ObjectTypeWithPropertyTokens } from \"../ontology/tokens\"\nimport {\n assertKnownProperties,\n assertValidFileRefs,\n normalizeObjectProperties,\n validateObjectProperties,\n validatePropertyValue,\n} from \"../ontology/validation\"\nimport { EditBatchError } from \"./errors\"\nimport type { EditObjectProperties } from \"./types\"\n\nexport function normalizeObjectEditProperties(params: {\n readonly objectType: ObjectTypeWithPropertyTokens\n readonly properties: Record<string, unknown>\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n readonly path: string\n}): EditObjectProperties {\n const { objectType, properties, valueTypesById, path } = params\n assertKnownProperties(objectType, properties)\n assertNoTelemetryProperties(objectType.properties, properties, path)\n validateObjectProperties(objectType, properties, valueTypesById)\n assertValidFileRefs(properties, objectType.id)\n return normalizeObjectProperties(objectType.properties, properties, valueTypesById, path)\n}\n\nexport function normalizeLinkEditProperties(params: {\n readonly sourceObjectTypeId: string\n readonly linkId: string\n readonly linkDefinition: ObjectLink\n readonly properties: Readonly<Record<string, unknown>>\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): EditObjectProperties {\n const { sourceObjectTypeId, linkId, linkDefinition, properties, valueTypesById } = params\n const linkProperties = linkDefinition.properties ?? []\n\n if (linkProperties.length === 0 && Object.keys(properties).length > 0) {\n throw new OntologyValidationError(\n `[Sixb] Link ${sourceObjectTypeId}.${linkId} does not define link properties`\n )\n }\n\n const knownPropertyIds = new Set(linkProperties.map((property) => property.id))\n for (const propertyId of Object.keys(properties)) {\n if (!knownPropertyIds.has(propertyId)) {\n throw new OntologyValidationError(\n `[Sixb] Unknown link property '${propertyId}' for link '${sourceObjectTypeId}.${linkId}'`\n )\n }\n }\n\n assertNoTelemetryProperties(linkProperties, properties, `${sourceObjectTypeId}.${linkId}`)\n\n for (const [propertyId, value] of Object.entries(properties)) {\n const property = linkProperties.find((candidate) => candidate.id === propertyId)\n if (!property) continue\n validatePropertyValue(\n property,\n value,\n `${sourceObjectTypeId}.${linkId}.${propertyId}`,\n valueTypesById\n )\n }\n assertValidFileRefs(properties, `${sourceObjectTypeId}.${linkId}`)\n\n return normalizeObjectProperties(\n linkProperties,\n properties,\n valueTypesById,\n `${sourceObjectTypeId}.${linkId}`\n )\n}\n\nexport function getPrimaryProperty(objectType: ObjectTypeWithPropertyTokens): Property {\n const primaryProperty = objectType.properties.find((property) => property.primary)\n if (!primaryProperty) {\n throw new OntologyValidationError(\n `[Sixb] Object type '${objectType.id}' has no primary property`\n )\n }\n return primaryProperty\n}\n\nexport function assertPrimaryPropertyNotUpdated(\n objectType: ObjectTypeWithPropertyTokens,\n properties: EditObjectProperties\n): void {\n const primaryProperty = getPrimaryProperty(objectType)\n if (Object.hasOwn(properties, primaryProperty.id)) {\n throw new EditBatchError(\n `[Sixb] EditBatch cannot update primary property '${objectType.id}.${primaryProperty.id}'.`\n )\n }\n}\n\n/** Validates `unset`/`reset` targets: known, non-primary, and not telemetry-backed. */\nexport function normalizeEditablePropertyIds(params: {\n readonly objectType: ObjectTypeWithPropertyTokens\n readonly propertyIds: readonly unknown[]\n readonly operation: \"unset\" | \"reset\"\n}): readonly string[] {\n const { objectType, propertyIds, operation } = params\n const primaryProperty = getPrimaryProperty(objectType)\n const normalized: string[] = []\n const seen = new Set<string>()\n\n for (const propertyId of propertyIds) {\n if (typeof propertyId !== \"string\" || !propertyId.trim()) {\n throw new EditBatchError(\n `[Sixb] EditBatch ${objectType.id}.${operation} property id must be a non-empty string.`\n )\n }\n const property = objectType.properties.find((candidate) => candidate.id === propertyId)\n if (!property) {\n throw new EditBatchError(\n `[Sixb] EditBatch ${operation} references unknown property '${objectType.id}.${propertyId}'.`\n )\n }\n if (property.id === primaryProperty.id) {\n throw new EditBatchError(\n `[Sixb] EditBatch cannot ${operation} primary property '${objectType.id}.${propertyId}'.`\n )\n }\n if (property.mode === \"telemetry\") {\n throw new EditBatchError(\n `[Sixb] EditBatch cannot ${operation} telemetry property '${objectType.id}.${propertyId}'.`\n )\n }\n if (seen.has(propertyId)) continue\n seen.add(propertyId)\n normalized.push(propertyId)\n }\n\n if (normalized.length === 0) {\n throw new EditBatchError(\n `[Sixb] EditBatch ${objectType.id}.${operation} requires at least one property id.`\n )\n }\n return normalized\n}\n\nfunction assertNoTelemetryProperties(\n definitions: readonly Property[],\n properties: Readonly<Record<string, unknown>>,\n path: string\n): void {\n for (const propertyId of Object.keys(properties)) {\n const property = definitions.find((candidate) => candidate.id === propertyId)\n if (property?.mode === \"telemetry\") {\n throw new EditBatchError(\n `[Sixb] EditBatch cannot edit telemetry property '${path}.${propertyId}' in the MVP.`\n )\n }\n }\n}\n",
21
+ "import type { EditBatch } from \"../edits\"\nimport { lowerEditBatch } from \"../edits\"\nimport type {\n EditCommitResult,\n EffectiveLinkChange,\n EffectiveObjectChange,\n ExpectedLinkRevision,\n ExpectedLinkScopeRevision,\n ExpectedObjectRevision,\n OntologyOperationOutcome,\n} from \"../materializer\"\nimport type { OntologyMutationRuntime } from \"../runtime/ontology-mutations\"\nimport type { RecordActionRunInput, UniqueValueRef } from \"../storage\"\n\n/** Exact reads an Action handler depended on, protected by row-level CAS at commit time. */\nexport interface ActionReadDependencies {\n readonly objects: readonly ExpectedObjectRevision[]\n readonly links: readonly ExpectedLinkRevision[]\n readonly linkScopes: readonly ExpectedLinkScopeRevision[]\n /** Unique values a lookup found no object holding. */\n readonly unclaimedValues?: readonly UniqueValueRef[]\n}\n\nconst NO_READ_DEPENDENCIES: ActionReadDependencies = { objects: [], links: [], linkScopes: [] }\n\nexport interface CommitActionEditsInput {\n readonly mutations: Pick<OntologyMutationRuntime, \"commitEdits\">\n /** The run's terminal record, which the commit inserts with its edits. */\n readonly run: RecordActionRunInput\n readonly batch: EditBatch\n readonly dependencies?: ActionReadDependencies\n}\n\n/** The authoritative ontology commit an Action run produced. */\nexport interface ActionEditCommitResult {\n readonly commitId: string\n readonly created: boolean\n readonly eventCount: number\n readonly outcomes: readonly OntologyOperationOutcome[]\n readonly changes: {\n readonly objects: readonly EffectiveObjectChange[]\n readonly links: readonly EffectiveLinkChange[]\n }\n readonly committedAt: Date\n}\n\n/**\n * Commits one Action run's recorded edits as a single atomic ontology commit.\n *\n * The batch lowers to canonical Materializer operations and the Materializer validates the Action run\n * identity, applies managed authority, resolves effective state, writes the authoritative commit,\n * inserts outbox facts, and records the run in one transaction. Repeating the call for the same run\n * replays that commit without recording anything; a divergent request for the same run is a typed\n * idempotency conflict.\n */\nexport async function commitActionEdits(\n input: CommitActionEditsInput\n): Promise<ActionEditCommitResult> {\n const dependencies = input.dependencies ?? NO_READ_DEPENDENCIES\n const commit = await input.mutations.commitEdits({\n mode: \"atomic\",\n source: { kind: \"action\", actionId: input.run.actionId, runId: input.run.id },\n run: input.run,\n operations: lowerEditBatch(input.batch),\n expectedObjects: dependencies.objects,\n expectedLinks: dependencies.links,\n expectedLinkScopes: dependencies.linkScopes,\n ...(dependencies.unclaimedValues?.length\n ? { expectedUnclaimedValues: dependencies.unclaimedValues }\n : {}),\n })\n return toActionEditCommitResult(commit)\n}\n\nfunction toActionEditCommitResult(commit: EditCommitResult): ActionEditCommitResult {\n return {\n commitId: commit.commitId,\n created: commit.created,\n eventCount: commit.eventCount,\n outcomes: commit.outcomes,\n changes: commit.changes,\n committedAt: new Date(commit.committedAt),\n }\n}\n",
22
+ "import { recordEdits } from \"../../edits/recorder\"\nimport type { RecordActionRunInput } from \"../../storage\"\nimport type { ActionEditCommitResult } from \"../commit-edits\"\nimport { commitActionEdits } from \"../commit-edits\"\nimport type { ActionReadRecorder } from \"../read-facade\"\nimport { isObjectActionDefinition } from \"../validation\"\nimport { type BasePhaseContext, requireObjectSubject, toActionReadFacade } from \"./context\"\nimport { throwIfAborted, translateActionPhaseError, untilAborted } from \"./normalize\"\nimport type { LoadedObjectTarget, PhaseExecutionBase, RuntimePhaseHandler } from \"./phase-types\"\nimport type { ActionRunState } from \"./state\"\n\n/** The commit of a run's edits, which recorded the run with them. */\nexport interface CommittedActionRun {\n readonly record: RecordActionRunInput\n readonly commit: ActionEditCommitResult\n}\n\n/**\n * Records the run's edits and commits them through the ontology Materializer, together with the\n * run's terminal record. Resolves with `null` for an Action without edits, which commits nothing.\n *\n * Object and link-scope reads performed by the writeback and edits handlers, including every object\n * a query or listing returned, are captured as expected revisions so a commit fails when that state\n * changes. Query membership and telemetry history stay call-level snapshots. Domain events are\n * durable outbox facts written inside the commit, so this phase never appends events itself.\n *\n * `signal` stops the edits handler and the step before the commit; the commit itself is never\n * interrupted.\n */\nexport async function runEditsAndCommitPhase(\n input: PhaseExecutionBase & {\n readonly state: ActionRunState\n readonly baseContext: BasePhaseContext\n readonly objectTarget: LoadedObjectTarget | null\n /** Shared with the writeback phase so both phases' reads fence the same commit. */\n readonly reads: ActionReadRecorder\n }\n): Promise<CommittedActionRun | null> {\n const handler = input.action.phases.edits as RuntimePhaseHandler | undefined\n if (!handler) return null\n\n const { state } = input\n const ids = { actionId: input.action.id, runId: state.run.id }\n state.enter(\"edits\")\n\n const reads = input.reads\n if (input.objectTarget) {\n reads.observeObject(\n {\n objectTypeId: input.objectTarget.row.objectTypeId,\n primaryId: input.objectTarget.row.primaryId,\n },\n input.objectTarget.row\n )\n }\n\n let batch: Awaited<ReturnType<typeof recordEdits>>\n try {\n batch = await recordEdits(\n {\n runId: state.run.id,\n valueTypesById: input.runtime.sixb.objects.getValueTypesById(),\n },\n async ({ objects }) => {\n const baseContext = {\n ...input.baseContext,\n signal: input.signal,\n objects,\n read: toActionReadFacade(input.runtime, reads),\n writeback: state.writebackValue,\n }\n\n const subject = isObjectActionDefinition(input.action)\n ? { subject: requireObjectSubject(state.run.subject, ids) }\n : {}\n await untilAborted(async () => handler({ ...baseContext, ...subject }), input.signal)\n }\n )\n } catch (error) {\n throw translateActionPhaseError(error, \"edits\", { ...ids, signal: input.signal })\n }\n\n throwIfAborted(input.signal)\n state.enter(\"commit\")\n // Built as the commit starts: the run succeeds exactly when this commit does.\n const record = state.succeeded()\n\n let commit: ActionEditCommitResult\n try {\n commit = await commitActionEdits({\n mutations: input.runtime.ontologyMutations,\n run: record,\n batch,\n dependencies: reads.dependencies(),\n })\n } catch (error) {\n // The commit ran to its end whatever `signal` did meanwhile, so its error is never a timeout.\n throw translateActionPhaseError(error, \"commit\", ids)\n }\n\n return { record, commit }\n}\n",
23
+ "import type { JsonValue } from \"../../json\"\nimport { assertJsonValue, cloneJsonValue } from \"../../json\"\nimport type { ActionReadRecorder } from \"../read-facade\"\nimport { isObjectActionDefinition } from \"../validation\"\nimport {\n type BasePhaseContext,\n requireObjectTarget,\n toActionReadFacade,\n toActionRuntimeFacade,\n} from \"./context\"\nimport { toActionRunFailure, translateActionPhaseError } from \"./normalize\"\nimport type { LoadedObjectTarget, PhaseExecutionBase, RuntimePhaseHandler } from \"./phase-types\"\nimport type { ActionRunState } from \"./state\"\n\n/**\n * Calls the Action's writeback, when it has one, and keeps how it ended on the run's state.\n *\n * A failed writeback fails the run with the writeback's own failure; a succeeded one is the run's\n * irreversible boundary.\n */\nexport async function runWritebackPhase(\n input: PhaseExecutionBase & {\n readonly state: ActionRunState\n readonly baseContext: BasePhaseContext\n readonly objectTarget: LoadedObjectTarget | null\n readonly reads: ActionReadRecorder\n }\n): Promise<void> {\n const handler = input.action.phases.writeback as RuntimePhaseHandler | undefined\n if (!handler) return\n\n const { state } = input\n const ids = { actionId: input.action.id, runId: state.run.id }\n state.enter(\"writeback\")\n\n let result: JsonValue\n try {\n // Reads are side-effect-free, so the writeback phase can safely enrich its external payload\n // before the edit batch exists. Object, link-scope, and returned query/list rows share the\n // edits phase's recorder and are fenced by the same CAS. Query membership and telemetry\n // history remain call-level snapshots.\n const context = {\n ...input.baseContext,\n signal: input.signal,\n sixb: toActionRuntimeFacade(input.runtime),\n read: toActionReadFacade(input.runtime, input.reads),\n }\n const rawResult = isObjectActionDefinition(input.action)\n ? await handler({\n ...context,\n target: requireObjectTarget(input.objectTarget, ids).snapshot,\n })\n : await handler(context)\n result = normalizeWritebackResult(rawResult)\n } catch (error) {\n const completedAt = new Date()\n const phaseError = translateActionPhaseError(error, \"writeback\", {\n ...ids,\n signal: input.signal,\n })\n state.recordWriteback({\n status: \"failed\",\n completedAt,\n error: toActionRunFailure(phaseError, \"writeback\", { ...ids, at: completedAt }),\n })\n throw error\n }\n\n state.recordWriteback({ status: \"succeeded\", completedAt: new Date(), result })\n}\n\nfunction normalizeWritebackResult(result: unknown): JsonValue {\n if (result === undefined) {\n return null\n }\n\n assertJsonValue(result, \"Action writeback result\")\n return cloneJsonValue(result)\n}\n",
24
+ "import { isSixbError } from \"../../errors/internal\"\nimport { resolveLoggingService } from \"../../logging/service\"\nimport { ActionReadRecorder } from \"../read-facade\"\nimport type { ActionDefinition } from \"../types\"\nimport { isObjectActionDefinition } from \"../validation\"\nimport { runActionValidators } from \"../validators\"\nimport { createBasePhaseContext, loadObjectTarget } from \"./context\"\nimport { type CommittedActionRun, runEditsAndCommitPhase } from \"./edits-commit\"\nimport { throwIfAborted, translateActionPhaseError, untilAborted } from \"./normalize\"\nimport type { ActionRunSignals } from \"./signals\"\nimport type { ActionRunState } from \"./state\"\nimport type { ActionRunContext } from \"./types\"\nimport { runWritebackPhase } from \"./writeback\"\n\n/** Commits a run attempts before a read conflict fails it. */\nconst MAX_COMMIT_ATTEMPTS = 3\n\ntype LogSession = ReturnType<ReturnType<typeof resolveLoggingService>[\"startExecution\"]>\n\ninterface PhasesInput {\n readonly runtime: ActionRunContext\n readonly action: ActionDefinition\n readonly state: ActionRunState\n readonly signals: ActionRunSignals\n}\n\n/**\n * Run the phases up to the commit, keeping what they do on the run's state.\n *\n * Resolves with the commit, which recorded the run, for an Action with edits; and with `null` for\n * one without, whose run is still to record. Rejects when a phase fails.\n */\nexport async function executeActionPhases(input: PhasesInput): Promise<CommittedActionRun | null> {\n const logSession = resolveLoggingService(input.runtime.id, input.runtime.logging).startExecution({\n kind: \"action\",\n id: input.state.run.id,\n })\n\n try {\n return await commitWithReplay({ ...input, logSession })\n } finally {\n await logSession.flush()\n }\n}\n\n/**\n * Runs the phases up to the commit, and replays them when the commit hits a read conflict.\n *\n * Before the boundary nothing irreversible happened, so the run restarts from validation against\n * current state while its deadline allows. After a succeeded writeback only edits and commit replay,\n * with the same writeback value: the external change happened, and the ontology must still record\n * it.\n */\nasync function commitWithReplay(\n input: PhasesInput & { readonly logSession: LogSession }\n): Promise<CommittedActionRun | null> {\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await commitOnce(input)\n } catch (error) {\n const replayable =\n isReadConflict(error) &&\n attempt < MAX_COMMIT_ATTEMPTS &&\n (hasSucceededWriteback(input.state) || !input.signals.beforeBoundary.aborted)\n if (!replayable) throw error\n }\n }\n}\n\nasync function commitOnce(\n input: PhasesInput & { readonly logSession: LogSession }\n): Promise<CommittedActionRun | null> {\n const { runtime, action, state, signals, logSession } = input\n const ids = { actionId: action.id, runId: state.run.id }\n const replayingEdits = hasSucceededWriteback(state)\n const signal = replayingEdits ? signals.uninterruptible : signals.beforeBoundary\n\n throwIfAborted(signal)\n // A replay starts over from the phase it repeats: what fails from here on failed there, not in\n // the commit the previous attempt reached.\n state.enter(replayingEdits ? \"edits\" : \"validation\")\n\n // Each attempt reads afresh, the subject included: a replay must observe the state that made the\n // previous commit conflict, and fence the commit against that state alone.\n const reads = new ActionReadRecorder()\n let objectTarget: Awaited<ReturnType<typeof loadObjectTarget>>\n try {\n objectTarget = await loadObjectTarget({ runtime, action, run: state.run })\n } catch (error) {\n // The subject changed while its requester's view of it was read: replay as a commit would.\n if (isReadConflict(error)) throw error\n throw translateActionPhaseError(error, replayingEdits ? \"edits\" : \"validation\", {\n ...ids,\n signal,\n })\n }\n const baseContext = createBasePhaseContext({\n runtime,\n action,\n state,\n logger: logSession.withContext({ phase: \"validation\" }),\n })\n\n if (!replayingEdits) {\n try {\n await untilAborted(\n () =>\n runActionValidators({\n action,\n subject: state.run.subject,\n baseContext: { ...baseContext, signal },\n target: isObjectActionDefinition(action) ? objectTarget?.snapshot : undefined,\n }),\n signal\n )\n } catch (error) {\n throw translateActionPhaseError(error, \"validation\", { ...ids, signal })\n }\n\n throwIfAborted(signal)\n await runWritebackPhase({\n runtime,\n action,\n state,\n signal,\n baseContext: { ...baseContext, logger: logSession.withContext({ phase: \"writeback\" }) },\n objectTarget,\n reads,\n })\n }\n\n // A succeeded writeback is the boundary: from here on, edits and commit always finish.\n const editsSignal = hasSucceededWriteback(state) ? signals.uninterruptible : signal\n throwIfAborted(editsSignal)\n return runEditsAndCommitPhase({\n runtime,\n action,\n state,\n signal: editsSignal,\n baseContext: { ...baseContext, logger: logSession.withContext({ phase: \"edits\" }) },\n objectTarget,\n reads,\n })\n}\n\nfunction hasSucceededWriteback(state: ActionRunState): boolean {\n return state.writeback?.status === \"succeeded\"\n}\n\nfunction isReadConflict(error: unknown): boolean {\n return isSixbError(error) && error.code === \"action.read_conflict\"\n}\n",
25
+ "import type { JsonValue } from \"../../json\"\nimport type {\n ActionRunFailure,\n ActionRunPhase,\n ActionRunWritebackRecord,\n RecordActionRunInput,\n} from \"../../storage\"\nimport type { PendingActionRun } from \"./types\"\n\nexport type SucceededActionRunRecord = Extract<\n RecordActionRunInput,\n { readonly status: \"succeeded\" }\n>\nexport type FailedActionRunRecord = Extract<RecordActionRunInput, { readonly status: \"failed\" }>\n\n/**\n * What a run has done so far: the phase it reached and how its writeback ended.\n *\n * It lives in memory while the run executes, and nothing about the run is stored before it ends:\n * its terminal record is built from this state once, when it succeeds or fails.\n */\nexport class ActionRunState {\n private reached: ActionRunPhase = \"validation\"\n private writebackRecord: ActionRunWritebackRecord | undefined\n\n constructor(\n readonly run: PendingActionRun,\n /** When the run started executing, as its handlers and its record see it. */\n readonly startedAt: Date\n ) {}\n\n /** The last phase the run reached. */\n get phase(): ActionRunPhase {\n return this.reached\n }\n\n get writeback(): ActionRunWritebackRecord | undefined {\n return this.writebackRecord\n }\n\n /** The value a succeeded writeback returned, which edits and effects receive. */\n get writebackValue(): JsonValue | undefined {\n return this.writebackRecord?.status === \"succeeded\" ? this.writebackRecord.result : undefined\n }\n\n /**\n * Whether the run's deadline and caller no longer apply to it.\n *\n * True once its writeback succeeded, or once its commit started for an Action without one: from\n * there the run either commits or fails on its own merits.\n */\n get pastBoundary(): boolean {\n return this.writebackRecord?.status === \"succeeded\" || this.reached === \"commit\"\n }\n\n /** Enter a phase before the commit. The run is recorded before its effects run. */\n enter(phase: Exclude<ActionRunPhase, \"effects\">): void {\n this.reached = phase\n }\n\n /** Keep how the writeback ended. A run calls its writeback once, so this is set once. */\n recordWriteback(writeback: ActionRunWritebackRecord): void {\n if (this.writebackRecord) {\n throw new Error(`[Sixb] Action run '${this.run.id}' already ended its writeback.`)\n }\n this.writebackRecord = writeback\n }\n\n /** The record of the run succeeding in the phase it reached. */\n succeeded(finishedAt: Date = new Date()): SucceededActionRunRecord {\n return { ...this.recordFields(this.reached, finishedAt), status: \"succeeded\" }\n }\n\n /** The record of the run failing with `error`, in the phase the failure names. */\n failed(error: ActionRunFailure, finishedAt: Date = new Date()): FailedActionRunRecord {\n return { ...this.recordFields(error.details.phase, finishedAt), status: \"failed\", error }\n }\n\n private recordFields(phase: ActionRunPhase, finishedAt: Date) {\n const { id, projectId, executionId, actionId, subject, params, idempotencyKey } = this.run\n return {\n id,\n projectId,\n executionId,\n actionId,\n subject,\n params,\n idempotencyKey,\n phase,\n startedAt: this.startedAt,\n finishedAt,\n ...(this.writebackRecord === undefined ? {} : { writeback: this.writebackRecord }),\n }\n }\n}\n",
26
+ "import { reportRunFailure } from \"../../error-reporting/capability\"\nimport { createSixbError } from \"../../errors/internal\"\nimport type { ActionRunFailure, RecordActionRunInput } from \"../../storage\"\nimport { ActionRunError } from \"../../storage\"\nimport type { CommittedActionRun } from \"./edits-commit\"\nimport { runActionEffects } from \"./effects\"\nimport { isActionPhaseFailure, toActionRunFailure, unwrapActionPhaseError } from \"./normalize\"\nimport { executeActionPhases } from \"./phases\"\nimport type { ActionRunSignals } from \"./signals\"\nimport { ActionRunState, type FailedActionRunRecord } from \"./state\"\nimport type { ActionRunContext, ActionRunOutcome, RunActionInput } from \"./types\"\n\n/**\n * A run that ended, but whose terminal record could not be written.\n *\n * It carries that record, so that whoever reports this error still reports how the run ended. Its\n * cause is the error that kept the record from being written.\n */\nexport class UnrecordedActionRunError extends Error {\n override readonly name = \"UnrecordedActionRunError\"\n\n constructor(\n readonly record: RecordActionRunInput,\n options: { readonly cause: unknown }\n ) {\n super(`[Sixb] Action run '${record.id}' ended, but its record could not be written.`, options)\n }\n}\n\n/**\n * Execute a requested run to its end, and record it once.\n *\n * A run with edits is recorded by the commit of its edits; any other run, succeeded or failed, is\n * recorded as soon as it ends. The run's effects are left to the caller to start: see\n * {@link ActionRunOutcome.effects}. This rejects when the run cannot execute here, or with an\n * {@link UnrecordedActionRunError} when its record cannot be written.\n */\nexport async function runAction(input: RunActionInput): Promise<ActionRunOutcome> {\n const { runtime, run, signals } = input\n const ids = { actionId: run.actionId, runId: run.id }\n\n if (run.projectId !== runtime.id) {\n throw createSixbError(\n \"internal.unexpected\",\n `[Sixb] Action run '${run.id}' belongs to project '${run.projectId}', not '${runtime.id}'.`,\n { details: { ...ids, durableProjectId: run.projectId } }\n )\n }\n\n const state = new ActionRunState(run, new Date())\n const action = runtime.actions.getById(run.actionId)\n if (!action) {\n const message = `[Sixb] Unknown action '${run.actionId}'.`\n const error = createSixbError(\"internal.unexpected\", message, { details: ids })\n const failure = toActionRunFailure(error, \"validation\", { ...ids, at: new Date() })\n return recordFailure(runtime, state.failed(failure), error)\n }\n\n let committed: CommittedActionRun | null\n try {\n committed = await executeActionPhases({ runtime, action, state, signals })\n } catch (error) {\n return recordFailure(runtime, state.failed(runFailure(error, state, signals)), error)\n }\n\n if (!committed) return recordRun(runtime, state.succeeded())\n // A commit that already existed recorded the run with it, for another request.\n if (!committed.commit.created) return findRecordedRun(runtime, committed.record)\n const { commit } = committed\n return {\n record: committed.record,\n recorded: true,\n ...(action.phases.effects\n ? {\n effects: () =>\n runActionEffects({\n runtime,\n action,\n state,\n commit,\n startDeadline: () => signals.startEffects(),\n }),\n }\n : {}),\n }\n}\n\n/**\n * The failure a run that threw records.\n *\n * A failed writeback fails the run with the writeback's own failure. Otherwise, only a run stopped\n * before its boundary is the caller's or the deadline's doing. Past it, or when a phase classified\n * its error before anything aborted, the run failed on its own merits.\n */\nfunction runFailure(\n error: unknown,\n state: ActionRunState,\n signals: ActionRunSignals\n): ActionRunFailure {\n if (state.writeback?.status === \"failed\") return state.writeback.error\n const stopped =\n !state.pastBoundary && signals.beforeBoundary.aborted && !isActionPhaseFailure(error)\n return toActionRunFailure(stopped ? signals.stopReason() : error, state.phase, {\n actionId: state.run.actionId,\n runId: state.run.id,\n at: new Date(),\n })\n}\n\n/**\n * Failures that are not the run's own: its caller cancelled it, or a validator rejected the request,\n * which is a business outcome the caller reads on the run.\n */\nconst UNREPORTED_FAILURE_CODES: ReadonlySet<string> = new Set([\n \"runtime.cancelled\",\n \"action.rejected\",\n])\n\n/**\n * Record a failed run, and report its failure to `onError` once this request recorded it, unless\n * it is one of the {@link UNREPORTED_FAILURE_CODES}.\n */\nasync function recordFailure(\n runtime: ActionRunContext,\n record: FailedActionRunRecord,\n error: unknown\n): Promise<ActionRunOutcome> {\n const outcome = await recordRun(runtime, record)\n if (outcome.recorded && !UNREPORTED_FAILURE_CODES.has(record.error.code)) {\n reportRunFailure(runtime.errorReporterHost, unwrapActionPhaseError(error), {\n projectId: runtime.id,\n runKind: \"action\",\n run: { runId: record.id, actionId: record.actionId },\n failure: record.error,\n })\n }\n return outcome\n}\n\n/**\n * Write a run's terminal record. A run id is recorded once: when a concurrent request for the same\n * run id recorded it first, with the same request, its record answers this one too.\n */\nasync function recordRun(\n runtime: ActionRunContext,\n record: RecordActionRunInput\n): Promise<ActionRunOutcome> {\n try {\n return { record: await runtime.actionRunsStorage.record(record), recorded: true }\n } catch (error) {\n if (error instanceof ActionRunError) return findRecordedRun(runtime, record, error)\n throw new UnrecordedActionRunError(record, { cause: error })\n }\n}\n\n/**\n * The record another request wrote for this run. Whether it answers this request is the request's\n * to decide, under the checks any record it finds gets.\n */\nasync function findRecordedRun(\n runtime: ActionRunContext,\n record: RecordActionRunInput,\n cause?: unknown\n): Promise<ActionRunOutcome> {\n try {\n const stored = await runtime.actionRunsStorage.getById({\n projectId: record.projectId,\n id: record.id,\n })\n if (!stored) {\n throw (\n cause ?? new ActionRunError(`[Sixb] Action run '${record.id}' committed without a record.`)\n )\n }\n return { record: stored, recorded: false }\n } catch (error) {\n throw new UnrecordedActionRunError(record, { cause: error })\n }\n}\n",
27
+ "import { createSixbError } from \"../../errors/internal\"\nimport {\n type BoundPrimitiveExecution,\n bindDurablePrimitiveExecution,\n type PrimitiveExecutionHost,\n} from \"../../execution/primitive\"\nimport type { LoggingService } from \"../../logging/service\"\nimport type { SixbDefinitions } from \"../../runtime/definitions\"\nimport type { ActionRunStorage, Storage } from \"../../storage\"\nimport type { ExecutionRecord } from \"../../storage/executions\"\nimport { runAction } from \"./run-action\"\nimport { ActionRunSignals } from \"./signals\"\nimport type {\n ActionRunContext,\n ActionRunOutcome,\n PendingActionRun,\n ReadSubjectAsRequester,\n} from \"./types\"\n\n/** What executing a stored Action run needs from its host. */\nexport interface ActionRunHost extends PrimitiveExecutionHost {\n readonly storage: Storage\n readonly logging?: LoggingService\n readonly definitions: Pick<SixbDefinitions, \"actions\">\n}\n\nexport interface ExecuteActionRunInput {\n readonly run: PendingActionRun\n /** The durable execution the run was requested under. */\n readonly execution: ExecutionRecord\n /** Cancels the run before its irreversible boundary. */\n readonly signal?: AbortSignal\n readonly readSubjectAsRequester?: ReadSubjectAsRequester\n}\n\n/**\n * The model-call attempt an Action run accounts under.\n *\n * Model accounting records every call against an execution attempt. A run executes once, in the\n * process that requested it, so it is always the first.\n */\nconst MODEL_EXECUTION_ATTEMPT = 1\n\n/**\n * Execute a requested Action run inside the durable execution it was requested under, and record it.\n *\n * Binds the Action's primitive scope to that execution, then runs the phases under the run's\n * deadline and the caller's signal. Its effects, when it has any, are left to start: see\n * {@link ActionRunOutcome.effects}.\n */\nexport async function executeActionRun(\n host: ActionRunHost,\n input: ExecuteActionRunInput\n): Promise<ActionRunOutcome> {\n const { run, execution } = input\n const actionRuns = requireActionRunStorage(host, run.id)\n const signals = new ActionRunSignals({\n actionId: run.actionId,\n runId: run.id,\n caller: input.signal,\n })\n\n try {\n const bound = bindDurablePrimitiveExecution(host, {\n // Model calls stop with their phase through the `signal` a handler forwards to them. Binding\n // the run's deadline here would also stop the embedding calls behind the vector reads that\n // edits make past the boundary, which must always finish.\n modelExecution: { attempt: MODEL_EXECUTION_ATTEMPT, signal: signals.uninterruptible },\n execution,\n primitive: { kind: \"action\", id: run.actionId, runId: run.id },\n })\n return await runAction({\n runtime: buildActionContext(host, actionRuns, bound, input.readSubjectAsRequester),\n run,\n signals,\n })\n } finally {\n signals.dispose()\n }\n}\n\nfunction requireActionRunStorage(host: ActionRunHost, runId: string): ActionRunStorage {\n const actionRuns = host.storage.actionRuns\n if (!actionRuns) {\n throw createSixbError(\n \"internal.unexpected\",\n \"[Sixb] Action execution requires storage.actionRuns support.\",\n { details: { runId } }\n )\n }\n return actionRuns\n}\n\nfunction buildActionContext(\n host: ActionRunHost,\n actionRunsStorage: ActionRunStorage,\n execution: BoundPrimitiveExecution,\n readSubjectAsRequester: ReadSubjectAsRequester | undefined\n): ActionRunContext {\n const sixb = {\n models: execution.sixb.models,\n objects: execution.sixb.objects,\n actions: execution.sixb.actions,\n connector: execution.sixb.connector,\n blobs: execution.sixb.blobs,\n users: execution.sixb.users,\n }\n return {\n id: host.id,\n errorReporterHost: host,\n logging: host.logging,\n storage: host.storage,\n actionRunsStorage,\n ontologyMutations: execution.ontologyMutations,\n sixb,\n actions: host.definitions.actions,\n requestedBy: execution.sixb.execution.requestedBy,\n ...(readSubjectAsRequester === undefined ? {} : { readSubjectAsRequester }),\n }\n}\n",
28
+ "import { reportRunFailure } from \"../../error-reporting/capability\"\nimport { createSixbError, type SixbCodedError } from \"../../errors/internal\"\nimport type { ActionRunRecord } from \"../../storage\"\nimport {\n type ActionRunRequestPayload,\n type AssertCanReuseActionRun,\n assertCanReuseActionRun,\n type PersistedActionRun,\n} from \"../run-persistence\"\nimport { type ActionRunHost, executeActionRun } from \"./execute\"\nimport { toActionRunFailure } from \"./normalize\"\nimport { UnrecordedActionRunError } from \"./run-action\"\nimport type { PendingActionRun, ReadSubjectAsRequester } from \"./types\"\n\n/** A request for an Action run, handed over to execute in the requesting process. */\nexport interface ActionRunRequest {\n readonly runId: string\n readonly payload: ActionRunRequestPayload\n /** Find the record of an earlier request with the same run id, or create the run's execution. */\n readonly persist: () => Promise<PersistedActionRun>\n /** Refuse a run that already exists under the run id, when this request's caller may not have it. */\n readonly assertCanReuse: AssertCanReuseActionRun\n /** Cancels the run before its irreversible boundary. */\n readonly signal?: AbortSignal\n /** Called once the run's execution exists, before the run executes. A throw starts nothing. */\n readonly onRequested?: (runId: string) => void | Promise<void>\n /** Set when the requester views the subject's type through a condition. */\n readonly readSubjectAsRequester?: ReadSubjectAsRequester\n}\n\ntype NewActionRun = Extract<PersistedActionRun, { readonly kind: \"new\" }>\n\n/** A request of this process that holds a run id, from before it looks the run id up. */\ninterface HeldRunId {\n /**\n * The run once its execution exists. It resolves with `null` when the request executes nothing,\n * having found a record or failed before, and the run id is released by then.\n */\n readonly pending: Promise<PendingActionRun | null>\n}\n\n/**\n * Runs requested Actions in the calling process, and tracks each request until its run is recorded\n * and its effects ended, so that a stopping process can wait for them.\n *\n * `SixbHost` registers one on itself and on the context its bound SDKs share, so a request can\n * execute its run without holding the host.\n */\nexport class ActionRunExecutor {\n private readonly inFlight = new Set<Promise<void>>()\n /** Run ids held by a request of this process, until it ends. */\n private readonly held = new Map<string, HeldRunId>()\n private stopping = false\n\n constructor(private readonly host: ActionRunHost) {}\n\n /**\n * Execute a requested run to its terminal record, or answer with the record of an earlier request\n * for the same run id.\n *\n * The request is tracked from before anything is persisted, so that {@link drain} waits for it\n * from the start. Once the process is stopping, a new request is refused before anything is\n * persisted. A request for a run id that this process is executing is refused as in progress:\n * see {@link joinHeldRunId}. A request for the same run id in another process executes too, and\n * the request that records it second answers with the first one's record, under the same checks\n * as any record it finds.\n *\n * Once the run's execution exists, the request either resolves with the run's record or rejects\n * with `internal.unexpected`: see {@link failRequest}.\n */\n request(request: ActionRunRequest): Promise<ActionRunRecord> {\n if (this.stopping) {\n return Promise.reject(\n createSixbError(\n \"runtime.stopping\",\n \"[Sixb] The runtime is stopping and starts no new Action run; retry the request.\"\n )\n )\n }\n const requested = this.dispatch(request)\n this.track(requested)\n return requested\n }\n\n /**\n * Refuse new requests, then wait for at most `timeoutMs` for those in flight and for the effects\n * they start meanwhile.\n */\n async drain(timeoutMs: number): Promise<void> {\n this.stopping = true\n const deadline = Date.now() + Math.max(0, timeoutMs)\n // A request that ends starts its run's effects before it settles, so they are tracked by the\n // time the wait for the request returns: wait again until nothing is left.\n while (this.inFlight.size > 0) {\n if (!(await settleWithin([...this.inFlight], deadline - Date.now()))) {\n console.error(\n `[Sixb] Stopped waiting after ${timeoutMs} ms for ${this.inFlight.size} in-flight Action run(s).`\n )\n return\n }\n }\n }\n\n /** Track work until it settles. Whoever started it handles how it ends; this only waits. */\n private track(work: Promise<unknown>): void {\n const settled: Promise<void> = work\n .then(\n () => undefined,\n () => undefined\n )\n .finally(() => {\n this.inFlight.delete(settled)\n })\n this.inFlight.add(settled)\n }\n\n private async dispatch(request: ActionRunRequest): Promise<ActionRunRecord> {\n // A request that held the run id but executes nothing releases it before its `pending`\n // settles, so each turn of this loop finds the run id free or held by another request.\n for (let held = this.held.get(request.runId); held; held = this.held.get(request.runId)) {\n const run = await held.pending\n if (run) return this.joinHeldRunId(run, request)\n }\n return this.holdAndExecute(request)\n }\n\n /**\n * Answer a request for a run id that a request of this process executes.\n *\n * Nothing is stored about a run before it ends, so this process is the only one that knows the\n * run is in progress. The request gets what a stored run would give it: refused when its caller\n * may not have the run or asks for something else, the record once it is written, and\n * `action.run_in_progress` until then.\n */\n private async joinHeldRunId(\n run: PendingActionRun,\n request: ActionRunRequest\n ): Promise<ActionRunRecord> {\n await assertCanReuseActionRun(run, request)\n const recorded = await this.host.storage.actionRuns?.getById({\n projectId: run.projectId,\n id: run.id,\n })\n if (recorded) return recorded\n throw createSixbError(\n \"action.run_in_progress\",\n `[Sixb] Action run '${run.id}' is already in progress.`,\n { details: { actionId: run.actionId, runId: run.id } }\n )\n }\n\n private async holdAndExecute(request: ActionRunRequest): Promise<ActionRunRecord> {\n const { runId } = request\n const pending = Promise.withResolvers<PendingActionRun | null>()\n this.held.set(runId, { pending: pending.promise })\n try {\n const persisted = await request.persist()\n if (persisted.kind === \"recorded\") return persisted.run\n pending.resolve(persisted.run)\n return await this.execute(persisted, request)\n } finally {\n this.held.delete(runId)\n pending.resolve(null)\n }\n }\n\n private async execute(\n persisted: NewActionRun,\n request: ActionRunRequest\n ): Promise<ActionRunRecord> {\n const { run, execution } = persisted\n try {\n await request.onRequested?.(run.id)\n } catch (error) {\n // Nothing ran and nothing is recorded: the error belongs to the caller whose hook threw.\n throw createSixbError(\n \"internal.unexpected\",\n `[Sixb] Action run '${run.id}' did not start: its requester failed before it executed.`,\n { cause: error, details: { actionId: run.actionId, runId: run.id } }\n )\n }\n\n let outcome: Awaited<ReturnType<typeof executeActionRun>>\n try {\n outcome = await executeActionRun(this.host, {\n run,\n execution,\n signal: request.signal,\n ...(request.readSubjectAsRequester === undefined\n ? {}\n : { readSubjectAsRequester: request.readSubjectAsRequester }),\n })\n } catch (error) {\n throw this.failRequest(run, error)\n }\n\n if (!outcome.recorded) {\n // Another process recorded this run id first: its record answers this request only under\n // the checks a record found before executing gets.\n await assertCanReuseActionRun(outcome.record, request)\n return outcome.record\n }\n if (outcome.effects) this.startEffects(run, outcome.effects)\n return outcome.record\n }\n\n /**\n * Start a recorded run's effects once the request has returned, tracked until they end. Deferring\n * them keeps a handler that does synchronous work before its first `await` from delaying the\n * response.\n */\n private startEffects(run: PendingActionRun, effects: () => Promise<void>): void {\n this.track(\n new Promise<void>((resolve) => setImmediate(resolve))\n .then(effects)\n .catch((error: unknown) => {\n console.error(`[Sixb] Action run '${run.id}' failed to run its effects:`, error)\n })\n )\n }\n\n /**\n * Fail a request whose run's execution exists.\n *\n * The run may have executed, so the caller gets an `internal.unexpected` error that names the run\n * and says what requesting it again does, never what went wrong inside it: that goes to\n * `onError`, once, with the failure the run recorded or would have recorded. Errors outside the\n * run's phases fail it in `validation`, the phase it starts in.\n */\n private failRequest(run: PendingActionRun, error: unknown): SixbCodedError {\n const ids = { actionId: run.actionId, runId: run.id }\n const requestError = createSixbError(\n \"internal.unexpected\",\n `[Sixb] Action run '${run.id}' was requested, but its record could not be written. ` +\n \"Requesting it again with the same runId returns its record if it was written, and runs \" +\n \"it again otherwise.\",\n { cause: error, details: ids }\n )\n const at = new Date()\n reportRunFailure(this.host, requestError, {\n projectId: this.host.id,\n runKind: \"action\",\n run: ids,\n failure:\n error instanceof UnrecordedActionRunError\n ? (error.record.error ??\n toActionRunFailure(error.cause, error.record.phase, { ...ids, at }))\n : toActionRunFailure(error, \"validation\", { ...ids, at }),\n })\n return requestError\n }\n}\n\nconst actionRunExecutorKey: unique symbol = Symbol(\"sixb.actionRunExecutor\")\n\ninterface ActionRunExecutorOwner {\n readonly [actionRunExecutorKey]?: ActionRunExecutor\n}\n\n/**\n * Attach the executor to a host or runtime context. The property is enumerable so that spreading a\n * context into a narrower one carries it along.\n */\nexport function registerActionRunExecutor(owner: object, executor: ActionRunExecutor): void {\n const registered = findActionRunExecutor(owner)\n if (registered && registered !== executor) {\n throw new Error(\"[Sixb] An Action run executor is already registered for this owner.\")\n }\n Object.defineProperty(owner, actionRunExecutorKey, {\n configurable: false,\n enumerable: true,\n value: executor,\n writable: false,\n })\n}\n\nexport function getActionRunExecutor(owner: object): ActionRunExecutor {\n const executor = findActionRunExecutor(owner)\n if (executor) return executor\n throw new Error(\n \"[Sixb] Actions cannot run from this runtime context: it was not bound by SixbHost.withScope().\"\n )\n}\n\n/** Copy the executor, when there is one, onto an internal runtime context being reconstructed. */\nexport function shareActionRunExecutor(source: object, target: object): void {\n const executor = findActionRunExecutor(source)\n if (executor) registerActionRunExecutor(target, executor)\n}\n\n/**\n * Refuse new Action requests on this host, then wait for at most `timeoutMs` for those in flight.\n *\n * Every `SixbHost` has an executor from construction on, so an object without one is not a host.\n */\nexport async function drainActionRuns(host: object, timeoutMs: number): Promise<void> {\n const executor = findActionRunExecutor(host)\n if (!executor) {\n throw new Error(\"[Sixb] Cannot drain Action runs: this object is not a SixbHost.\")\n }\n await executor.drain(timeoutMs)\n}\n\nfunction findActionRunExecutor(owner: object): ActionRunExecutor | undefined {\n return (owner as ActionRunExecutorOwner)[actionRunExecutorKey]\n}\n\nasync function settleWithin(\n promises: readonly Promise<unknown>[],\n timeoutMs: number\n): Promise<boolean> {\n let timeout: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n Promise.allSettled(promises).then(() => true),\n new Promise<false>((resolve) => {\n timeout = setTimeout(() => resolve(false), timeoutMs)\n }),\n ])\n } finally {\n if (timeout) clearTimeout(timeout)\n }\n}\n",
29
+ "import { AuthorizationError, assertAuthorized } from \"../authorization\"\nimport {\n getAuthorizationRef,\n type ResolvedRuntimeAuthorization,\n resolveExecutionScopeAuthorization,\n} from \"../execution/authorization\"\nimport {\n createPrimitiveExecutionRecord,\n ensureExecutionRecord,\n executionRecordInputFromRuntime,\n} from \"../execution/durable\"\nimport type { ExecutionContext } from \"../execution/types\"\nimport type { ObjectRef } from \"../ontology\"\nimport { OntologyValidationError } from \"../ontology/errors\"\nimport { isObjectRefSchema } from \"../ontology/refs\"\nimport type { ObjectTypeWithPropertyTokens } from \"../ontology/tokens\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport { assertParamUsersActive } from \"../shared/params/user-refs\"\nimport { type ActionRunRecord, ObjectNotFoundError, objectBatchKey } from \"../storage\"\nimport type { ActionRunParams } from \"../storage/action-runs/types\"\nimport {\n assertObjectReadOutputWithinLimit,\n ObjectReadLimitExceededError,\n} from \"../storage/objects/execution-limits\"\nimport { admitDelegatedObjectAction, assertDelegatedActionTarget } from \"./delegated-admission\"\nimport { getActionRunExecutor } from \"./run/executor\"\nimport {\n actionRunBelongsToShareGrant,\n canReadActionRunSubject,\n viewableActionRuns,\n} from \"./run-authorization\"\nimport { createActionRunId } from \"./run-id\"\nimport { type ExistingActionRun, persistActionRun } from \"./run-persistence\"\nimport type { ActionDefinition, ActionSubject } from \"./types\"\nimport {\n isObjectActionDefinition,\n normalizeActionParams,\n resolveObjectActionSubject,\n validateActionSubject,\n} from \"./validation\"\n\nexport interface RequestActionOptions {\n readonly runId?: string\n /**\n * Cancels the run before its irreversible boundary: a succeeded writeback, or the commit of an\n * Action without one. Past it, the run finishes whatever this signal does.\n */\n readonly signal?: AbortSignal\n}\n\nexport interface RequestActionInput extends RequestActionOptions {\n readonly actionId: string\n readonly subject?: ActionSubject\n readonly params?: Record<string, unknown>\n /** Called once the run's execution exists, before the run executes. A throw starts nothing. */\n readonly onRequested?: (runId: string) => void | Promise<void>\n}\n\nfunction getActionDefinition(runtime: SixbRuntimeContext, actionId: string): ActionDefinition {\n const action = runtime.actionRegistry.getById(actionId)\n if (!action) {\n throw new OntologyValidationError(`Unknown action '${actionId}'`)\n }\n return action\n}\n\n/**\n * Request an Action run and execute it in this process, returning its terminal record.\n *\n * Admission, authorization and params are checked before anything is persisted. A run id that is\n * already recorded returns that run's record, without running it again.\n */\nexport async function requestAction(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n input: RequestActionInput\n): Promise<ActionRunRecord> {\n const admitted = await admitActionRequest(runtime, execution, input)\n const { projectId, runtimeAuthorization, objectReader, authorization, request } = admitted\n const { action, subject, pathPrefix, actionParams } = admitted\n const actionId = action.id\n const runId = createActionRunId(request.runId)\n\n // `persistActionRun` checks an existing run id before creating its durable execution. Keep\n // process-local delegation outside that oracle unless it carries durable grant provenance.\n void getAuthorizationRef(runtimeAuthorization)\n // A run starts only while its caller still waits for it; an aborted caller gets its abort.\n const executor = getActionRunExecutor(runtime)\n request.signal?.throwIfAborted()\n\n const payload = { actionId, subject, params: actionParams }\n const assertCanReuse = (run: ExistingActionRun) =>\n assertCallerMayHaveRun({\n storage: runtime.storage,\n projectId,\n authorization,\n objectReader,\n run,\n })\n const persist = () =>\n persistActionRun({\n projectId,\n storage: runtime.storage,\n runId,\n payload,\n assertCanReuse,\n assertNewRun: () =>\n assertParamUsersActive({\n auth: runtime.storage.auth,\n projectId,\n schemas: Object.fromEntries(\n Object.entries(action.params).map(([paramId, param]) => [paramId, param.schema])\n ),\n values: actionParams,\n valueTypesById: runtime.ontology.getValueTypesById(),\n describe: (paramId) => `Action param '${pathPrefix}.${paramId}'`,\n invalid: (message) => new OntologyValidationError(message),\n }),\n createExecution: async (executionId, runId) => {\n const caller = await ensureExecutionRecord(\n runtime.storage.executions,\n executionRecordInputFromRuntime({\n execution,\n runtimeAuthorization,\n })\n )\n return createPrimitiveExecutionRecord({\n id: executionId,\n primitive: { kind: \"action\", id: actionId, runId },\n origin: { type: \"execution\", parent: caller },\n })\n },\n })\n\n // The request saw its subject; the run reads it again, and must find a state its requester sees.\n const conditioned =\n authorization.type === \"principal\" &&\n subject.kind === \"object\" &&\n objectReader.viewsThroughCondition(subject.objectTypeId)\n\n const run = await executor.request({\n runId,\n payload,\n persist,\n assertCanReuse,\n signal: request.signal,\n onRequested: request.onRequested,\n ...(conditioned\n ? {\n readSubjectAsRequester: ({ objectTypeId, primaryId }) =>\n objectReader.getByPrimaryId({ objectTypeId, primaryId }),\n }\n : {}),\n })\n return enforceDelegatedOutputBudget(authorization, run)\n}\n\n/** An Action request as it would run: admitted, and its params normalized. */\nexport interface PreparedActionRequest {\n readonly actionId: string\n readonly subject: ActionSubject\n readonly params: ActionRunParams\n /** `external` when the Action has a writeback or effects: it reaches beyond Sixb. */\n readonly effect: \"ontology\" | \"external\"\n}\n\n/**\n * Admit an Action request without running it: the checks and the params `requestAction` applies\n * before anything is persisted. The agent API gateway prepares the calls it holds for approval.\n */\nexport async function prepareActionRequest(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n input: Pick<RequestActionInput, \"actionId\" | \"subject\" | \"params\">\n): Promise<PreparedActionRequest> {\n const { action, subject, actionParams } = await admitActionRequest(runtime, execution, input)\n\n return {\n actionId: action.id,\n subject,\n params: actionParams,\n effect:\n action.phases.writeback !== undefined || action.phases.effects !== undefined\n ? \"external\"\n : \"ontology\",\n }\n}\n\n/**\n * Who may request the Action on this subject, and its normalized params, with the capabilities the\n * request runs with. Persists nothing.\n */\nasync function admitActionRequest(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n input: RequestActionInput\n) {\n // Capture the three process-local capabilities before caller-owned request getters can run.\n const projectId = runtime.projectId\n const runtimeAuthorization = runtime.runtimeAuthorization\n const objectReader = runtime.objectReader\n const request = snapshotActionRequest(input)\n const authorization = resolveExecutionScopeAuthorization(projectId, {\n execution,\n authorization: runtimeAuthorization,\n })\n const subject = request.subject\n const delegatedSubject =\n authorization.type === \"delegated\"\n ? assertDelegatedActionTarget({\n authorization,\n actionId: request.actionId,\n subject,\n })\n : undefined\n const action = getActionDefinition(runtime, request.actionId)\n const rawParams = request.params\n\n if (authorization.type === \"delegated\") {\n await admitDelegatedObjectAction({\n objectReader,\n runtimeAuthorization,\n execution,\n authorization,\n action,\n subject: delegatedSubject!,\n })\n } else {\n assertAuthorized(\n { projectId, runtimeAuthorization },\n { kind: \"action.apply\", actionId: action.id }\n )\n }\n if (authorization.type !== \"delegated\" && action.binding.kind === \"object\") {\n // Object actions require visibility of the type they are bound to, as listing them does.\n await assertTypeViewable({\n projectId,\n runtimeAuthorization,\n objectReader,\n objectTypeId: action.binding.objectType.id,\n })\n }\n\n validateActionSubject(action, subject)\n\n let pathPrefix = action.id\n if (isObjectActionDefinition(action)) {\n const objectType: ObjectTypeWithPropertyTokens = resolveObjectActionSubject({\n runtime,\n action,\n subject,\n })\n pathPrefix = `${objectType.id}.${action.id}`\n }\n\n const actionParams = normalizeActionParams(runtime, action.params, rawParams, pathPrefix)\n\n if (authorization.type !== \"delegated\") {\n await assertNamedObjectsVisible({\n objectReader,\n subject,\n paramsConfig: action.params,\n params: actionParams,\n pathPrefix,\n })\n }\n\n return {\n projectId,\n runtimeAuthorization,\n objectReader,\n authorization,\n request,\n action,\n subject,\n pathPrefix,\n actionParams,\n }\n}\n\n/**\n * A principal views a type whole, through a view grant, or through a condition its reader applies.\n * Only the reader knows the latter, and each object the request names is then read through it.\n */\nasync function assertTypeViewable(input: {\n readonly projectId: string\n readonly runtimeAuthorization: SixbRuntimeContext[\"runtimeAuthorization\"]\n readonly objectReader: SixbRuntimeContext[\"objectReader\"]\n readonly objectTypeId: string\n}): Promise<void> {\n const { objectReader, objectTypeId } = input\n\n if (objectReader.viewsThroughCondition(objectTypeId)) {\n await objectReader.assertViewable([objectTypeId])\n return\n }\n\n assertAuthorized(input, { kind: \"object.view\", objectTypeId })\n}\n\n/**\n * A principal acts only on the objects it can see: the action runs as trusted code, so it cannot\n * name, as its subject or a `ref()` param, an object it could not read itself. Each one's type must\n * be viewable as a read requires it, its markings included. A subtype excluded from a broad grant\n * is not viewable through its parent, and a run on it is one its caller could never read back.\n *\n * Where it views a type through a condition, each object of that type must also be visible through\n * its reader now: one that is not is hidden or missing, and both are not found, before anything is\n * recorded. An object of a type it views whole is not read here. Its missing subject fails the run,\n * and its `ref()` params are not looked up, as before conditions existed.\n */\nasync function assertNamedObjectsVisible(input: {\n readonly objectReader: SixbRuntimeContext[\"objectReader\"]\n readonly subject: ActionSubject\n readonly paramsConfig: ActionDefinition[\"params\"]\n readonly params: Record<string, unknown>\n readonly pathPrefix: string\n}): Promise<void> {\n const { objectReader, subject, params } = input\n\n const named: { readonly ref: ObjectRef; readonly context: string }[] = []\n if (subject.kind === \"object\") {\n named.push({ ref: subject, context: \"Object not found for action run\" })\n }\n for (const [paramId, param] of Object.entries(input.paramsConfig)) {\n const value = params[paramId]\n if (!isObjectRefSchema(param.schema) || value === undefined || value === null) continue\n\n named.push({\n ref: value as ObjectRef,\n context: `Object not found for action param '${input.pathPrefix}.${paramId}'`,\n })\n }\n\n if (named.length === 0) return\n await objectReader.assertViewable(named.map(({ ref }) => ref.objectTypeId))\n\n const conditioned = named.filter(({ ref }) =>\n objectReader.viewsThroughCondition(ref.objectTypeId)\n )\n if (conditioned.length === 0) return\n\n const visible = await objectReader.getByPrimaryIdBatch({\n items: conditioned.map(({ ref }) => ({\n objectTypeId: ref.objectTypeId,\n primaryId: ref.primaryId,\n })),\n })\n\n for (const { ref, context } of conditioned) {\n if (visible.has(objectBatchKey(ref.objectTypeId, ref.primaryId))) continue\n throw new ObjectNotFoundError(ref.objectTypeId, ref.primaryId, context)\n }\n}\n\n/**\n * A run that already exists under the requested run id, recorded or executing, answers this request\n * only under the rules that would let its caller read it.\n *\n * A principal gets it under the visibility rules `actions.runs.getById` applies; admission already\n * requires the grants those rules check for the request's own Action and subject, and this keeps a\n * run that carries another request from depending on it. A delegated caller gets it only when it was\n * requested under the same Share grant.\n */\nasync function assertCallerMayHaveRun(input: {\n readonly storage: SixbRuntimeContext[\"storage\"]\n readonly projectId: string\n readonly authorization: ResolvedRuntimeAuthorization\n readonly objectReader: SixbRuntimeContext[\"objectReader\"]\n readonly run: ExistingActionRun\n}): Promise<void> {\n const { authorization, run } = input\n const visible =\n authorization.type === \"delegated\"\n ? authorization.delegation !== undefined &&\n (await actionRunBelongsToShareGrant({\n storage: input.storage,\n projectId: input.projectId,\n run,\n grantId: authorization.delegation.grantId,\n }))\n : authorization.type !== \"principal\" ||\n ((await viewableActionRuns(input.objectReader, authorization.context, [run])).length > 0 &&\n (await canReadActionRunSubject(input.objectReader, run)))\n if (!visible) {\n throw new AuthorizationError(\n `apply:action:${run.actionId}`,\n authorization.type === \"delegated\"\n ? \"[Sixb] Delegated authority cannot reuse this Action run.\"\n : `[Sixb] Action run '${run.id}' is not visible to this principal.`\n )\n }\n}\n\n/**\n * A delegated caller receives the record only within its output budget, like any read.\n *\n * The run already ran by then, and its record does not change: requesting the same run id again\n * is refused the same way.\n */\nfunction enforceDelegatedOutputBudget(\n authorization: ResolvedRuntimeAuthorization,\n run: ActionRunRecord\n): ActionRunRecord {\n if (authorization.type !== \"delegated\") return run\n try {\n assertObjectReadOutputWithinLimit(run, authorization.objectRead.limits)\n } catch (error) {\n if (!(error instanceof ObjectReadLimitExceededError)) throw error\n throw new ObjectReadLimitExceededError(\n error.metric,\n error.limit,\n `[Sixb] Action run '${run.id}' finished with status '${run.status}', but its record exceeds ` +\n `this caller's ${error.metric} limit (${error.limit}). Requesting it again returns the ` +\n \"same record.\"\n )\n }\n return run\n}\n\nfunction snapshotActionRequest(input: RequestActionInput): {\n readonly actionId: string\n readonly subject: ActionSubject\n readonly params: Record<string, unknown>\n readonly runId?: string\n readonly signal?: AbortSignal\n readonly onRequested?: (runId: string) => void | Promise<void>\n} {\n const actionId = input.actionId\n const subject = input.subject\n const params = input.params\n const runId = input.runId\n const signal = input.signal\n const onRequested = input.onRequested\n return {\n ...structuredClone({\n actionId,\n subject: subject ?? { kind: \"none\" },\n params: params ?? {},\n ...(runId === undefined ? {} : { runId }),\n }),\n ...(signal === undefined ? {} : { signal }),\n ...(onRequested === undefined ? {} : { onRequested }),\n }\n}\n",
30
+ "import { isAllowed } from \"../authorization\"\nimport type { ExecutionContext } from \"../execution\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport {\n assertAuthorizedObjectReaderBinding,\n getAuthorizedOntologyView,\n} from \"../execution/authorized-object-reader\"\nimport type { ObjectType } from \"../ontology\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type {\n ActionRunRecord,\n ListActionRunsInput,\n ListActionRunsResult,\n} from \"../storage/action-runs\"\nimport { assertObjectReadOutputWithinLimit } from \"../storage/objects/execution-limits\"\nimport { type ActionDescriptor, snapshotActionDescriptor } from \"./descriptor\"\nimport { type RequestActionInput, requestAction } from \"./request\"\nimport {\n canDelegationAccessActionRun,\n canReadActionRunSubject,\n readableSubjects,\n unreadableActionRunTypes,\n viewableActionRuns,\n} from \"./run-authorization\"\nimport type { ActionDefinition } from \"./types\"\n\nexport interface ActionRunsRuntime {\n getById(runId: string): Promise<ActionRunRecord | null>\n list(\n input?: Omit<ListActionRunsInput, \"projectId\" | \"actionIds\" | \"objectTypeIds\">\n ): Promise<ListActionRunsResult>\n}\n\nexport interface ActionsRuntime {\n list(): readonly ActionDescriptor[]\n getById(actionId: string): ActionDescriptor | null\n listGlobal(): readonly ActionDescriptor[]\n listForType(objectType: ObjectType): readonly ActionDescriptor[]\n /**\n * Run an Action in this process and return its terminal record, without waiting for its effects.\n * A run that fails resolves with status `failed`. The call rejects when the request itself is\n * refused (unknown action, invalid params, missing authority, a run id this process is still\n * running, a stopping runtime), and with `internal.unexpected` when a run that started could not\n * be recorded: requesting it again with the same run id returns its record if it was recorded, and\n * runs it again otherwise.\n */\n request(input: RequestActionInput): Promise<ActionRunRecord>\n readonly runs: ActionRunsRuntime\n}\n\nexport function createActionsRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext\n): ActionsRuntime {\n const projectId = runtime.projectId\n const runtimeAuthorization = runtime.runtimeAuthorization\n const objectReader = runtime.objectReader\n assertAuthorizedObjectReaderBinding({\n reader: objectReader,\n scope: { execution, authorization: runtimeAuthorization },\n })\n const authorization = resolveRuntimeAuthorizationForProject({\n projectId,\n runtimeAuthorization,\n })\n const canList = (action: ActionDefinition) => {\n if (authorization.type === \"denied\") return false\n if (authorization.type === \"delegated\") {\n const binding = action.binding\n return (\n binding.kind === \"object\" &&\n authorization.actionApply.some(\n (target) =>\n target.actionId === action.id && target.subject.objectTypeId === binding.objectType.id\n ) &&\n getAuthorizedOntologyView(objectReader).getObjectTypeById(binding.objectType.id) !== null\n )\n }\n if (authorization.type === \"unrestricted\") return true\n if (!isAllowed(authorization.context, { kind: \"action.apply\", actionId: action.id })) {\n return false\n }\n if (action.binding.kind === \"global\") return true\n\n // A type viewed through a condition is viewable as the reader decides it: its requests then\n // name objects the reader sees.\n const objectTypeId = action.binding.objectType.id\n return objectReader.viewsThroughCondition(objectTypeId)\n ? getAuthorizedOntologyView(objectReader).getObjectTypeById(objectTypeId) !== null\n : isAllowed(authorization.context, { kind: \"object.view\", objectTypeId })\n }\n\n const release = <T>(value: T): T => {\n if (authorization.type === \"delegated\") {\n assertObjectReadOutputWithinLimit(value, authorization.objectRead.limits)\n }\n return value\n }\n const describeAll = (actions: readonly ActionDefinition[]) =>\n release(actions.filter(canList).map(snapshotActionDescriptor))\n\n return {\n list: () => describeAll(runtime.actionRegistry.list()),\n getById: (actionId) => {\n const action = runtime.actionRegistry.getById(actionId)\n return release(action && canList(action) ? snapshotActionDescriptor(action) : null)\n },\n listGlobal: () => describeAll(runtime.actionRegistry.listGlobal()),\n listForType: (objectType) =>\n describeAll(\n runtime.actionRegistry\n .listForType(objectType)\n .filter(\n (action) =>\n authorization.type !== \"delegated\" ||\n (action.binding.kind === \"object\" && action.binding.objectType.id === objectType.id)\n )\n ),\n request: (input) => requestAction(runtime, execution, input),\n runs: {\n getById: async (runId) => {\n if (\n authorization.type === \"denied\" ||\n (authorization.type === \"delegated\" &&\n (!authorization.delegation || authorization.actionApply.length === 0))\n )\n return null\n const run =\n (await runtime.storage.actionRuns?.getById({\n projectId,\n id: runId,\n })) ?? null\n return run &&\n (authorization.type === \"unrestricted\" ||\n (authorization.type === \"principal\" &&\n (await viewableActionRuns(objectReader, authorization.context, [run])).length > 0) ||\n (authorization.type === \"delegated\" &&\n (await canDelegationAccessActionRun({\n storage: runtime.storage,\n projectId,\n authority: authorization,\n run,\n })))) &&\n (await canReadActionRunSubject(objectReader, run))\n ? release(run)\n : null\n },\n list: async (input = {}) => {\n if (authorization.type === \"denied\" || authorization.type === \"delegated\") {\n return { runs: [], hasMore: false, total: 0 }\n }\n const storage = runtime.storage.actionRuns\n if (!storage) return { runs: [], hasMore: false, total: 0 }\n if (authorization.type === \"unrestricted\") return storage.list({ ...input, projectId })\n\n // Storage filters, so its pages and totals only count runs the reader can see. A run on a\n // type viewed through a condition shows only through its subject: a listing that names\n // one the reader reads now includes it, every other listing leaves the type out. HTTP\n // names it by objectTypeId and primaryId.\n const context = authorization.context\n const unreadable = await unreadableActionRunTypes(objectReader)\n const objectTypeIds = [...context.grants[\"view:object\"]].filter(\n (objectTypeId) => !unreadable.has(objectTypeId)\n )\n\n const subject =\n input.subject ??\n (input.objectTypeId !== undefined && input.primaryId !== undefined\n ? {\n kind: \"object\" as const,\n objectTypeId: input.objectTypeId,\n primaryId: input.primaryId,\n }\n : undefined)\n if (subject?.kind === \"object\" && context.viewConditions?.has(subject.objectTypeId)) {\n const readable = await readableSubjects(objectReader, [subject])\n if (readable.size === 0) return { runs: [], hasMore: false, total: 0 }\n objectTypeIds.push(subject.objectTypeId)\n }\n\n return storage.list({\n ...input,\n projectId,\n actionIds: [...context.grants[\"apply:action\"]],\n objectTypeIds,\n })\n },\n },\n }\n}\n",
31
+ "import type { AiModelCallUsage, AiModelCallUsageInput, AiUsageStorage } from \"../storage/ai-usage\"\nimport {\n AI_USAGE_FIELDS,\n aggregateAiModelCallUsage,\n normalizeAiModelCallUsage,\n} from \"../storage/ai-usage/usage\"\n\n/** Resolve execution usage for runtime views without exposing the accounting provider. */\nexport async function resolveExecutionUsage(input: {\n readonly storage: AiUsageStorage | undefined\n readonly projectId: string\n readonly executionIds: readonly string[]\n}): Promise<readonly (AiModelCallUsage | undefined)[]> {\n if (input.executionIds.length === 0) return []\n if (!input.storage) return input.executionIds.map(() => undefined)\n\n const summaries = await input.storage.summarizeExecutions({\n projectId: input.projectId,\n executionIds: input.executionIds,\n })\n return summaries.map((summary) => (summary.modelCallCount === 0 ? undefined : summary.usage))\n}\n\n/**\n * The usage of several executions together. When each knows its token totals, a count is summed\n * only where all of them know it, as their calls would be one by one. When one does not, such as a\n * child cut short mid-call, the total keeps what the others know: each count sums the executions\n * that know it, and the total is `partial`, a floor for what was spent.\n */\nexport function addUsageSummaries(\n usages: readonly AiModelCallUsage[]\n): AiModelCallUsage | undefined {\n if (usages.length <= 1) return usages[0]\n if (usages.every((usage) => usage.reportingStatus === \"complete\")) {\n return aggregateAiModelCallUsage(usages)\n }\n\n const counts: AiModelCallUsageInput = Object.fromEntries(\n AI_USAGE_FIELDS.flatMap((field) => {\n const known = usages.flatMap((usage) => (usage[field] === undefined ? [] : [usage[field]]))\n return known.length === 0 ? [] : [[field, known.reduce((sum, count) => sum + count, 0)]]\n })\n )\n const total = normalizeAiModelCallUsage(counts)\n return usages.every((usage) => usage.reportingStatus === \"unavailable\")\n ? total\n : { ...total, reportingStatus: \"partial\" }\n}\n",
32
+ "import { nearestOwner } from \"../execution/lineage\"\nimport { addCostSummaries, resolveExecutionCosts } from \"../runtime/ai-cost\"\nimport { addUsageSummaries, resolveExecutionUsage } from \"../runtime/ai-usage\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type { AiCostSummary } from \"../storage/ai-cost\"\nimport type { AiModelCallUsage } from \"../storage/ai-usage\"\n\n/**\n * Each turn's usage and cost: its own calls and those of everything below it, its children and\n * what its tools ran, as Activity counts them. Each call counts once, toward the nearest turn above\n * it. A child still at work adds what it has spent so far, and so does a workflow a tool started,\n * also once the turn has ended: Activity counts it toward the conversation the same way. A child's\n * execution counts the same way when it is the one asked about.\n */\nexport async function resolveTurnAccounting(\n runtime: SixbRuntimeContext,\n executionIds: readonly string[]\n): Promise<readonly { readonly usage?: AiModelCallUsage; readonly cost?: AiCostSummary }[]> {\n if (executionIds.length === 0) return []\n const { projectId, storage } = runtime\n\n const below = await storage.executions.listDescendants({ projectId, executionIds })\n const turns = new Set(executionIds)\n const parentOf = new Map(below.map(({ id, parentId }) => [id, parentId]))\n const turnOf = (executionId: string) =>\n nearestOwner(\n executionId,\n (id) => parentOf.get(id),\n (id) => turns.has(id)\n )\n\n const accounted = [...executionIds, ...below.map(({ id }) => id)]\n const [usages, costs] = await Promise.all([\n resolveExecutionUsage({ storage: storage.aiUsage, projectId, executionIds: accounted }),\n resolveExecutionCosts({ storage: storage.aiCosts, projectId, executionIds: accounted }),\n ])\n\n const usagesByTurn = new Map<string, AiModelCallUsage[]>()\n const costsByTurn = new Map<string, AiCostSummary[]>()\n accounted.forEach((executionId, index) => {\n const turn = turnOf(executionId)\n const usage = usages[index]\n const cost = costs[index]\n // Never: every execution listed descends from a turn asked about.\n if (turn === undefined) return\n\n if (usage) usagesByTurn.set(turn, [...(usagesByTurn.get(turn) ?? []), usage])\n if (cost) costsByTurn.set(turn, [...(costsByTurn.get(turn) ?? []), cost])\n })\n\n return executionIds.map((executionId) => {\n const usage = addUsageSummaries(usagesByTurn.get(executionId) ?? [])\n const cost = addCostSummaries(costsByTurn.get(executionId) ?? [])\n return {\n ...(usage === undefined ? {} : { usage }),\n ...(cost === undefined ? {} : { cost }),\n }\n })\n}\n",
33
+ "import type { Sixb } from \"../runtime/sixb\"\nimport type { AgentTurnResume } from \"./request\"\n\n/** Where a resume left the paused turn, as whoever asked it learns. */\nexport type AgentApprovalResume =\n | AgentTurnResume\n /**\n * The turn could not resume as its requester: an AI limit, a lost grant or a thread they left.\n * `retrying`: Sixb tries again; otherwise the thread's next message reports the calls.\n */\n | {\n readonly status: \"refused\"\n readonly code: string\n readonly message: string\n readonly retrying: boolean\n }\n\nconst resumeKey = Symbol(\"sixb.agentTurnResume\")\n\ninterface ResumeOwner {\n readonly [resumeKey]?: (runId: string) => Promise<AgentApprovalResume>\n}\n\n/**\n * Let code without a request resume a paused turn with a bound SDK's authority: the worker, after a\n * turn paused on calls already decided, and its repair pass. The call side of a decision is the\n * host's approval executor.\n */\nexport function registerAgentTurnResume(\n agent: object,\n resume: (runId: string) => Promise<AgentApprovalResume>\n): void {\n Object.defineProperty(agent, resumeKey, {\n configurable: false,\n enumerable: false,\n value: resume,\n writable: false,\n })\n}\n\n/** Resume a paused turn as the bound SDK's principal, its requester. */\nexport function resumeDecidedAgentTurn(sixb: Sixb, runId: string): Promise<AgentApprovalResume> {\n const resume = (sixb.agent as ResumeOwner)[resumeKey]\n if (!resume) {\n throw new Error(\"[Sixb] Agent turns cannot resume from this SDK: it was not bound by Sixb.\")\n }\n return resume(runId)\n}\n",
34
+ "import { randomUUID } from \"node:crypto\"\nimport type { Broker } from \"../broker\"\nimport { SIXB_ERROR_CODES } from \"../errors/catalog\"\nimport { captureSixbFailure, createSixbError, isSixbError, toSixbFailure } from \"../errors/internal\"\nimport { bindDurableAgentExecution, createInheritedAgentExecutionRecord } from \"../execution/agent\"\nimport { ensureExecutionRecord, executionRecordInputFromRuntime } from \"../execution/durable\"\nimport type { ExecutionScope } from \"../execution/types\"\nimport type { Sixb } from \"../runtime/sixb\"\nimport type { ActionRunRecord } from \"../storage/action-runs\"\nimport type {\n AgentApprovalCall,\n AgentApprovalOutcome,\n AgentApprovalRecord,\n AgentStorage,\n} from \"../storage/agents\"\nimport type { WorkflowRunRecord } from \"../storage/workflow-runs\"\nimport { announceAgentApprovals } from \"./approvals\"\nimport { resolveInheritedAgentExecutionAuthorization } from \"./authority\"\nimport { AgentRequestError } from \"./errors\"\nimport {\n AgentRunScopeError,\n type AgentRunScopeHost,\n resolveAgentRunExecutionScope,\n} from \"./run-scope\"\n\nexport interface AgentApprovalHost extends AgentRunScopeHost {\n readonly storage: AgentRunScopeHost[\"storage\"] & {\n readonly agents?: AgentStorage\n readonly actionRuns?: {\n getById(params: { projectId: string; id: string }): Promise<ActionRunRecord | null>\n }\n readonly workflowRuns?: {\n getById(params: { projectId: string; id: string }): Promise<WorkflowRunRecord | null>\n }\n }\n readonly broker: Broker\n withScope(scope: ExecutionScope): object\n}\n\n/**\n * The request that decides, as its own bound SDK carries it. The call runs with this authority: the\n * requester's grants and credential at decision time, not those the turn started with.\n */\nexport type AgentApprovalDecider = ExecutionScope\n\n/** Runs the calls a host's requesters approve. */\nexport interface AgentApprovalExecutor {\n /** Run the call the caller's decision just approved, and record its outcome. */\n run(approval: AgentApprovalRecord, decider: AgentApprovalDecider): Promise<AgentApprovalRecord>\n /**\n * Run an approved call a crash left without its outcome, as the run that made it, with the\n * authority its turn holds now. When that authority has ended, the outcome says so and the call\n * does not run. The caller holds the call's execution claim.\n */\n complete(approval: AgentApprovalRecord): Promise<AgentApprovalRecord>\n /**\n * The outcome of a call another decision approved, without starting it: the outcome of the run\n * this process is making, or the one the call's run recorded. Without either, the approval comes\n * back as it is.\n */\n settle(approval: AgentApprovalRecord): Promise<AgentApprovalRecord>\n}\n\n/**\n * One executor per host. It knows the calls this process is running, so that a second approval of\n * the same call, a double click or a retried request, waits for the first instead of starting it.\n */\nclass HostAgentApprovalExecutor implements AgentApprovalExecutor {\n private readonly running = new Map<string, Promise<AgentApprovalRecord>>()\n\n constructor(private readonly host: AgentApprovalHost) {}\n\n run(approval: AgentApprovalRecord, decider: AgentApprovalDecider): Promise<AgentApprovalRecord> {\n const key = runningKey(approval)\n const running = this.running.get(key)\n if (running) return running\n\n const started = this.execute(approval, () => this.bindDecision(approval, decider)).finally(() =>\n this.running.delete(key)\n )\n this.running.set(key, started)\n return started\n }\n\n complete(approval: AgentApprovalRecord): Promise<AgentApprovalRecord> {\n const key = runningKey(approval)\n const running = this.running.get(key)\n if (running) return running\n\n const started = this.completeLost(approval).finally(() => this.running.delete(key))\n this.running.set(key, started)\n return started\n }\n\n private async completeLost(approval: AgentApprovalRecord): Promise<AgentApprovalRecord> {\n let sixb: Sixb\n try {\n sixb = await this.bindCallerRun(approval)\n } catch (error) {\n if (!(error instanceof AgentRunScopeError)) throw error\n return this.record(approval, {\n kind: \"error\",\n error: toSixbFailure(\n createSixbError(\n \"agent.approval_authority_lost\",\n \"[Sixb] The approved call did not run: the sign-in of whoever asked for it ended first. Ask the Agent again.\",\n { cause: error }\n ),\n { allowedCodes: SIXB_ERROR_CODES }\n ),\n })\n }\n return this.execute(approval, async () => sixb)\n }\n\n /** The run that made the call, with the authority its execution holds now. */\n private async bindCallerRun(approval: AgentApprovalRecord): Promise<Sixb> {\n const run = await this.host.storage.agents?.runs.getById({\n projectId: approval.projectId,\n id: approval.callerRunId,\n })\n if (!run) throw new Error(`[Sixb] Agent run '${approval.callerRunId}' was not found.`)\n\n const scope = await resolveAgentRunExecutionScope(this.host, {\n runId: run.id,\n executionId: run.executionId,\n authority: { type: \"inherited\" },\n })\n return bindDurableAgentExecution(this.host, scope)\n }\n\n async settle(approval: AgentApprovalRecord): Promise<AgentApprovalRecord> {\n const running = this.running.get(runningKey(approval))\n if (running) return running\n\n return this.recordRanOutcome(approval)\n }\n\n /** Run the call bound by `bind`, and record what it gave. A refusal becomes the outcome. */\n private async execute(\n approval: AgentApprovalRecord,\n bind: () => Promise<Sixb>\n ): Promise<AgentApprovalRecord> {\n try {\n const sixb = await bind()\n return await this.record(approval, await runCall(sixb, approval.call))\n } catch (error) {\n // The call's own run is running in another request: its record holds the outcome, not this.\n if (isSixbError(error) && error.code === \"action.run_in_progress\") {\n return this.recordRanOutcome(approval)\n }\n return this.record(approval, {\n kind: \"error\",\n error: captureSixbFailure(error, {\n allowedCodes: [\"internal.unexpected\", \"runtime.stopping\"],\n defaultCode: \"internal.unexpected\",\n }),\n })\n }\n }\n\n /** Record the outcome the call's run already has, if it has one. */\n private async recordRanOutcome(approval: AgentApprovalRecord): Promise<AgentApprovalRecord> {\n const outcome = await this.ranOutcome(approval.projectId, approval.call)\n return outcome ? this.record(approval, outcome) : approval\n }\n\n private async ranOutcome(\n projectId: string,\n call: AgentApprovalCall\n ): Promise<AgentApprovalOutcome | undefined> {\n const storage = this.host.storage\n if (call.kind === \"workflow\") {\n const run = await storage.workflowRuns?.getById({ projectId, id: call.workflowRunId })\n return run\n ? workflowRunOutcome(run.id, (run.queuedAt ?? run.startedAt).toISOString())\n : undefined\n }\n\n const run = await storage.actionRuns?.getById({ projectId, id: call.actionRunId })\n return run ? actionRunOutcome(run) : undefined\n }\n\n /** Record the outcome, once, and announce it. */\n private async record(\n approval: AgentApprovalRecord,\n outcome: AgentApprovalOutcome\n ): Promise<AgentApprovalRecord> {\n const agents = this.host.storage.agents\n if (!agents) {\n throw new AgentRequestError(\"storage_unavailable\", \"[Sixb] Agent storage is not configured.\")\n }\n const recorded = await agents.approvals.recordOutcome({\n projectId: approval.projectId,\n id: approval.id,\n outcome,\n })\n await announceAgentApprovals(this.host.broker, [recorded])\n return recorded\n }\n\n /**\n * Bind the call to an execution of its own, as the run that made it: its executor is that run, as\n * if the gateway had let the call through. It is a child of the deciding request and carries its\n * authority: the turn's credential may have ended since, a logout or an expired session, and the\n * decider's request is live.\n */\n private async bindDecision(\n approval: AgentApprovalRecord,\n decider: AgentApprovalDecider\n ): Promise<Sixb> {\n const { projectId } = approval\n const storage = this.host.storage\n const request = await ensureExecutionRecord(\n storage.executions,\n executionRecordInputFromRuntime({\n execution: decider.execution,\n runtimeAuthorization: decider.authorization,\n })\n )\n const execution = await storage.executions.create(\n createInheritedAgentExecutionRecord({\n id: `exec_${randomUUID()}`,\n parent: request,\n runId: approval.callerRunId,\n })\n )\n\n // Grants come from the server's records for that credential, as the gateway resolves them.\n const authorization = await resolveInheritedAgentExecutionAuthorization({\n auth: storage.auth,\n projectId,\n authorizationRef: execution.authorizationRef,\n security: this.host.definitions.security,\n })\n return bindDurableAgentExecution(this.host, {\n execution,\n runId: approval.callerRunId,\n authorization,\n })\n }\n}\n\nfunction runningKey(approval: AgentApprovalRecord): string {\n return JSON.stringify([approval.projectId, approval.id])\n}\n\n/** The call names its run, so asking for it again returns the same run instead of another. */\nasync function runCall(sixb: Sixb, call: AgentApprovalCall): Promise<AgentApprovalOutcome> {\n if (call.kind === \"workflow\") {\n const started = await sixb.workflows.requestById({\n workflowId: call.workflowId,\n input: call.input,\n runId: call.workflowRunId,\n source: { type: \"manual\" },\n })\n return workflowRunOutcome(started.runId, started.queuedAt)\n }\n\n return actionRunOutcome(\n await sixb.actions.request({\n actionId: call.actionId,\n subject: call.subject,\n params: call.params,\n runId: call.actionRunId,\n })\n )\n}\n\nfunction actionRunOutcome(run: ActionRunRecord): AgentApprovalOutcome {\n return {\n kind: \"action-run\",\n runId: run.id,\n status: run.status,\n ...(run.status === \"failed\" && run.error ? { error: run.error } : {}),\n }\n}\n\nfunction workflowRunOutcome(runId: string, queuedAt: string): AgentApprovalOutcome {\n return { kind: \"workflow-run\", runId, queuedAt }\n}\n\nconst approvalExecutorKey = Symbol(\"sixb.agentApprovalExecutor\")\n\ninterface ApprovalExecutorOwner {\n readonly [approvalExecutorKey]?: AgentApprovalExecutor\n}\n\nexport function createAgentApprovalExecutor(host: AgentApprovalHost): AgentApprovalExecutor {\n return new HostAgentApprovalExecutor(host)\n}\n\n/**\n * Attach the host's approval executor to the host, for its workers, and to its context.\n * Enumerable, like the Action run executor, so that the runtime context of every bound SDK carries\n * it: deciding needs to bind another execution.\n */\nexport function registerAgentApprovalExecutor(\n owner: object,\n executor: AgentApprovalExecutor\n): void {\n Object.defineProperty(owner, approvalExecutorKey, {\n configurable: false,\n enumerable: true,\n value: executor,\n writable: false,\n })\n}\n\nexport function getAgentApprovalExecutor(owner: object): AgentApprovalExecutor {\n const executor = (owner as ApprovalExecutorOwner)[approvalExecutorKey]\n if (!executor) {\n throw new Error(\n \"[Sixb] Agent approvals cannot run from this runtime context: it was not bound by SixbHost.withScope().\"\n )\n }\n return executor\n}\n",
35
+ "import { randomUUID } from \"node:crypto\"\nimport { isDeepStrictEqual } from \"node:util\"\nimport { type Principal, principalsEqual, SYSTEM_PRINCIPAL } from \"../auth\"\nimport type { Broker } from \"../broker\"\nimport type {\n AgentApprovalCall,\n AgentApprovalMode,\n AgentApprovalRecord,\n AgentRunRecord,\n AgentStorage,\n} from \"../storage/agents\"\nimport { agentApprovalHoldsRun, isAgentApprovalMode } from \"../storage/agents/provider\"\nimport { AGENT_APPROVAL_MODES } from \"../storage/agents/types\"\nimport type { AgentApprovalDecider, AgentApprovalExecutor } from \"./approval-executor\"\nimport { AgentRequestError } from \"./errors\"\nimport type {\n AgentApprovalCaller,\n AgentApprovalCallSummary,\n AgentApprovalOutcomePart,\n} from \"./message\"\nimport { publishAgentApprovalActivity } from \"./streams/protocol\"\n\n/**\n * The mode of a turn whose requester chose none, in the thread or as their default: every action\n * and workflow waits for them. A run admitted before approval modes keeps `auto`\n * ({@link agentRunApprovalMode}).\n */\nconst FALLBACK_AGENT_APPROVAL_MODE: AgentApprovalMode = \"manual\"\n\n/** How long a held call waits for its requester. */\nexport const AGENT_APPROVAL_TTL_MS = 7 * 24 * 60 * 60 * 1_000\n\n/** From least to most allowed. */\nconst APPROVAL_MODE_RANK: Readonly<Record<AgentApprovalMode, number>> = {\n manual: 0,\n \"accept-edits\": 1,\n auto: 2,\n}\n\n/** What a call does, as far as approval modes tell calls apart. */\nexport type AgentApprovalCallEffect =\n | { readonly kind: \"action\"; readonly effect: \"ontology\" | \"external\" }\n | { readonly kind: \"workflow\" }\n\n/**\n * Where a user's mode in a thread comes from: their choice there, their default, or neither. A\n * sub-agent's thread has no mode of its own to choose: `run`, its latest run's, copied from the turn\n * it works under.\n */\nexport type AgentApprovalModeSource = \"thread\" | \"default\" | \"fallback\" | \"run\"\n\nexport interface ResolvedAgentApprovalMode {\n readonly approvalMode: AgentApprovalMode\n readonly approvalModeSource: AgentApprovalModeSource\n}\n\n/** Whether a turn with this mode runs the call without asking. */\nexport function approvalModeAllows(\n mode: AgentApprovalMode,\n call: AgentApprovalCallEffect\n): boolean {\n return APPROVAL_MODE_RANK[mode] >= APPROVAL_MODE_RANK[leastApprovalModeAllowing(call)]\n}\n\n/** The least the requester has to allow for this call to run without asking. */\nexport function leastApprovalModeAllowing(call: AgentApprovalCallEffect): AgentApprovalMode {\n return call.kind === \"action\" && call.effect === \"ontology\" ? \"accept-edits\" : \"auto\"\n}\n\n/** A mode a caller asked for, refused as a request error when it is not one. */\nexport function assertAgentApprovalMode(value: unknown): AgentApprovalMode {\n if (!isAgentApprovalMode(value)) {\n throw new AgentRequestError(\n \"invalid_approval_mode\",\n `[Sixb] Agent approval mode must be one of: ${AGENT_APPROVAL_MODES.join(\", \")}.`\n )\n }\n return value\n}\n\n/** A user's mode in a thread: their choice there, then their default, then the fallback. */\nexport async function resolveAgentApprovalMode(\n agents: AgentStorage,\n input: {\n readonly projectId: string\n readonly principal: Principal\n /** Omitted for a thread the turn creates. */\n readonly threadId?: string\n }\n): Promise<ResolvedAgentApprovalMode> {\n const chosen =\n input.threadId === undefined\n ? null\n : await agents.approvalModes.getForThread({\n projectId: input.projectId,\n threadId: input.threadId,\n principal: input.principal,\n })\n return chosen === null\n ? defaultAgentApprovalMode(agents, input)\n : { approvalMode: chosen, approvalModeSource: \"thread\" }\n}\n\n/** The requester's default, or the fallback when they chose none. */\nexport async function defaultAgentApprovalMode(\n agents: AgentStorage,\n input: { readonly projectId: string; readonly principal: Principal }\n): Promise<ResolvedAgentApprovalMode> {\n const chosen = await agents.approvalModes.getDefault({\n projectId: input.projectId,\n principal: input.principal,\n })\n return chosen === null\n ? { approvalMode: FALLBACK_AGENT_APPROVAL_MODE, approvalModeSource: \"fallback\" }\n : { approvalMode: chosen, approvalModeSource: \"default\" }\n}\n\n/** The mode a run's calls are held by. A run admitted before approval modes has none: `auto`. */\nexport function agentRunApprovalMode(run: AgentRunRecord): AgentApprovalMode {\n return run.spec?.approvalMode ?? \"auto\"\n}\n\n/** What became of a call the Agent made through the gateway. */\nexport type AgentApprovalHold =\n /** The run's mode lets it run, or its requester approved it already. */\n | { readonly kind: \"pass\" }\n /** It waits for its requester: the route must not run it. */\n | { readonly kind: \"held\"; readonly approval: AgentApprovalRecord }\n | { readonly kind: \"denied\"; readonly approval: AgentApprovalRecord }\n /** The call's run id already names another call in the thread. */\n | { readonly kind: \"conflict\"; readonly approval: AgentApprovalRecord }\n\n/**\n * Hold a call the run's mode does not run, until whoever asked for the turn decides on it. A\n * child's call waits for the turn that spawned it. Asking again with the same run id finds the same\n * approval: an approved call passes, as its route returns the run the decision started.\n */\nexport async function holdAgentApprovalCall(\n agents: AgentStorage,\n input: {\n readonly projectId: string\n /** The running conversation turn or child that makes the call. */\n readonly run: AgentRunRecord\n /** The run's requester; absent when auth is disabled. */\n readonly requestedBy?: Principal\n /** Prepared as it would run. */\n readonly call: AgentApprovalCall\n readonly now?: Date\n }\n): Promise<AgentApprovalHold> {\n const { run, call } = input\n const mode = agentRunApprovalMode(run)\n if (mode === \"auto\" || approvalModeAllows(mode, call)) return { kind: \"pass\" }\n\n const executionToken = run.execution?.token\n if (!executionToken) {\n throw new Error(`[Sixb] Agent run '${run.id}' holds no delivery to fence its approval with.`)\n }\n\n const createdAt = input.now ?? new Date()\n const { approval, created } = await agents.approvals.request({\n id: `apr_${randomUUID()}`,\n projectId: input.projectId,\n runId: run.kind === \"subagent\" ? run.parentRunId : run.id,\n callerRunId: run.id,\n executionToken,\n requestedBy: input.requestedBy ?? SYSTEM_PRINCIPAL,\n mode,\n call,\n createdAt,\n expiresAt: new Date(createdAt.getTime() + AGENT_APPROVAL_TTL_MS),\n })\n if (!created && !isDeepStrictEqual(approval.call, call)) return { kind: \"conflict\", approval }\n\n switch (approval.status) {\n case \"approved\":\n return { kind: \"pass\" }\n case \"denied\":\n return { kind: \"denied\", approval }\n default:\n return { kind: \"held\", approval }\n }\n}\n\n/** The call as the model asked for it, without its params. */\nexport function approvalCallSummary(call: AgentApprovalCall): AgentApprovalCallSummary {\n return call.kind === \"action\"\n ? { kind: \"action\", actionId: call.actionId, subject: call.subject }\n : { kind: \"workflow\", workflowId: call.workflowId }\n}\n\n/** A call a child made that waits for its turn's requester. */\nexport interface AgentChildApprovalAwaiting {\n readonly approvalId: string\n readonly call: AgentApprovalCallSummary\n}\n\n/**\n * The calls each of a turn's children made that still wait for the turn's requester: they are\n * held on the turn, and name the child that asked.\n */\nexport async function listChildApprovalsAwaiting(\n agents: AgentStorage,\n input: {\n readonly projectId: string\n readonly parentRunId: string\n readonly childRunIds: readonly string[]\n }\n): Promise<ReadonlyMap<string, readonly AgentChildApprovalAwaiting[]>> {\n const children = new Set(input.childRunIds)\n const byChild = new Map<string, AgentChildApprovalAwaiting[]>()\n for (let offset = 0; ; ) {\n const page = await agents.approvals.list({\n projectId: input.projectId,\n runId: input.parentRunId,\n statuses: [\"pending\"],\n limit: 100,\n offset,\n })\n for (const approval of page.approvals) {\n if (!children.has(approval.callerRunId)) continue\n\n const awaiting = byChild.get(approval.callerRunId) ?? []\n awaiting.push({ approvalId: approval.id, call: approvalCallSummary(approval.call) })\n byChild.set(approval.callerRunId, awaiting)\n }\n offset += page.approvals.length\n if (!page.hasMore || page.approvals.length === 0) return byChild\n }\n}\n\n/**\n * In the transaction that admits a thread's next message: set its pending approvals aside, and\n * return one part per approval that left `pending` and no message reported yet, for the message to\n * carry. An approved call reports once it ran.\n */\nexport async function reportAgentApprovals(\n agents: AgentStorage,\n input: { readonly projectId: string; readonly threadId: string; readonly messageId: string }\n): Promise<{\n readonly parts: readonly AgentApprovalOutcomePart[]\n /** The approvals this message set aside, to announce once it is admitted. */\n readonly superseded: readonly AgentApprovalRecord[]\n}> {\n const superseded = await agents.approvals.settle({ ...input, status: \"superseded\" })\n return { parts: await reportSettledAgentApprovals(agents, input), superseded }\n}\n\n/** Whether the turn paused on held calls: it succeeded, waiting for its requester's decisions. */\nexport function isAwaitingApprovalRun(run: AgentRunRecord | null | undefined): boolean {\n return (\n run?.kind === \"conversation\" &&\n run.status === \"succeeded\" &&\n run.finishReason === \"awaiting_approval\"\n )\n}\n\n/**\n * Whether the child paused on its held calls: it succeeded before it was done. It continues once\n * they are decided and its turn resumes, unless a new message sets them aside, one expires or the\n * turn is stopped.\n */\nexport function isPausedSubagentRun(run: AgentRunRecord | null | undefined): boolean {\n return (\n run?.kind === \"subagent\" &&\n run.status === \"succeeded\" &&\n run.finishReason === \"awaiting_approval\"\n )\n}\n\n/**\n * How long a process keeps an approved call it took to run. Longer than an Action's 30-second\n * limit, so a claim still held is a call still running; a claim older than this was lost in a crash.\n */\nexport const AGENT_APPROVAL_EXECUTION_LEASE_MS = 2 * 60_000\n\n/** Where a paused turn stands, from the calls it held. */\nexport type AgentTurnReadiness =\n /** Every call was decided, every approved one ran, and none was reported yet. */\n | \"ready\"\n /** A call still waits for its decision, or an approved one has not run yet. */\n | \"waiting\"\n /**\n * It never resumes: a call was set aside, cancelled or expired, the turn was stopped, or it\n * resumed already. The thread's next message reports what is left.\n */\n | \"closed\"\n\nexport function turnResumeReadiness(approvals: readonly AgentApprovalRecord[]): AgentTurnReadiness {\n if (\n approvals.some(\n (approval) =>\n approval.status === \"pending\" ||\n (approval.status === \"approved\" && approval.outcome === undefined)\n )\n ) {\n return \"waiting\"\n }\n const resumable =\n approvals.length > 0 &&\n approvals.every(\n (approval) =>\n (approval.status === \"approved\" || approval.status === \"denied\") &&\n approval.turnStoppedAt === undefined\n ) &&\n approvals.some((approval) => approval.reportedInMessageId === undefined)\n return resumable ? \"ready\" : \"closed\"\n}\n\n/**\n * Whether a conversation turn pauses after a step on the calls it holds. Its own call pauses it\n * after the step that made it. A child's waits for the children still at work: the turn's end\n * would cancel them, and a child that holds a call pauses by itself.\n */\nexport async function turnPausesOnHeldCalls(\n agents: AgentStorage,\n run: { readonly projectId: string; readonly id: string }\n): Promise<boolean> {\n const { projectId, id: runId } = run\n if (!(await agents.approvals.holdsRun({ projectId, runId }))) return false\n\n const held = (await listTurnApprovals(agents, { projectId, runId })).filter((approval) =>\n agentApprovalHoldsRun(approval, runId)\n )\n if (held.some((approval) => approval.callerRunId === runId)) return true\n return !(await hasActiveChildren(agents, run))\n}\n\n/** Whether any child of the turn is queued or running. */\nexport async function hasActiveChildren(\n agents: AgentStorage,\n run: { readonly projectId: string; readonly id: string }\n): Promise<boolean> {\n const active = await agents.runs.list({\n projectId: run.projectId,\n kinds: [\"subagent\"],\n parentRunId: run.id,\n statuses: [\"queued\", \"running\"],\n limit: 1,\n })\n return active.total > 0\n}\n\n/** The calls a conversation turn held, its children's included. */\nexport async function listTurnApprovals(\n agents: AgentStorage,\n input: { readonly projectId: string; readonly runId: string }\n): Promise<readonly AgentApprovalRecord[]> {\n return (await agents.approvals.list({ projectId: input.projectId, runId: input.runId })).approvals\n}\n\n/**\n * The mode a resumed turn runs with: the paused turn's, raised only by \"Always allow\" on one of its\n * own calls, and lowered to the requester's choice in the thread when that is stricter. A user who\n * tightens the mode while a turn waits gets it at the resume; a looser choice never reaches it.\n */\nexport function resumedApprovalMode(\n paused: AgentApprovalMode,\n approvals: readonly AgentApprovalRecord[],\n /** The requester's own choice in the thread, `null` when they made none. */\n chosen: AgentApprovalMode | null\n): AgentApprovalMode {\n const raised = approvals.reduce<AgentApprovalMode>(\n (mode, { raisedMode }) =>\n raisedMode !== undefined && APPROVAL_MODE_RANK[raisedMode] > APPROVAL_MODE_RANK[mode]\n ? raisedMode\n : mode,\n paused\n )\n\n return chosen !== null && APPROVAL_MODE_RANK[chosen] < APPROVAL_MODE_RANK[raised]\n ? chosen\n : raised\n}\n\n/**\n * Stop a paused turn from resuming: its calls still waiting are cancelled, and the decided ones are\n * reported by the thread's next message. Returns how many calls it stopped; none means the turn had\n * nothing left to resume on.\n */\nexport async function stopAgentTurn(\n agents: AgentStorage,\n broker: Broker,\n turn: { readonly projectId: string; readonly threadId: string; readonly id: string }\n): Promise<number> {\n const { cancelled, stopped } = await agents.approvals.stop({\n projectId: turn.projectId,\n threadId: turn.threadId,\n runId: turn.id,\n })\n await announceAgentApprovals(broker, cancelled)\n return stopped\n}\n\n/** Announce changed approvals on the activity feed. Clients learn it best-effort. */\nexport async function announceAgentApprovals(\n broker: Broker,\n approvals: readonly AgentApprovalRecord[]\n): Promise<void> {\n try {\n await publishAgentApprovalActivity(broker, approvals)\n } catch (error) {\n console.error(\"[Sixb] Agent approval activity stream publish failed:\", error)\n }\n}\n\n/**\n * Mark and return, as message parts, the thread's approvals that left `pending` and no message\n * reported yet. An approved call reports once it ran: one still running when this message is\n * admitted stays for a later one.\n */\nexport async function reportSettledAgentApprovals(\n agents: AgentStorage,\n input: {\n readonly projectId: string\n readonly threadId: string\n readonly messageId: string\n /** A resume: the approvals of a stopped turn stay for the next message. */\n readonly resuming?: boolean\n }\n): Promise<readonly AgentApprovalOutcomePart[]> {\n const { approvals } = await agents.approvals.list({\n projectId: input.projectId,\n threadId: input.threadId,\n statuses: [\"approved\", \"denied\", \"cancelled\", \"superseded\", \"expired\"],\n reported: false,\n })\n const reportable = approvals.filter(\n (approval) => approval.status !== \"approved\" || approval.outcome !== undefined\n )\n if (reportable.length === 0) return []\n\n const marked = new Set(\n await agents.approvals.markReported({ ...input, ids: reportable.map(({ id }) => id) })\n )\n const reported = reportable.filter(({ id }) => marked.has(id))\n const callers = await agentApprovalCallers(agents, input.projectId, reported)\n return reported.map((approval) => {\n const caller = callers.get(approval.callerRunId)\n // Only a resume continues a child, and only one that paused on its calls.\n const continues = input.resuming === true && caller?.paused === true\n return approvalOutcomePart(\n approval,\n caller && { runId: caller.runId, key: caller.key, ...(continues ? { continues } : {}) }\n )\n })\n}\n\n/** A sub-agent that made a call: its run, its key, and whether it paused on its calls. */\nexport interface AgentApprovalCallerRun {\n readonly runId: string\n readonly key: string\n readonly paused: boolean\n}\n\n/** The sub-agents that made some of these calls, by run id. A turn's own calls have none. */\nexport async function agentApprovalCallers(\n agents: AgentStorage,\n projectId: string,\n approvals: readonly AgentApprovalRecord[]\n): Promise<ReadonlyMap<string, AgentApprovalCallerRun>> {\n const ids = approvals\n .filter((approval) => approval.callerRunId !== approval.runId)\n .map((approval) => approval.callerRunId)\n if (ids.length === 0) return new Map()\n\n const runs = await agents.runs.getByIds({ projectId, ids })\n return new Map(\n runs.flatMap((run) =>\n run.kind === \"subagent\"\n ? [\n [\n run.id,\n {\n runId: run.id,\n key: run.spawnKey,\n paused: isPausedSubagentRun(run),\n },\n ] as const,\n ]\n : []\n )\n )\n}\n\nfunction approvalOutcomePart(\n approval: AgentApprovalRecord,\n caller: AgentApprovalCaller | undefined\n): AgentApprovalOutcomePart {\n return {\n type: \"approval-outcome\",\n approvalId: approval.id,\n status: approval.status === \"pending\" ? \"superseded\" : approval.status,\n call: approvalCallSummary(approval.call),\n ...(approval.outcome === undefined ? {} : { outcome: approval.outcome }),\n ...(caller === undefined ? {} : { caller }),\n }\n}\n\n/**\n * Decide on a held call as `decidedBy`, who must be who asked for the turn: the call runs with their\n * rights. Only the decision that approves it runs it, as the run that made it and with the deciding\n * request's authority, and records its outcome. Approving again never starts it: it returns the\n * outcome, waiting for the run this process is making, or reading the call's run.\n */\nexport async function decideAgentApproval(\n agents: AgentStorage,\n executor: AgentApprovalExecutor,\n input: {\n readonly approval: AgentApprovalRecord\n readonly decision: \"approved\" | \"denied\"\n readonly decidedBy: Principal\n /** The deciding request: an approved call runs with its authority. */\n readonly decider: AgentApprovalDecider\n /** \"Always allow\": the mode the requester raises the turn's calls to with this approval. */\n readonly raisedMode?: AgentApprovalMode\n /** Where the decision is announced; the executor announces the call's outcome. */\n readonly broker: Broker\n }\n): Promise<AgentApprovalRecord> {\n const { approval } = input\n if (!principalsEqual(approval.requestedBy, input.decidedBy)) {\n throw new AgentRequestError(\n \"not_run_requester\",\n `[Sixb] Only whoever asked for Agent run '${approval.runId}' can decide on its approval '${approval.id}': the call runs with their rights.`\n )\n }\n\n const result = await agents.approvals.decide({\n projectId: approval.projectId,\n id: approval.id,\n decision: input.decision,\n decidedBy: input.decidedBy,\n ...(input.raisedMode === undefined ? {} : { raisedMode: input.raisedMode }),\n })\n const decided = result?.approval\n if (!result || !decided) {\n throw new AgentRequestError(\n \"approval_not_found\",\n `[Sixb] Agent approval '${approval.id}' was not found.`\n )\n }\n if (decided.status === \"expired\") {\n await announceAgentApprovals(input.broker, [decided])\n throw new AgentRequestError(\n \"approval_expired\",\n `[Sixb] Agent approval '${approval.id}' expired before it was decided. Ask the Agent again.`\n )\n }\n if (decided.status !== input.decision) {\n throw new AgentRequestError(\n \"approval_not_pending\",\n `[Sixb] Agent approval '${approval.id}' is already ${decided.status}.`\n )\n }\n\n if (decided.status !== \"approved\" || decided.outcome !== undefined) {\n if (result.decided) await announceAgentApprovals(input.broker, [decided])\n return decided\n }\n\n // Started before anything else is awaited, so a second approval finds it running.\n const running = result.decided ? executor.run(decided, input.decider) : executor.settle(decided)\n if (result.decided) await announceAgentApprovals(input.broker, [decided])\n return running\n}\n",
36
+ "import { assertAgentExecutionRecord } from \"../execution/agent\"\nimport type { SecurityDefinitionCatalog } from \"../security\"\nimport type { AuthStorage } from \"../storage/auth\"\nimport type { ExecutionRecord, ExecutionStorage } from \"../storage/executions\"\nimport {\n type AgentExecutionAuthorization,\n resolveAgentExecutionAuthorization,\n resolveInheritedAgentExecutionAuthorization,\n} from \"./authority\"\n\nexport interface AgentRunScopeHost {\n readonly id: string\n readonly storage: { readonly executions: ExecutionStorage; readonly auth?: AuthStorage }\n readonly definitions: { readonly security: SecurityDefinitionCatalog }\n}\n\n/** A conversation turn or a child inherits its requester's authority; a workflow node is managed. */\nexport type AgentRunScopeAuthority =\n | { readonly type: \"inherited\" }\n | { readonly type: \"managed\"; readonly actorId: string }\n\n/** What an Agent run's work is bound to: its own execution, with its current grants. */\nexport interface AgentRunExecutionScope {\n readonly execution: ExecutionRecord\n readonly actorId?: string\n readonly runId: string\n readonly authorization: AgentExecutionAuthorization\n}\n\nexport type AgentRunScopeErrorCode =\n /** The run's execution record is missing. */\n | \"execution_unavailable\"\n /** The record names a principal, and the runtime has no auth storage to resolve it. */\n | \"auth_unavailable\"\n /** The record's authority no longer resolves, or does not belong to the run. */\n | \"authority_invalid\"\n\nexport class AgentRunScopeError extends Error {\n readonly name = \"AgentRunScopeError\"\n\n constructor(\n readonly code: AgentRunScopeErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n\n/**\n * Restore an Agent run's execution from server-side records only: the run's execution record, then\n * the grants its authority has now. The agent API gateway binds every request to it, and a decided\n * approval runs its call under it.\n */\nexport async function resolveAgentRunExecutionScope(\n host: AgentRunScopeHost,\n run: {\n readonly runId: string\n readonly executionId: string\n readonly authority: AgentRunScopeAuthority\n }\n): Promise<AgentRunExecutionScope> {\n const execution = await host.storage.executions.getById({\n projectId: host.id,\n id: run.executionId,\n })\n if (!execution) {\n throw new AgentRunScopeError(\n \"execution_unavailable\",\n `[Sixb] Agent run '${run.runId}' execution is not available.`\n )\n }\n\n // Authority comes from the record whether auth is enabled or not: an auth-disabled record is\n // unrestricted, and a workflow AI task has its groups, as for its in-process tools. Only a record\n // naming a principal needs auth storage.\n const auth = host.storage.auth\n if (!auth && execution.authorizationRef.type !== \"disabled\") {\n throw new AgentRunScopeError(\n \"auth_unavailable\",\n `[Sixb] Agent run '${run.runId}' needs auth storage to resolve its authority.`\n )\n }\n\n try {\n const authorization = await resolveAuthorization(host, auth, run, execution)\n return {\n execution,\n ...(run.authority.type === \"managed\" ? { actorId: run.authority.actorId } : {}),\n runId: run.runId,\n authorization,\n }\n } catch (error) {\n throw new AgentRunScopeError(\n \"authority_invalid\",\n `[Sixb] Agent run '${run.runId}' execution authority is not valid: ${\n error instanceof Error ? error.message : String(error)\n }`\n )\n }\n}\n\nasync function resolveAuthorization(\n host: AgentRunScopeHost,\n auth: AuthStorage | undefined,\n run: { readonly runId: string; readonly authority: AgentRunScopeAuthority },\n execution: ExecutionRecord\n): Promise<AgentExecutionAuthorization> {\n if (run.authority.type === \"inherited\") {\n const authorization = await resolveInheritedAgentExecutionAuthorization({\n auth,\n projectId: host.id,\n authorizationRef: execution.authorizationRef,\n security: host.definitions.security,\n })\n assertAgentExecutionRecord({ execution, runId: run.runId, authorization })\n return authorization\n }\n\n const resolved = await resolveAgentExecutionAuthorization({\n auth,\n projectId: host.id,\n actorId: run.authority.actorId,\n authorizationRef: execution.authorizationRef,\n security: host.definitions.security,\n })\n const authorization = { type: \"principal\", context: resolved.context } as const\n assertAgentExecutionRecord({\n execution,\n actorId: run.authority.actorId,\n runId: run.runId,\n authorization,\n })\n return authorization\n}\n",
37
+ "import type { SixbRuntimeContext } from \"../runtime/types\"\nimport {\n type AgentRunRecord,\n type AgentStorage,\n AgentStorageError,\n type ConversationAgentRunRecord,\n} from \"../storage/agents\"\nimport { isAwaitingApprovalRun, stopAgentTurn } from \"./approvals\"\nimport { AgentRequestError } from \"./errors\"\nimport { publishAgentRunCancel, publishAgentRunFinished } from \"./streams/protocol\"\n\n/**\n * Stop a turn. A queued turn ends here, before any worker starts it. A running turn receives the\n * stop signal its worker obeys, so it is still running when this returns. A turn paused on held\n * calls is returned as it ended, `awaiting_approval`, and never resumes: its waiting calls are\n * cancelled. Who may stop it is the caller's decision.\n */\nexport async function cancelAgentRun(\n runtime: SixbRuntimeContext,\n run: ConversationAgentRunRecord\n): Promise<ConversationAgentRunRecord> {\n const storage = runtime.storage.agents\n if (!storage) {\n throw new AgentRequestError(\"storage_unavailable\", \"[Sixb] Agent storage is not configured.\")\n }\n\n let current = run\n if (current.status === \"queued\") {\n const queued = await cancelQueuedRun(runtime, storage, current)\n if (queued.cancelled) {\n if (queued.run.kind !== \"conversation\") {\n throw new Error(`[Sixb] Agent run '${queued.run.id}' changed kind.`)\n }\n return queued.run\n }\n\n if (queued.run?.kind !== \"conversation\") {\n throw new AgentRequestError(\"run_not_found\", `[Sixb] Agent run '${run.id}' was not found.`)\n }\n current = queued.run\n }\n\n // A paused turn is stopped from resuming: its waiting calls are cancelled, and the thread's next\n // message reports them and the decided ones. Nothing left to stop means it resumed already.\n if (\n isAwaitingApprovalRun(current) &&\n (await stopAgentTurn(storage, runtime.broker, current)) > 0\n ) {\n return current\n }\n\n if (current.status !== \"running\") {\n throw new AgentRequestError(\n \"run_not_active\",\n `[Sixb] Agent run '${current.id}' is not active: it is ${current.status}.`\n )\n }\n\n await publishAgentRunCancel(runtime.broker, { projectId: runtime.projectId, runId: current.id })\n return current\n}\n\n/**\n * Cancel a queued run before any worker starts it. The worker may have started it after the\n * caller's read but before `finishQueued` locked it: then the run comes back as it is now, for the\n * caller to stop as a running one. A retained control record is safe even if the worker has not\n * attached its cancel subscription yet.\n */\nexport async function cancelQueuedRun(\n runtime: SixbRuntimeContext,\n storage: AgentStorage,\n run: AgentRunRecord\n): Promise<\n | { readonly cancelled: true; readonly run: AgentRunRecord }\n | { readonly cancelled: false; readonly run: AgentRunRecord | null }\n> {\n try {\n const cancelled = await storage.runs.finishQueued({\n projectId: runtime.projectId,\n id: run.id,\n status: \"cancelled\",\n })\n await publishQueuedRunCancellation(runtime, cancelled)\n return { cancelled: true, run: cancelled }\n } catch (error) {\n if (!(error instanceof AgentStorageError) || error.code !== \"invalid_state\") throw error\n }\n\n const current = await storage.runs.getById({ projectId: runtime.projectId, id: run.id })\n return { cancelled: false, run: current }\n}\n\n/** The run is cancelled once stored; its stream learns it best-effort. */\nasync function publishQueuedRunCancellation(\n runtime: SixbRuntimeContext,\n run: AgentRunRecord\n): Promise<void> {\n try {\n await publishAgentRunFinished(runtime.broker, run)\n } catch (error) {\n console.error(`[Sixb] Agent run '${run.id}' cancellation stream publish failed:`, error)\n }\n}\n",
38
+ "import { isJsonObject } from \"../json\"\nimport type { AgentRunRecord } from \"../storage/agents\"\nimport type { AgentMessage } from \"./message\"\n\n/** A question a sub-agent asked its parent: the id of its mail and what it asks. */\nexport interface AgentChildQuestion {\n readonly id: string\n readonly text: string\n}\n\n/**\n * Whether the child paused on its question when its turn ended: it continues once a later turn of\n * the conversation answers it under its key.\n */\nexport function isAwaitingAnswerRun(run: AgentRunRecord | null | undefined): boolean {\n return (\n run?.kind === \"subagent\" && run.status === \"succeeded\" && run.finishReason === \"awaiting_answer\"\n )\n}\n\n/**\n * The question a run's messages paused on: its `ask_parent` call whose answer was deferred to a\n * later turn, which names the question's id.\n */\nexport function deferredChildQuestion(\n messages: readonly Pick<AgentMessage, \"parts\">[]\n): AgentChildQuestion | undefined {\n const asked = messages\n .flatMap((message) => message.parts)\n .flatMap((part) =>\n part.type === \"tool-call\" &&\n part.toolName === \"ask_parent\" &&\n part.state === \"output-available\" &&\n isJsonObject(part.output) &&\n part.output.status === \"deferred\" &&\n isJsonObject(part.input)\n ? [{ input: part.input, output: part.output }]\n : []\n )\n .at(-1)\n if (!asked) return undefined\n\n const { question: text } = asked.input\n const { question: id } = asked.output\n return typeof text === \"string\" && typeof id === \"string\" ? { id, text: text.trim() } : undefined\n}\n",
39
+ "import type { AgentStorage, SubagentRunRecord } from \"../storage/agents\"\n\nconst PAGE = 100\n\n/**\n * A sub-agent's thread's runs, in the order they ran: by creation, then, for runs created in the\n * same instant, by where their trigger is in the thread. Runs are single-flight in a thread, so each\n * trigger follows the work of the runs before it. A run whose messages left the thread, an attempt\n * a retry removed, comes first among those created with it.\n */\nexport async function listSubagentThreadRuns(\n agents: AgentStorage,\n input: { readonly projectId: string; readonly threadId: string }\n): Promise<readonly SubagentRunRecord[]> {\n const runs: SubagentRunRecord[] = []\n for (;;) {\n const page = await agents.runs.list({\n projectId: input.projectId,\n threadId: input.threadId,\n kinds: [\"subagent\"],\n order: \"asc\",\n limit: PAGE,\n offset: runs.length,\n })\n runs.push(...page.runs.filter((run) => run.kind === \"subagent\"))\n if (!page.hasMore || page.runs.length === 0) break\n }\n\n const triggers = await Promise.all(\n runs.map((run) =>\n agents.messages.getById({ projectId: input.projectId, id: run.triggerMessageId })\n )\n )\n const seqOf = new Map(runs.map((run, index) => [run.id, triggers[index]?.seq ?? -1]))\n return runs.sort(\n (a, b) =>\n a.createdAt.getTime() - b.createdAt.getTime() ||\n (seqOf.get(a.id) ?? -1) - (seqOf.get(b.id) ?? -1) ||\n a.id.localeCompare(b.id)\n )\n}\n",
40
+ "import type { SixbFailure } from \"../errors/types\"\nimport type { LanguageModelRef, LanguageModelTier } from \"../models\"\nimport { addCostSummaries } from \"../runtime/ai-cost\"\nimport { addUsageSummaries } from \"../runtime/ai-usage\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type {\n AgentApprovalRecord,\n AgentRunFailureCode,\n AgentRunFinishReason,\n AgentRunRecord,\n AgentRunStatus,\n AgentStorage,\n AgentThreadRecord,\n SubagentRunFile,\n SubagentRunRecord,\n SubagentRunResult,\n} from \"../storage/agents\"\nimport type { AiCostSummary } from \"../storage/ai-cost\"\nimport type { AiModelCallUsage } from \"../storage/ai-usage\"\nimport { resolveTurnAccounting } from \"./accounting\"\nimport { isPausedSubagentRun, turnResumeReadiness } from \"./approvals\"\nimport { cancelQueuedRun } from \"./cancel\"\nimport {\n type AgentChildQuestion,\n deferredChildQuestion,\n isAwaitingAnswerRun,\n} from \"./child-question\"\nimport { AgentRequestError } from \"./errors\"\nimport { publishAgentRunCancel } from \"./streams/protocol\"\nimport { listSubagentThreadRuns } from \"./subagent-runs\"\nimport type { AgentReasoning } from \"./types\"\n\n// A child the Agent spawned works in a thread of its own, however many runs it takes: a child that\n// paused on its held calls or its question continues, once decided or answered, as the next run of\n// its thread, under the turn that goes on. Readers see the thread as one child.\n\n/** What a child waits for before it goes on. */\nexport type AgentChildAwaiting =\n | {\n /** Its calls still waiting for the turn's requester, filed on the turn that ran it. */\n readonly type: \"approval\"\n readonly approvalIds: readonly string[]\n }\n | {\n /** Its calls were decided: it continues once its turn resumes. */\n readonly type: \"resume\"\n }\n | {\n /**\n * It paused on the question it asked its parent when the parent's turn ended: a later turn of\n * the conversation answers it, and it continues with the answer.\n */\n readonly type: \"answer\"\n readonly question: AgentChildQuestion\n }\n\n/**\n * Why a paused child never continues. On its calls: a new message set them aside, one expired, or\n * its turn was stopped, its requester leaving among the reasons. On its question: the Agent spawned\n * another child under its key, which a later answer would reach instead.\n */\nexport type AgentChildEndReason = \"superseded\" | \"expired\" | \"stopped\" | \"replaced\"\n\n/** One run of a child: the one spawned, or one that continued it. */\nexport interface AgentChildRunView {\n readonly id: string\n /** The turn the run worked under: the one that spawned the child, or one that went on with it. */\n readonly parentRunId: string\n readonly status: AgentRunStatus\n readonly finishReason?: AgentRunFinishReason\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly modelId?: string\n readonly attempt: number\n readonly createdAt: Date\n readonly startedAt?: Date\n readonly completedAt?: Date\n /** What it answered, and the files it wrote under `out/`. */\n readonly result?: SubagentRunResult\n /** Its own model calls and those of what it ran. */\n readonly usage?: AiModelCallUsage\n readonly cost?: AiCostSummary\n}\n\n/** A child of a conversation, its thread, with every run it took. */\nexport interface AgentChildView {\n /** Its first run's id: the one `spawn_agent` answered with. */\n readonly id: string\n /** Its own thread, whose messages are what it did. */\n readonly threadId: string\n readonly projectId: string\n /** The turn that spawned it. */\n readonly spawnedBy: string\n readonly key: string\n readonly task: string\n readonly model: LanguageModelRef\n readonly tier?: LanguageModelTier\n readonly reasoning?: AgentReasoning\n /** What its parent handed it, by path in its sandbox. */\n readonly handedFiles: readonly SubagentRunFile[]\n /** Its latest run's. */\n readonly status: AgentRunStatus\n readonly finishReason?: AgentRunFinishReason\n readonly error?: SixbFailure<AgentRunFailureCode>\n /** Set while its latest run paused, until it continues. */\n readonly awaiting?: AgentChildAwaiting\n /** Set when its latest run paused and it will not continue. */\n readonly ended?: { readonly reason: AgentChildEndReason }\n /** Its run at work, which streams; `null` when none is. */\n readonly activeRunId: string | null\n readonly createdAt: Date\n /** Its latest run's, once that ended. */\n readonly completedAt?: Date\n /** Every run of it. */\n readonly usage?: AiModelCallUsage\n readonly cost?: AiCostSummary\n /** Oldest first: the run spawned, then each that continued it. */\n readonly runs: readonly AgentChildRunView[]\n}\n\nconst PAGE = 100\n\n/** A conversation's children, oldest first: all of them, or those one of its turns spawned. */\nexport async function listAgentChildren(\n runtime: SixbRuntimeContext,\n conversation: AgentThreadRecord,\n options: { readonly spawnedBy?: string } = {}\n): Promise<readonly AgentChildView[]> {\n const agents = requireAgents(runtime)\n const threads: AgentThreadRecord[] = []\n for (;;) {\n const page = await agents.threads.listChildren({\n projectId: runtime.projectId,\n parentThreadId: conversation.id,\n ...(options.spawnedBy === undefined ? {} : { parentRunId: options.spawnedBy }),\n limit: PAGE,\n offset: threads.length,\n })\n threads.push(...page)\n if (page.length < PAGE) break\n }\n return readChildren(runtime, conversation, threads)\n}\n\n/** The child that works in `thread`, a sub-agent's thread of `conversation`. */\nexport async function readAgentChild(\n runtime: SixbRuntimeContext,\n conversation: AgentThreadRecord,\n thread: AgentThreadRecord\n): Promise<AgentChildView | null> {\n if (thread.parent?.threadId !== conversation.id) return null\n const [child] = await readChildren(runtime, conversation, [thread])\n return child ?? null\n}\n\n/**\n * Stop a child's run at work. A queued one is cancelled here; a running one receives the stop signal\n * its worker obeys, so it is still running when this returns. Who may stop it is the caller's\n * decision.\n */\nexport async function cancelAgentChildRun(\n runtime: SixbRuntimeContext,\n run: SubagentRunRecord\n): Promise<AgentRunRecord> {\n let current: AgentRunRecord | null = run\n if (run.status === \"queued\") {\n const queued = await cancelQueuedRun(runtime, requireAgents(runtime), run)\n if (queued.cancelled) return queued.run\n current = queued.run\n }\n\n if (current?.status !== \"running\") {\n throw new AgentRequestError(\n \"run_not_active\",\n `[Sixb] Sub-agent run '${run.id}' is not at work: it is ${current?.status ?? run.status}.`\n )\n }\n await publishAgentRunCancel(runtime.broker, { projectId: runtime.projectId, runId: run.id })\n return current\n}\n\nasync function readChildren(\n runtime: SixbRuntimeContext,\n conversation: AgentThreadRecord,\n threads: readonly AgentThreadRecord[]\n): Promise<readonly AgentChildView[]> {\n if (threads.length === 0) return []\n\n const agents = requireAgents(runtime)\n const runsOf = await Promise.all(threads.map((thread) => listThreadRuns(agents, thread)))\n const runs = runsOf.flat()\n const approvals = createTurnApprovals(agents, runtime.projectId)\n\n const accounting = await resolveTurnAccounting(\n runtime,\n runs.map((run) => run.executionId)\n )\n const accounted = new Map(runs.map((run, index) => [run.id, accounting[index] ?? {}]))\n\n const children = await Promise.all(\n threads.map(async (thread, index) => {\n const own = runsOf[index] ?? []\n const first = own[0]\n const latest = own.at(-1)\n if (!first || !latest) return null\n\n const views = own.map((run) => childRunView(run, accounted.get(run.id) ?? {}))\n const usage = addUsageSummaries(views.flatMap((view) => (view.usage ? [view.usage] : [])))\n const cost = addCostSummaries(views.flatMap((view) => (view.cost ? [view.cost] : [])))\n const paused = isPausedSubagentRun(latest)\n ? await pausedState(agents, approvals, latest)\n : await questionState(agents, conversation.id, thread, own)\n\n return {\n id: first.id,\n threadId: thread.id,\n projectId: thread.projectId,\n spawnedBy: first.parentRunId,\n key: first.spawnKey,\n task: first.spec.task,\n model: first.spec.model,\n ...(first.spec.tier === undefined ? {} : { tier: first.spec.tier }),\n ...(first.spec.reasoning === undefined ? {} : { reasoning: first.spec.reasoning }),\n handedFiles: first.spec.files ?? [],\n status: latest.status,\n ...(latest.finishReason === undefined ? {} : { finishReason: latest.finishReason }),\n ...(latest.error === undefined ? {} : { error: latest.error }),\n ...paused,\n activeRunId: thread.activeRunId,\n createdAt: thread.createdAt,\n ...(latest.completedAt === undefined ? {} : { completedAt: latest.completedAt }),\n ...(usage === undefined ? {} : { usage }),\n ...(cost === undefined ? {} : { cost }),\n runs: views,\n } satisfies AgentChildView\n })\n )\n return children.filter((child) => child !== null)\n}\n\n/** A child thread's runs, in the order they ran. */\nfunction listThreadRuns(\n agents: AgentStorage,\n thread: AgentThreadRecord\n): Promise<readonly SubagentRunRecord[]> {\n return listSubagentThreadRuns(agents, { projectId: thread.projectId, threadId: thread.id })\n}\n\nfunction childRunView(\n run: SubagentRunRecord,\n accounting: { readonly usage?: AiModelCallUsage; readonly cost?: AiCostSummary }\n): AgentChildRunView {\n return {\n id: run.id,\n parentRunId: run.parentRunId,\n status: run.status,\n ...(run.finishReason === undefined ? {} : { finishReason: run.finishReason }),\n ...(run.error === undefined ? {} : { error: run.error }),\n ...(run.modelId === undefined ? {} : { modelId: run.modelId }),\n attempt: run.attempt,\n createdAt: run.createdAt,\n ...(run.startedAt === undefined ? {} : { startedAt: run.startedAt }),\n ...(run.completedAt === undefined ? {} : { completedAt: run.completedAt }),\n ...(run.result === undefined ? {} : { result: run.result }),\n ...(accounting.usage === undefined ? {} : { usage: accounting.usage }),\n ...(accounting.cost === undefined ? {} : { cost: accounting.cost }),\n }\n}\n\n/** A turn's approvals, read once per turn however many of its children ask. */\ninterface TurnApprovals {\n of(turnId: string): Promise<readonly AgentApprovalRecord[]>\n}\n\nfunction createTurnApprovals(agents: AgentStorage, projectId: string): TurnApprovals {\n const read = new Map<string, Promise<readonly AgentApprovalRecord[]>>()\n\n return {\n of(turnId) {\n const known = read.get(turnId)\n if (known) return known\n\n const approvals = listAllApprovals(agents, projectId, turnId)\n read.set(turnId, approvals)\n return approvals\n },\n }\n}\n\n/**\n * Where a paused child stands, from its calls and its turn's: still waiting for decisions, decided\n * and continuing once the turn resumes, or ended without continuing. Every call reported by a\n * message: only a resume that continues it keeps it going.\n */\nasync function pausedState(\n agents: AgentStorage,\n approvals: TurnApprovals,\n run: SubagentRunRecord\n): Promise<Pick<AgentChildView, \"awaiting\" | \"ended\">> {\n const turnApprovals = await approvals.of(run.parentRunId)\n const own = turnApprovals.filter((approval) => approval.callerRunId === run.id)\n\n const pending = own.filter((approval) => approval.status === \"pending\")\n if (pending.length > 0) {\n return { awaiting: { type: \"approval\", approvalIds: pending.map((approval) => approval.id) } }\n }\n\n const ended = { ended: { reason: endReason(own, turnApprovals) } }\n const reportedIn = new Set(own.flatMap((approval) => approval.reportedInMessageId ?? []))\n if (reportedIn.size === 0) {\n // A stopped turn never resumes, even on a call still running when it was stopped.\n const stopped = turnApprovals.some((approval) => approval.turnStoppedAt !== undefined)\n const closed = stopped || turnResumeReadiness(turnApprovals) === \"closed\"\n return closed ? ended : { awaiting: { type: \"resume\" } }\n }\n\n for (const messageId of reportedIn) {\n const message = await agents.messages.getById({ projectId: run.projectId, id: messageId })\n const continues = message?.parts.some(\n (part) =>\n part.type === \"approval-outcome\" &&\n part.caller?.runId === run.id &&\n part.caller.continues === true\n )\n // Reported by the resume, whose turn admits its continuation before its model runs.\n if (continues) return { awaiting: { type: \"resume\" } }\n }\n return ended\n}\n\n/**\n * Where a child that paused on its question stands: waiting for a later turn's answer while its\n * thread is the latest under its key in the conversation, else replaced. A continuation that\n * failed or was stopped leaves the question open again, so the run waiting is the one before it.\n */\nasync function questionState(\n agents: AgentStorage,\n conversationId: string,\n thread: AgentThreadRecord,\n runs: readonly SubagentRunRecord[]\n): Promise<Pick<AgentChildView, \"awaiting\" | \"ended\">> {\n const waiting = [...runs]\n .reverse()\n .find((run) => run.status !== \"failed\" && run.status !== \"cancelled\")\n if (!waiting || !isAwaitingAnswerRun(waiting)) return {}\n\n const [latest] = await agents.runs.listThreadSubagents({\n projectId: waiting.projectId,\n threadId: conversationId,\n spawnKey: waiting.spawnKey,\n limit: 1,\n })\n if (latest && latest.threadId !== thread.id) return { ended: { reason: \"replaced\" } }\n\n // Its question is in the last message of the run that paused.\n const { messages } = await agents.messages.list({\n projectId: thread.projectId,\n threadId: thread.id,\n order: \"desc\",\n limit: 2,\n })\n const work = messages.find(\n (message) => message.runId === waiting.id && message.role === \"assistant\"\n )\n const question = work ? deferredChildQuestion([work]) : undefined\n return question ? { awaiting: { type: \"answer\", question } } : {}\n}\n\n/** Its own calls say why first, then its turn's: a sibling's call set aside closes the turn too. */\nfunction endReason(\n own: readonly AgentApprovalRecord[],\n turn: readonly AgentApprovalRecord[]\n): AgentChildEndReason {\n for (const approvals of [own, turn]) {\n if (approvals.some((approval) => approval.status === \"superseded\")) return \"superseded\"\n if (approvals.some((approval) => approval.status === \"expired\")) return \"expired\"\n }\n return \"stopped\"\n}\n\nasync function listAllApprovals(\n agents: AgentStorage,\n projectId: string,\n runId: string\n): Promise<readonly AgentApprovalRecord[]> {\n const approvals: AgentApprovalRecord[] = []\n for (;;) {\n const page = await agents.approvals.list({\n projectId,\n runId,\n limit: PAGE,\n offset: approvals.length,\n })\n approvals.push(...page.approvals)\n if (!page.hasMore || page.approvals.length === 0) return approvals\n }\n}\n\nfunction requireAgents(runtime: SixbRuntimeContext): AgentStorage {\n const agents = runtime.storage.agents\n if (!agents) {\n throw new AgentRequestError(\"storage_unavailable\", \"[Sixb] Agent storage is not configured.\")\n }\n return agents\n}\n",
41
+ "import { getInvalidJsonValueReason, isPlainRecord } from \"../json\"\nimport { OntologyValidationError } from \"../ontology/errors\"\nimport type { OntologyRegistry } from \"../ontology/registry\"\nimport type { SandboxDefinition } from \"../sandboxes/configuration\"\nimport { normalizeParams } from \"../shared/params/validation\"\nimport type { AgentThreadSandboxParams } from \"../storage/agents/types\"\nimport { AgentRequestError } from \"./errors\"\n\nexport function normalizeSandboxBinding(\n definition: Pick<SandboxDefinition, \"params\"> | undefined,\n input: unknown,\n ontology: OntologyRegistry\n): AgentThreadSandboxParams {\n if (!definition) {\n throw new AgentRequestError(\n \"sandbox_not_configured\",\n \"[Sixb] This sandbox provider has no compatible thread configuration.\"\n )\n }\n if (!isPlainRecord(input)) {\n throw new AgentRequestError(\n \"invalid_sandbox_params\",\n \"[Sixb] sandbox must be an object containing the declared parameter values.\"\n )\n }\n try {\n const params = normalizeParams(ontology.getValueTypesById(), definition.params, input, {\n kind: \"sandbox\",\n id: \"sandboxes\",\n path: \"sandbox\",\n })\n if (getInvalidJsonValueReason(params)) {\n throw new OntologyValidationError(\"[Sixb] Sandbox params must normalize to JSON values.\")\n }\n return params\n } catch (error) {\n throw new AgentRequestError(\n \"invalid_sandbox_params\",\n error instanceof OntologyValidationError\n ? error.message\n : \"[Sixb] Sandbox params could not be normalized.\"\n )\n }\n}\n",
42
+ "import { createRuntimeArtifactAccessRule } from \"../artifacts/execution\"\nimport { createArtifactId } from \"../artifacts/ids\"\nimport type { Principal } from \"../auth\"\nimport type { SixbDependencies } from \"../runtime/sixb\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport { AgentStorageError, type AgentThreadRecord } from \"../storage/agents\"\nimport { ArtifactStorageError } from \"../storage/artifacts/errors\"\nimport type { ArtifactStorage, CopyArtifactInput } from \"../storage/artifacts/types\"\nimport type { Storage } from \"../storage/types\"\nimport { AgentRequestError } from \"./errors\"\nimport { createAgentThreadId, createAgentThreadSandboxName } from \"./ids\"\nimport { normalizeSandboxBinding } from \"./sandbox\"\n\n/**\n * Copy a thread of the caller's, or one shared with them, into a new thread the caller owns alone.\n *\n * The caller has already checked that `source` is visible. A workspace binding is checked again\n * against the project's current sandbox definition, and the fork gets a sandbox of its own.\n */\nexport async function forkAgentThread(\n runtime: SixbRuntimeContext,\n input: {\n readonly source: AgentThreadRecord\n readonly ownerPrincipal: Principal\n readonly sandbox?: SixbDependencies[\"sandbox\"]\n }\n): Promise<AgentThreadRecord> {\n const storage = runtime.storage.agents\n if (!storage) {\n throw new AgentRequestError(\"storage_unavailable\", \"[Sixb] Agent storage is not configured.\")\n }\n\n const { source, sandbox } = input\n if (source.sandboxParams !== undefined && !sandbox?.supportsPersistence) {\n throw new AgentRequestError(\n \"sandbox_not_configured\",\n \"[Sixb] Thread sandboxes require a provider with persistence support.\"\n )\n }\n\n const id = createAgentThreadId()\n const sandboxParams =\n source.sandboxParams === undefined\n ? undefined\n : normalizeSandboxBinding(sandbox?.definition, source.sandboxParams, runtime.ontology)\n\n try {\n // One transaction: a fork that fails leaves no copy behind, and none copied is missing.\n return await runtime.storage.transaction(async (tx) => {\n const threads = tx.agents?.threads\n if (!threads) {\n throw new AgentRequestError(\n \"storage_unavailable\",\n \"[Sixb] Agent storage is not configured.\"\n )\n }\n\n const artifactCopies = await copySharedArtifacts(runtime, tx, {\n sourceThreadId: source.id,\n forkId: id,\n owner: input.ownerPrincipal,\n })\n\n return threads.fork({\n projectId: runtime.projectId,\n sourceThreadId: source.id,\n id,\n ownerPrincipal: input.ownerPrincipal,\n ...(source.title === undefined ? {} : { title: source.title }),\n ...(sandboxParams === undefined\n ? {}\n : {\n sandboxParams,\n sandboxName: createAgentThreadSandboxName(runtime.projectId, id),\n }),\n ...(Object.keys(artifactCopies).length === 0 ? {} : { artifactCopies }),\n })\n })\n } catch (error) {\n if (error instanceof AgentStorageError && error.code === \"thread_not_found\") {\n throw new AgentRequestError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${source.id}' not found.`\n )\n }\n\n throw error\n }\n}\n\n/**\n * The fork's own copies of the artifacts the source shares that the caller reads, by the artifact\n * access rule: every one for a signed-in session, only its own for an access token. Each copy has\n * every version under its number, so a copied card or an `@N` address still resolves; it reuses\n * the files, which blob storage keeps by content, is owned by whoever forks, and is shared in the\n * fork alone. A copy keeps its addresses: one naming another artifact still names the original.\n * Returns each source id with its copy's.\n */\nasync function copySharedArtifacts(\n runtime: SixbRuntimeContext,\n tx: Storage,\n input: {\n readonly sourceThreadId: string\n readonly forkId: string\n readonly owner: Principal\n }\n): Promise<Record<string, string>> {\n const { projectId } = runtime\n const artifacts = tx.artifacts\n if (!artifacts) {\n const shared = await runtime.storage.artifacts?.list({\n projectId,\n threadId: input.sourceThreadId,\n limit: 1,\n })\n if (shared && shared.total > 0) {\n throw new AgentRequestError(\n \"storage_unavailable\",\n \"[Sixb] Forking a conversation that shares artifacts needs artifacts and Agent threads in one storage.\"\n )\n }\n return {}\n }\n\n const access = createRuntimeArtifactAccessRule(runtime, tx)\n const copies: Record<string, string> = {}\n const { artifacts: shared } = await artifacts.list({ projectId, threadId: input.sourceThreadId })\n for (const artifact of shared) {\n if ((await access.accessTo(artifact)) === \"none\") continue\n\n copies[artifact.id] = await createCopy(artifacts, {\n projectId,\n sourceId: artifact.id,\n owner: input.owner,\n threadId: input.forkId,\n })\n }\n return copies\n}\n\n/** A copy of the artifact under a fresh id. */\nasync function createCopy(\n artifacts: ArtifactStorage,\n input: Omit<CopyArtifactInput, \"id\">\n): Promise<string> {\n for (let attempt = 1; ; attempt += 1) {\n const id = createArtifactId()\n try {\n await artifacts.copy({ ...input, id })\n return id\n } catch (error) {\n const collided = error instanceof ArtifactStorageError && error.code === \"artifact_exists\"\n if (!collided || attempt === COPY_ATTEMPTS) throw error\n }\n }\n}\n\nconst COPY_ATTEMPTS = 3\n",
43
+ "/**\n * Agent memory repos: a folder of linked Markdown files with `MEMORY.md` as the entry point, in the\n * Agent Memory Repo format. These rules decide what a save may contain before it reaches storage.\n */\n\nimport type { Principal } from \"../auth\"\nimport type { AgentMemoryChange, AgentMemoryFile } from \"../storage/agents\"\nimport { AgentMemoryError } from \"./errors\"\n\n/** The two repos a conversation reaches: its user's own, and the one the project shares. */\nexport type AgentMemoryRepoName = \"user\" | \"project\"\n\nexport const AGENT_MEMORY_REPO_NAMES: readonly AgentMemoryRepoName[] = [\"user\", \"project\"]\n\n/** The file every repo starts from, and the one rendered into every conversation's prompt. */\nexport const AGENT_MEMORY_ENTRY = \"MEMORY.md\"\n\nexport const AGENT_MEMORY_LIMITS = {\n /** `MEMORY.md` is part of every prompt. */\n entryBytes: 16 * 1024,\n fileBytes: 256 * 1024,\n repoBytes: 4 * 1024 * 1024,\n pathLength: 256,\n messageLength: 500,\n} as const\n\n/** A link to a path that is not in the repo, found in one of its Markdown files. */\nexport interface AgentMemoryLinkWarning {\n /** The file the link is in. */\n readonly path: string\n readonly link: string\n}\n\nconst encoder = new TextEncoder()\n\n/**\n * The storage id of a repo: `user:<userId>` or `project`. A caller with no user of its own keeps\n * its memory as `system:<id>`: a project without auth, or app code running as the system, which\n * then reads a repo no signed-in user's conversation does.\n */\nexport function agentMemoryRepoId(repo: AgentMemoryRepoName, owner: Principal | null): string {\n if (repo === \"project\") return \"project\"\n if (!owner || owner.type === \"serviceAccount\") {\n throw new AgentMemoryError(\n \"not_allowed\",\n \"[Sixb] Agent memory of its own belongs to a signed-in user.\"\n )\n }\n return `${owner.type}:${owner.id}`\n}\n\nexport function parseAgentMemoryRepoName(value: string): AgentMemoryRepoName {\n if (value === \"user\" || value === \"project\") return value\n throw new AgentMemoryError(\n \"invalid_repo\",\n `[Sixb] Agent memory repo '${value}' does not exist. Use 'user' or 'project'.`\n )\n}\n\n/** Why a path cannot hold a memory file, or `null` when it can. */\nexport function agentMemoryPathProblem(path: string): string | null {\n if (path.length === 0) return \"is empty\"\n if (path.length > AGENT_MEMORY_LIMITS.pathLength) {\n return `is longer than ${AGENT_MEMORY_LIMITS.pathLength} characters`\n }\n if (/[\\u0000-\\u001f\\u007f\\\\]/.test(path)) return \"contains a backslash or a control character\"\n if (path.startsWith(\"/\")) return \"is absolute; paths start at the repo root\"\n const segments = path.split(\"/\")\n if (segments.some((segment) => segment.length === 0)) return \"has an empty segment\"\n if (segments.some((segment) => segment === \".\" || segment === \"..\")) {\n return \"has a '.' or '..' segment\"\n }\n if (segments.some((segment) => segment.startsWith(\".\"))) return \"names a dotfile\"\n if (path.endsWith(\".theirs\")) return \"is a conflict copy; merge it into its file and delete it\"\n return null\n}\n\n/**\n * Apply `changes` to the repo's current files and check the result, so a save is rejected with\n * an error the Agent can act on. Returns the repo as the save leaves it.\n */\nexport function applyAgentMemoryChanges(\n current: readonly AgentMemoryFile[],\n message: string,\n changes: readonly AgentMemoryChange[]\n): AgentMemoryFile[] {\n const fail = (detail: string): never => {\n throw new AgentMemoryError(\"invalid_save\", `[Sixb] Agent memory ${detail}`)\n }\n\n if (message.trim().length === 0) fail(\"save needs a message saying what was learned.\")\n if (message.length > AGENT_MEMORY_LIMITS.messageLength) {\n fail(`save message is longer than ${AGENT_MEMORY_LIMITS.messageLength} characters.`)\n }\n if (changes.length === 0) fail(\"save changes no file.\")\n\n const files = new Map(current.map((file) => [file.path, file.contents]))\n const seen = new Set<string>()\n for (const change of changes) {\n const problem = agentMemoryPathProblem(change.path)\n if (problem) fail(`path '${change.path}' ${problem}.`)\n if (seen.has(change.path)) fail(`save changes '${change.path}' more than once.`)\n seen.add(change.path)\n\n if (change.contents === null) {\n files.delete(change.path)\n continue\n }\n if (change.contents.includes(\"\\u0000\")) fail(`file '${change.path}' is not text.`)\n const bytes = encoder.encode(change.contents).byteLength\n if (change.path === AGENT_MEMORY_ENTRY && bytes > AGENT_MEMORY_LIMITS.entryBytes) {\n fail(\n `${AGENT_MEMORY_ENTRY} is over ${kilobytes(AGENT_MEMORY_LIMITS.entryBytes)}, and it is part of every prompt. Move entries into topic files and link them.`\n )\n }\n if (bytes > AGENT_MEMORY_LIMITS.fileBytes) {\n fail(`file '${change.path}' is over ${kilobytes(AGENT_MEMORY_LIMITS.fileBytes)}.`)\n }\n files.set(change.path, change.contents)\n }\n\n if (!files.has(AGENT_MEMORY_ENTRY)) {\n fail(`repo must keep its ${AGENT_MEMORY_ENTRY}.`)\n }\n let total = 0\n for (const contents of files.values()) total += encoder.encode(contents).byteLength\n if (total > AGENT_MEMORY_LIMITS.repoBytes) {\n fail(\n `repo would be over ${kilobytes(AGENT_MEMORY_LIMITS.repoBytes)}. Remove entries that are cheap to look up again.`\n )\n }\n\n return [...files].map(([path, contents]) => ({ path, contents }))\n}\n\n/**\n * Links in the repo's Markdown files that point at no file. A `[[target]]` names a path from the\n * repo root, with `.md` left out and any other extension kept.\n */\nexport function findBrokenAgentMemoryLinks(\n files: readonly AgentMemoryFile[]\n): AgentMemoryLinkWarning[] {\n const paths = new Set(files.map((file) => file.path))\n const warnings: AgentMemoryLinkWarning[] = []\n for (const file of files) {\n if (!file.path.endsWith(\".md\")) continue\n for (const link of agentMemoryLinks(file.contents)) {\n if (!paths.has(agentMemoryLinkPath(link))) warnings.push({ path: file.path, link })\n }\n }\n return warnings.sort((left, right) =>\n left.path === right.path ? compare(left.link, right.link) : compare(left.path, right.path)\n )\n}\n\n/** The distinct `[[link]]` targets in a Markdown file, in the order they first appear. */\nexport function agentMemoryLinks(contents: string): string[] {\n const links = new Set<string>()\n for (const match of contents.matchAll(/\\[\\[([^[\\]\\n]+)\\]\\]/g)) {\n const link = match[1]?.trim()\n if (link) links.add(link)\n }\n return [...links]\n}\n\n/** The file a link names: `.md` is added unless its last segment already has an extension. */\nexport function agentMemoryLinkPath(link: string): string {\n const name = link.slice(link.lastIndexOf(\"/\") + 1)\n return name.includes(\".\") ? link : `${link}.md`\n}\n\nfunction kilobytes(bytes: number): string {\n return bytes >= 1024 * 1024 ? `${bytes / (1024 * 1024)} MB` : `${bytes / 1024} KB`\n}\n\nfunction compare(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n",
44
+ "import { type Principal, SYSTEM_PRINCIPAL } from \"../auth\"\nimport { isRuntimeAllowed } from \"../authorization\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type {\n AgentMemoryChange,\n AgentMemoryFile,\n AgentMemoryStore,\n ListAgentMemoryRevisionsResult,\n} from \"../storage/agents\"\nimport { AgentMemoryError } from \"./errors\"\nimport {\n type AgentMemoryLinkWarning,\n type AgentMemoryRepoName,\n agentMemoryRepoId,\n applyAgentMemoryChanges,\n findBrokenAgentMemoryLinks,\n} from \"./memory\"\n\n/** A memory repo as the caller sees it. */\nexport interface AgentMemoryRepoView {\n readonly repo: AgentMemoryRepoName\n /** 0 before the first save. */\n readonly revision: number\n /** Ordered by path. */\n readonly files: readonly AgentMemoryFile[]\n}\n\nexport interface SaveAgentMemoryRuntimeInput {\n /** The revision the changes were made against. */\n readonly baseRevision: number\n /** What was learned, as the revision's entry in the repo's history. */\n readonly message: string\n /** `contents: null` deletes the file. */\n readonly changes: readonly AgentMemoryChange[]\n /** The conversation the save came from, `/agents/<threadId>`. */\n readonly source?: string\n}\n\nexport type SaveAgentMemoryRuntimeResult =\n | {\n readonly saved: true\n readonly revision: number\n /** Links in the saved repo that point at no file. */\n readonly warnings: readonly AgentMemoryLinkWarning[]\n }\n | {\n readonly saved: false\n /** The repo's latest revision. */\n readonly revision: number\n /** Files in `changes` that another save changed after `baseRevision`, as they are now. */\n readonly conflicts: readonly AgentMemoryChange[]\n }\n\n/**\n * The Agent's memory: `user` is the caller's own; `project` is built up by everyone who can run the\n * Agent, who all read and save it, and deleted only with `can.manage(agent.memory)`.\n */\nexport interface AgentMemoryRuntime {\n /**\n * With `asOf`, the repo at the latest revision saved by then; with `revision`, as that revision\n * left it.\n */\n get(\n repo: AgentMemoryRepoName,\n options?: { readonly asOf?: Date; readonly revision?: number }\n ): Promise<AgentMemoryRepoView>\n save(\n repo: AgentMemoryRepoName,\n input: SaveAgentMemoryRuntimeInput\n ): Promise<SaveAgentMemoryRuntimeResult>\n /** Newest first. */\n listRevisions(\n repo: AgentMemoryRepoName,\n input?: { readonly limit?: number; readonly offset?: number }\n ): Promise<ListAgentMemoryRevisionsResult>\n /** Deletes the repo with its history. */\n delete(repo: AgentMemoryRepoName): Promise<void>\n}\n\nconst SOURCE_PATTERN = /^\\/agents\\/[A-Za-z0-9_-]{1,128}$/\n\nexport function createAgentMemoryRuntime(runtime: SixbRuntimeContext): AgentMemoryRuntime {\n const authority = resolveRuntimeAuthorizationForProject(runtime)\n // Shared-link sessions and unresolved authority reach no memory.\n const caller: Principal | null =\n authority.type === \"principal\"\n ? authority.context.principal\n : authority.type === \"unrestricted\"\n ? SYSTEM_PRINCIPAL\n : null\n\n const requireStorage = (): AgentMemoryStore => {\n const storage = runtime.storage.agents?.memory\n if (!storage) {\n throw new AgentMemoryError(\n \"storage_unavailable\",\n \"[Sixb] Agent memory needs storage that supports the Agent.\"\n )\n }\n return storage\n }\n\n const canManageProject = () => isRuntimeAllowed(runtime, { kind: \"agentMemory.manage\" })\n\n /** The repo's storage id, once the caller may read and save it. */\n const usable = (repo: AgentMemoryRepoName): string => {\n if (\n repo === \"project\" &&\n !isRuntimeAllowed(runtime, { kind: \"agent.run\" }) &&\n !canManageProject()\n ) {\n throw new AgentMemoryError(\n \"not_allowed\",\n \"[Sixb] The project's Agent memory needs can.run(agent) or can.manage(agent.memory).\"\n )\n }\n return agentMemoryRepoId(repo, caller)\n }\n\n /** The repo's storage id, once the caller may delete it with its history. */\n const deletable = (repo: AgentMemoryRepoName): string => {\n const repoId = usable(repo)\n if (repo === \"project\" && !canManageProject()) {\n throw new AgentMemoryError(\n \"not_allowed\",\n \"[Sixb] Deleting the project's Agent memory needs can.manage(agent.memory).\"\n )\n }\n return repoId\n }\n\n return {\n async get(repo, options = {}) {\n const repoId = usable(repo)\n const { revision, files } = await requireStorage().get({\n projectId: runtime.projectId,\n repoId,\n ...(options.asOf === undefined ? {} : { asOf: options.asOf }),\n ...(options.revision === undefined ? {} : { revision: options.revision }),\n })\n return { repo, revision, files }\n },\n\n async save(repo, input) {\n const repoId = usable(repo)\n if (!Number.isSafeInteger(input.baseRevision) || input.baseRevision < 0) {\n throw new AgentMemoryError(\n \"invalid_save\",\n \"[Sixb] Agent memory base revision must be the revision the changes were made against.\"\n )\n }\n if (input.source !== undefined && !SOURCE_PATTERN.test(input.source)) {\n throw new AgentMemoryError(\n \"invalid_save\",\n \"[Sixb] Agent memory source must be a conversation link, '/agents/<threadId>'.\"\n )\n }\n const storage = requireStorage()\n const current = await storage.get({ projectId: runtime.projectId, repoId })\n const files = applyAgentMemoryChanges(current.files, input.message, input.changes)\n const result = await storage.save({\n projectId: runtime.projectId,\n repoId,\n baseRevision: input.baseRevision,\n message: input.message.trim(),\n author: caller ?? SYSTEM_PRINCIPAL,\n ...(input.source === undefined ? {} : { source: input.source }),\n changes: input.changes,\n })\n return result.saved ? { ...result, warnings: findBrokenAgentMemoryLinks(files) } : result\n },\n\n async listRevisions(repo, input = {}) {\n return requireStorage().listRevisions({\n projectId: runtime.projectId,\n repoId: usable(repo),\n ...input,\n })\n },\n\n async delete(repo) {\n await requireStorage().delete({ projectId: runtime.projectId, repoId: deletable(repo) })\n },\n }\n}\n",
45
+ "import type {\n DecisionModelsRuntime,\n LanguageModelCatalog,\n LanguageModelEntry,\n LanguageModelTier,\n LanguageModelTierProbabilities,\n ModelCatalog,\n} from \"../models\"\nimport { LANGUAGE_MODEL_TIERS } from \"../models/catalog\"\nimport { question } from \"../models/decision/questions\"\nimport { supportsQuestion } from \"../models/decision/validation\"\nimport { RuntimeError } from \"../runtime/errors\"\nimport type { ConversationAgentRunRecord } from \"../storage/agents\"\n\n/** Moving up needs no confidence: a turn goes to `heavy` from this probability. */\nconst HEAVY_FROM = 0.4\n\n/** Moving down does: a turn goes to `light` only from this probability. */\nconst LIGHT_FROM = 0.8\n\n/**\n * How long a turn waits for its tier before it aims for `standard`. Jev answers in about 150 ms;\n * the margin covers a gateway's slow start, and every millisecond delays the answer's first token.\n */\nconst DECISION_TIMEOUT_MS = 2_000\n\n/** How long a provider keeps a thread's prompt cache after the last call that read it. */\nconst PROMPT_CACHE_TTL_MS = 5 * 60_000\n\nconst TIER_QUESTIONS = {\n tier: question.choice({\n instructions:\n \"A user sent this message to a data agent. The agent answers from the project's data with \" +\n \"tools: it searches and reads objects, queries and aggregates datasets, follows links, runs \" +\n \"actions and writes reports. Pick the model tier the answer needs. Judge the work the \" +\n \"answer takes, not the length or tone of the message.\",\n options: {\n light:\n \"A lookup, a count, a filter or a list: one or two queries with an obvious answer. \" +\n \"Greetings, thanks and short follow-ups.\",\n standard:\n \"Usual analysis: several queries, comparisons, trends or aggregations, a short summary, \" +\n \"or a simple action, with a clear path to the answer.\",\n heavy:\n \"Open-ended work: a multi-step investigation, explaining why something happened, \" +\n \"weighing trade-offs, building a plan, or writing a long report.\",\n },\n }),\n}\n\nexport interface TurnModelChoice {\n readonly model: LanguageModelEntry\n /** The decision model's answer; absent when it failed and the turn aimed for `standard`. */\n readonly tierProbabilities?: LanguageModelTierProbabilities\n}\n\nexport interface TurnModelRouter {\n /** The model of a turn that names none, given the thread's previous turn. */\n choose(text: string, previous: ConversationAgentRunRecord | undefined): Promise<TurnModelChoice>\n}\n\n/**\n * With tiers, the default decision model picks the tier of each turn, so it must take the question.\n * Checked at startup: a model that cannot would leave every turn on `standard`, warning each time.\n */\nexport function assertTurnModelRouting(models: ModelCatalog | undefined): void {\n const tiers = models?.language?.tiers ?? []\n const decision = models?.decision?.default\n if (tiers.length === 0 || !decision) return\n if (supportsQuestion(decision.model.definition.capabilities, TIER_QUESTIONS.tier)) return\n\n throw new RuntimeError(\n `[Sixb] The default decision model '${decision.provider}/${decision.modelId}' cannot pick the tier of an Agent turn: it needs 'choice' questions with ${LANGUAGE_MODEL_TIERS.length} options. Put a decision model that supports them first in 'models.decision', or configure 'models.language' as a list.`\n )\n}\n\n/** Sixb picks the model of each turn when the project configures tiers and a decision model. */\nexport function createTurnModelRouter(\n models: ModelCatalog | undefined,\n decision: DecisionModelsRuntime\n): TurnModelRouter | undefined {\n const language = models?.language\n if (!language || language.tiers.length === 0 || !models?.decision) return undefined\n\n return {\n async choose(text, previous) {\n const tierProbabilities = await askTier(decision, text)\n const tier = tierProbabilities ? tierFor(tierProbabilities) : \"standard\"\n\n return {\n model: turnModel(language, tier, previous),\n ...(tierProbabilities ? { tierProbabilities } : {}),\n }\n },\n }\n}\n\n/** The decision model's answer, or nothing when it fails or is too slow. */\nasync function askTier(\n decision: DecisionModelsRuntime,\n text: string\n): Promise<LanguageModelTierProbabilities | undefined> {\n const timeout = new AbortController()\n const timer = setTimeout(() => {\n timeout.abort(\n new DOMException(\"[Sixb] The decision model did not answer in time.\", \"TimeoutError\")\n )\n }, DECISION_TIMEOUT_MS)\n\n try {\n // The race holds the turn to its timeout even when a provider ignores the signal.\n const { output } = await Promise.race([\n decision.evaluate({ input: text, questions: TIER_QUESTIONS, signal: timeout.signal }),\n rejectOnAbort(timeout.signal),\n ])\n const { light, standard, heavy } = output.tier.probabilities\n return { light, standard, heavy }\n } catch (error) {\n // The request's own cancellation still cancels the message.\n if (!timeout.signal.aborted && isAbortError(error)) throw error\n\n console.warn(\n \"[Sixb] Could not pick the tier of an Agent turn; it aims for standard, and the cache rule still applies.\",\n error\n )\n return undefined\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** Moving down needs confidence; moving up doesn't. */\nfunction tierFor(probabilities: LanguageModelTierProbabilities): LanguageModelTier {\n if (probabilities.heavy >= HEAVY_FROM) return \"heavy\"\n if (probabilities.light >= LIGHT_FROM) return \"light\"\n return \"standard\"\n}\n\n/**\n * Switching models drops the prompt cache, so the thread stays on its model unless the switch is\n * free: a harder turn always moves up, an easier one moves down only once the cache is cold.\n */\nfunction turnModel(\n language: LanguageModelCatalog,\n tier: LanguageModelTier,\n previous: ConversationAgentRunRecord | undefined\n): LanguageModelEntry {\n const target = language.getByTier(tier)\n const last = previous && previousTurn(language, previous)\n if (!last) return target\n\n const change = tierRank(target.tier ?? tier) - tierRank(last.tier)\n if (change > 0 || last.model === null) return target\n if (change === 0 || last.cacheWarm) return last.model\n return target\n}\n\ninterface PreviousTurn {\n /** Null once the model has left the catalog. */\n readonly model: LanguageModelEntry | null\n readonly tier: LanguageModelTier\n readonly cacheWarm: boolean\n}\n\n/** An older run without a tier takes its model's; one without either counts as no turn at all. */\nfunction previousTurn(\n language: LanguageModelCatalog,\n run: ConversationAgentRunRecord\n): PreviousTurn | undefined {\n if (!run.spec) return undefined\n\n const model = language.getByRef(run.spec.model)\n const tier = run.spec.tier ?? model?.tier\n if (tier === undefined) return undefined\n\n // A run that never recorded its end counts from its start, or from its admission.\n const lastCallAt = run.completedAt ?? run.startedAt ?? run.createdAt\n return { model, tier, cacheWarm: Date.now() - lastCallAt.getTime() < PROMPT_CACHE_TTL_MS }\n}\n\nfunction tierRank(tier: LanguageModelTier): number {\n return LANGUAGE_MODEL_TIERS.indexOf(tier)\n}\n\nfunction rejectOnAbort(signal: AbortSignal): Promise<never> {\n return new Promise((_, reject) => {\n signal.addEventListener(\"abort\", () => reject(signal.reason), { once: true })\n })\n}\n\nfunction isAbortError(error: unknown): boolean {\n return (error instanceof DOMException || error instanceof Error) && error.name === \"AbortError\"\n}\n",
46
+ "import { principalsEqual, type UserPrincipal } from \"../auth\"\nimport { userReferenceProblem } from \"../ontology/user-ref\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type { SecurityDefinitionCatalog } from \"../security\"\nimport {\n type AgentStorage,\n AgentStorageError,\n type AgentThreadParticipantRecord,\n} from \"../storage/agents\"\nimport { announceAgentApprovals } from \"./approvals\"\nimport { userCanRunAgent } from \"./authority\"\nimport { AgentRequestError } from \"./errors\"\nimport {\n type AgentThreadAccessRule,\n type AgentThreadView,\n assertConversationThread,\n} from \"./thread-access\"\n\n/** At most this many users take part in one conversation, besides its owner. */\nexport const MAX_AGENT_THREAD_PARTICIPANTS = 50\n\n/** A user to add: by id, or by the email of their account. */\nexport type AgentThreadParticipantInput = UserPrincipal | { readonly email: string }\n\n/** Add users to a conversation. Only its owner may, and only active users of the project. */\nexport async function addAgentThreadParticipants(\n runtime: SixbRuntimeContext,\n rule: AgentThreadAccessRule,\n security: SecurityDefinitionCatalog,\n threadId: string,\n users: readonly AgentThreadParticipantInput[]\n): Promise<AgentThreadView> {\n const storage = requireStorage(runtime)\n const readable = await rule.read(threadId)\n if (!readable) throw threadNotFound(threadId)\n // A sub-agent's thread is read by its conversation's participants.\n assertConversationThread(readable.thread)\n\n if (readable.access !== \"owner\") {\n throw new AgentRequestError(\n \"not_thread_owner\",\n `[Sixb] Only the owner of Agent thread '${threadId}' can add participants to it.`\n )\n }\n\n const principals = await activeUsers(runtime, security, users)\n if (principals.some((user) => principalsEqual(user, readable.thread.ownerPrincipal))) {\n throw invalidParticipant(\"The thread's owner already takes part in it; add other users.\")\n }\n\n let participants: readonly AgentThreadParticipantRecord[]\n try {\n participants = await storage.threads.addParticipants({\n projectId: runtime.projectId,\n threadId,\n principals,\n addedBy: rule.caller,\n maxParticipants: MAX_AGENT_THREAD_PARTICIPANTS,\n })\n } catch (error) {\n if (error instanceof AgentStorageError && error.code === \"participant_limit\") {\n throw invalidParticipant(\n `An Agent thread can have at most ${MAX_AGENT_THREAD_PARTICIPANTS} participants.`\n )\n }\n throw error\n }\n\n return {\n ...readable.thread,\n participants: participants.map(({ principal, addedAt, addedBy }) => ({\n principal,\n addedAt,\n addedBy,\n })),\n }\n}\n\n/**\n * Remove a user from a conversation. Its owner removes anyone; a participant removes only\n * themself, which is how they leave. Removing someone who does not take part changes nothing.\n */\nexport async function removeAgentThreadParticipant(\n runtime: SixbRuntimeContext,\n rule: AgentThreadAccessRule,\n threadId: string,\n user: UserPrincipal\n): Promise<void> {\n requireStorage(runtime)\n const readable = await rule.read(threadId)\n if (!readable) throw threadNotFound(threadId)\n assertConversationThread(readable.thread)\n\n const principal = userOf(user)\n\n if (principalsEqual(principal, readable.thread.ownerPrincipal)) {\n throw invalidParticipant(\"The thread's owner cannot be removed from it.\")\n }\n if (readable.access !== \"owner\" && !principalsEqual(principal, rule.caller)) {\n throw new AgentRequestError(\n \"not_thread_owner\",\n `[Sixb] Only the owner of Agent thread '${threadId}' can remove other participants.`\n )\n }\n\n // Their turns never resume: the calls still waiting are cancelled, and the thread's next message\n // reports what they decided.\n const { cancelled } = await runtime.storage.transaction(async (tx) => {\n const agents = tx.agents\n if (!agents) {\n throw new AgentRequestError(\"storage_unavailable\", \"[Sixb] Agent storage is not configured.\")\n }\n await agents.threads.removeParticipant({ projectId: runtime.projectId, threadId, principal })\n return agents.approvals.stop({ projectId: runtime.projectId, threadId, requestedBy: principal })\n })\n await announceAgentApprovals(runtime.broker, cancelled)\n}\n\n/**\n * Each user once, by their account: an email resolves to its user. The only place that checks who\n * may take part: storage receives distinct users and enforces only the limit. An unknown or\n * suspended email is refused in the words an unknown or suspended id is, so it tells no more.\n */\nasync function activeUsers(\n runtime: SixbRuntimeContext,\n security: SecurityDefinitionCatalog,\n users: readonly AgentThreadParticipantInput[]\n): Promise<UserPrincipal[]> {\n if (!Array.isArray(users) || users.length === 0) {\n throw invalidParticipant(\"Name at least one user.\")\n }\n if (users.length > MAX_AGENT_THREAD_PARTICIPANTS) {\n throw invalidParticipant(\n `Add at most ${MAX_AGENT_THREAD_PARTICIPANTS} users to an Agent thread at once.`\n )\n }\n\n const auth = runtime.storage.auth\n const unique = new Map<string, UserPrincipal>()\n for (const user of users) {\n const email = emailOf(user)\n const account =\n auth &&\n (email === undefined\n ? await auth.users.getById({ projectId: runtime.projectId, id: userOf(user).id })\n : await auth.users.getByEmail({ projectId: runtime.projectId, email }))\n\n const named = email ?? userOf(user).id\n const status = auth ? (account?.status ?? null) : \"unverifiable\"\n const problem = userReferenceProblem(\"Agent thread participant\", named, status)\n if (problem || !account || !auth) {\n throw new AgentRequestError(\n \"invalid_participant\",\n problem ?? `[Sixb] Unknown user '${named}'.`\n )\n }\n\n // Someone who cannot use the Agent could never read the conversation they were added to.\n const allowed = await userCanRunAgent({\n auth,\n projectId: runtime.projectId,\n userId: account.id,\n security,\n })\n if (!allowed) {\n throw invalidParticipant(\n `User '${named}' cannot use the Agent: a role granting can.run(agent) must reach them first.`\n )\n }\n\n unique.set(account.id, { type: \"user\", id: account.id })\n }\n return [...unique.values()]\n}\n\n/** The trimmed email of an input naming a user by email; `undefined` for one naming an id. */\nfunction emailOf(user: AgentThreadParticipantInput): string | undefined {\n if (!user || typeof user !== \"object\" || !(\"email\" in user)) return undefined\n\n const email = typeof user.email === \"string\" ? user.email.trim() : \"\"\n if (!email) throw invalidParticipant(\"A user's email must not be empty.\")\n return email\n}\n\n/** A user named by id, with the id trimmed. */\nfunction userOf(user: AgentThreadParticipantInput): UserPrincipal {\n const id =\n user && \"type\" in user && user.type === \"user\" && typeof user.id === \"string\"\n ? user.id.trim()\n : \"\"\n if (!id) {\n throw invalidParticipant(\n `Only users take part in an Agent thread: pass { type: \"user\", id } or { email }, not ${JSON.stringify(user)}.`\n )\n }\n return { type: \"user\", id }\n}\n\nfunction requireStorage(runtime: SixbRuntimeContext): AgentStorage {\n const storage = runtime.storage.agents\n if (!storage) {\n throw new AgentRequestError(\"storage_unavailable\", \"[Sixb] Agent storage is not configured.\")\n }\n return storage\n}\n\nfunction threadNotFound(threadId: string): AgentRequestError {\n return new AgentRequestError(\"thread_not_found\", `[Sixb] Agent thread '${threadId}' not found.`)\n}\n\nfunction invalidParticipant(message: string): AgentRequestError {\n return new AgentRequestError(\"invalid_participant\", `[Sixb] ${message}`)\n}\n",
47
+ "import { randomUUID } from \"node:crypto\"\nimport type { Principal } from \"../auth\"\nimport { SYSTEM_PRINCIPAL } from \"../auth\"\nimport { assertAuthorized } from \"../authorization\"\nimport type { FileRef } from \"../blob-storage\"\nimport { isValidFileRef } from \"../blob-storage/validation\"\nimport {\n canInheritAgentRequestAuthorization,\n createInheritedAgentExecutionRecord,\n} from \"../execution/agent\"\nimport { resolveExecutionScopeAuthorization } from \"../execution/authorization\"\nimport { ensureExecutionRecord, executionRecordInputFromRuntime } from \"../execution/durable\"\nimport type { ExecutionContext } from \"../execution/types\"\nimport type {\n LanguageModelCatalog,\n LanguageModelEntry,\n LanguageModelRef,\n LanguageModelTierProbabilities,\n} from \"../models\"\nimport { isModelReasoning, modelReasoningSupportIssue } from \"../models/language-model\"\nimport { resolveLanguageModel } from \"../models/resolve\"\nimport { canonicalLocale, canonicalTimeZone } from \"../runtime/locale\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport {\n type AgentApprovalMode,\n type AgentApprovalRecord,\n type AgentStorage,\n AgentStorageError,\n type AgentThreadRecord,\n type ConversationAgentRunRecord,\n type ConversationAgentRunSpec,\n} from \"../storage/agents\"\nimport {\n aiLimitSubjectsFromAttribution,\n aiUsageLimitExceededError,\n aiUsageLimitUnavailableError,\n applicableAiLimitPolicyStatuses,\n} from \"../storage/ai-limits/enforcement\"\nimport type { AiLimitPolicyStatus } from \"../storage/ai-limits/types\"\nimport type { ExecutionRecord } from \"../storage/executions\"\nimport {\n type AgentTurnReadiness,\n announceAgentApprovals,\n assertAgentApprovalMode,\n isAwaitingApprovalRun,\n listTurnApprovals,\n reportAgentApprovals,\n reportSettledAgentApprovals,\n resolveAgentApprovalMode,\n turnResumeReadiness,\n} from \"./approvals\"\nimport type { AgentContextEntryInput } from \"./context/entries\"\nimport { resolveAgentContextParts } from \"./context-resolution\"\nimport { dispatchQueuedAgentRuns } from \"./dispatch\"\nimport { AgentRequestError } from \"./errors\"\nimport { createAgentMessageId, createAgentRunId, createAgentThreadId } from \"./ids\"\nimport type { AgentMessagePart } from \"./message\"\nimport type { TurnModelRouter } from \"./model-routing\"\nimport { assertNoAgentSelector } from \"./retired-config\"\nimport { publishAgentRunActivity } from \"./streams/protocol\"\nimport { assertConversationThread } from \"./thread-access\"\nimport { AGENT_REASONING_LEVELS, type AgentReasoning } from \"./types\"\n\nexport interface RequestAgentRunInput {\n /** The user's message that triggers the turn. Omitted only to {@link continue}. */\n readonly text?: string\n /**\n * Continue an answer the turn limit cut short, in an existing thread. Sixb writes the\n * instruction the model reads, so the request carries no text, attachments, or context.\n */\n readonly continue?: boolean\n /** Blob-backed files attached to the trigger message. */\n readonly attachments?: readonly FileRef[]\n /** Structured page/object context snapshotted onto the triggering user message. */\n readonly context?: readonly AgentContextEntryInput[]\n /** Continue an existing thread. Omitted → a fresh thread is created for this agent. */\n readonly threadId?: string\n /** Configured language model selected for this turn. Omitted uses the agent default. */\n readonly model?: LanguageModelRef\n /** Reasoning effort or token budget for this turn. Omitted uses the model's default. */\n readonly reasoning?: AgentReasoning\n /**\n * IANA time zone of the person asking, such as their browser's. The Agent presents dates and\n * times in it. Omitted uses the project time zone.\n */\n readonly timeZone?: string\n /** BCP 47 language of the person asking. Omitted uses the project locale. */\n readonly locale?: string\n /**\n * What the turn may change without asking whoever sent it. Omitted uses their choice in the\n * thread, then their default, then `auto`.\n */\n readonly approvalMode?: AgentApprovalMode\n /** Title to stamp on the thread when one is created. */\n readonly title?: string\n /** Explicit id for the trigger (user) message. Defaults to a generated id. */\n readonly messageId?: string\n /** Caller principal for privileged integrations; scoped runtimes use their authorization principal. */\n readonly principal?: Principal\n}\n\n/** What a turn's model is chosen from. */\nexport interface AgentRequestModels {\n readonly language?: LanguageModelCatalog\n /** Picks the model of a turn that names none; absent without tiers and `models.decision`. */\n readonly router?: TurnModelRouter\n}\n\nexport interface RequestAgentRunResult {\n /** The durable queued run exactly as it was created (`status: \"queued\"`, attempt 0). */\n readonly run: ConversationAgentRunRecord\n /** The enqueued job id, when the queue returns one. */\n readonly jobId?: string\n /** Whether this call created the thread. */\n readonly createdThread: boolean\n}\n\n/**\n * Trigger an agent turn.\n *\n * The user message and a `queued` run are persisted atomically before the queue intent is\n * published. This makes accepted work visible immediately and lets refresh reconstruct queue state.\n * The run's thread claim is the single-flight authority; a second request receives\n * `active_run_exists` before it can leave an orphan message.\n */\nexport async function requestAgentRun(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n models: AgentRequestModels,\n input: RequestAgentRunInput\n): Promise<RequestAgentRunResult> {\n const authority = resolveExecutionScopeAuthorization(runtime.projectId, {\n execution,\n authorization: runtime.runtimeAuthorization,\n })\n assertNoAgentSelector(input)\n assertAuthorized(runtime, { kind: \"agent.run\" })\n assertRequestAuthorityCanRunAgent(runtime)\n const trigger = triggerParts(input)\n const continued = input.continue ? await continuedSelection(runtime, models.language, input) : {}\n const selection = {\n model: input.model ?? continued.model,\n reasoning: input.reasoning ?? continued.reasoning,\n }\n const settings = requesterSettings(input)\n if (input.approvalMode !== undefined) assertAgentApprovalMode(input.approvalMode)\n\n // Any other turn's spec is checked now, before anything is written. A routed turn holds its\n // router until its model is picked, last.\n const routed = routedTurn(models.router, selection, input.text)\n const requested =\n routed ?? (await resolveConversationRunSpec({ models: models.language, selection, settings }))\n assertAttachments(input.attachments)\n\n // Resolve context before creating a thread: invalid or inaccessible references must not leave an\n // empty conversation behind. The resulting parts are the exact snapshot persisted below.\n const contextParts = await resolveAgentContextParts(runtime, input.context)\n\n const agents = requireAgentStorage(runtime)\n const projectId = runtime.projectId\n // Attribution comes from the exact capability/execution pair, never the optional context cache\n // on the runtime. `input.principal` remains available to unrestricted server integrations that\n // have already authenticated their request.\n const principal =\n authority.type === \"principal\"\n ? authority.context.principal\n : (input.principal ?? SYSTEM_PRINCIPAL)\n const runId = createAgentRunId()\n const durableExecution = await prepareDurableAgentExecution(runtime, execution, runId)\n await assertAiLimitPreflight(runtime, durableExecution)\n\n const existingThread = input.threadId\n ? await agents.threads.getById({ projectId, id: input.threadId })\n : null\n if (existingThread) assertThreadAcceptsRun(existingThread)\n // The message's mode, else the sender's in the thread.\n const approvalMode =\n input.approvalMode ??\n (await resolveAgentApprovalMode(agents, { projectId, principal, threadId: existingThread?.id }))\n .approvalMode\n\n // Last before anything is written, so a message the checks above refuse never reaches the\n // decision model. Concurrent messages to an idle thread can still each ask before one of them is\n // refused with `active_run_exists` below.\n const selected =\n \"router\" in requested\n ? await routedConversationRunSpec(agents, {\n ...requested,\n projectId,\n threadId: existingThread?.id,\n settings,\n language: models.language,\n })\n : requested\n const spec: ConversationAgentRunSpec = Object.freeze({ ...selected, approvalMode })\n\n const createdThread = existingThread === null\n const thread =\n existingThread ??\n (await createThread(agents, {\n projectId,\n threadId: input.threadId,\n title: input.title,\n principal,\n }))\n\n const triggerMessageId = input.messageId ?? createAgentMessageId()\n let run: ConversationAgentRunRecord\n let superseded: readonly AgentApprovalRecord[] = []\n try {\n run = await runtime.storage.transaction(async (tx) => {\n const agents = tx.agents\n if (!agents) {\n throw new AgentRequestError(\n \"storage_unavailable\",\n \"[Sixb] Agent storage is not configured.\"\n )\n }\n await tx.executions.create(durableExecution)\n // The model learns, once, how the calls it made earlier ended: the ones still waiting are\n // set aside by this message.\n const reported = createdThread\n ? { parts: [], superseded: [] }\n : await reportAgentApprovals(agents, {\n projectId,\n threadId: thread.id,\n messageId: triggerMessageId,\n })\n superseded = reported.superseded\n await agents.messages.append({\n id: triggerMessageId,\n projectId,\n threadId: thread.id,\n runId: null,\n role: \"user\",\n parts: [\n ...reported.parts,\n ...contextParts,\n ...trigger,\n ...(input.attachments ?? []).map((fileRef) => ({ type: \"file\" as const, fileRef })),\n ],\n authorPrincipal: principal,\n })\n return agents.runs.create({\n id: runId,\n projectId,\n executionId: durableExecution.id,\n threadId: thread.id,\n triggerMessageId,\n spec,\n })\n })\n } catch (error) {\n if (error instanceof AgentStorageError && error.code === \"active_run_exists\") {\n throw new AgentRequestError(\"active_run_exists\", error.message)\n }\n throw error\n }\n\n await announceAgentApprovals(runtime.broker, superseded)\n await publishRunActivity(runtime, run)\n const jobId = await dispatchAgentRun(runtime, agents, runId)\n\n return {\n run,\n ...(jobId ? { jobId } : {}),\n createdThread,\n }\n}\n\n/** A failed turn, or one its worker died during, can run again from the same trigger message. */\nexport function isRetryableAgentRun(\n run: Pick<ConversationAgentRunRecord, \"status\" | \"finishReason\">\n): boolean {\n return (\n run.status === \"failed\" || (run.status === \"cancelled\" && run.finishReason === \"interrupted\")\n )\n}\n\n/** Retry a failed turn as a new child execution while reusing its immutable trigger message. */\nexport async function retryAgentRun(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n models: LanguageModelCatalog | undefined,\n failedRun: ConversationAgentRunRecord\n): Promise<RequestAgentRunResult> {\n resolveExecutionScopeAuthorization(runtime.projectId, {\n execution,\n authorization: runtime.runtimeAuthorization,\n })\n assertAuthorized(runtime, { kind: \"agent.run\" })\n assertRequestAuthorityCanRunAgent(runtime)\n if (!isRetryableAgentRun(failedRun)) {\n throw new AgentRequestError(\n \"run_not_retryable\",\n `[Sixb] Only failed or interrupted Agent runs can be retried.`\n )\n }\n\n const agents = requireAgentStorage(runtime)\n const thread = await agents.threads.getById({\n projectId: runtime.projectId,\n id: failedRun.threadId,\n })\n if (!thread) {\n throw new AgentRequestError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${failedRun.threadId}' was not found.`\n )\n }\n assertSandboxExecutionAvailable(thread)\n const runId = createAgentRunId()\n const durableExecution = await prepareDurableAgentExecution(runtime, execution, runId)\n await assertAiLimitPreflight(runtime, durableExecution)\n const run = await runtime.storage.transaction(async (tx) => {\n const agents = tx.agents\n if (!agents) {\n throw new AgentRequestError(\"storage_unavailable\", \"[Sixb] Agent storage is not configured.\")\n }\n await agents.messages.deleteByRunId({\n projectId: runtime.projectId,\n threadId: failedRun.threadId,\n runId: failedRun.id,\n })\n // What the failed turn published goes with what it said, so the retry starts clean. Its\n // children published into the thread too, each as its own run.\n const artifacts = tx.artifacts\n if (artifacts) {\n for (const publishedBy of [failedRun.id, ...(await childRunIds(agents, failedRun))]) {\n await artifacts.deleteVersionsByOrigin({ projectId: runtime.projectId, runId: publishedBy })\n }\n }\n await tx.executions.create(durableExecution)\n return agents.runs.create({\n id: runId,\n projectId: runtime.projectId,\n executionId: durableExecution.id,\n threadId: failedRun.threadId,\n triggerMessageId: failedRun.triggerMessageId,\n spec:\n failedRun.spec ??\n (await resolveConversationRunSpec({ models, selection: {}, settings: {} })),\n })\n })\n await publishRunActivity(runtime, run)\n const jobId = await dispatchAgentRun(runtime, agents, runId)\n return { run, ...(jobId ? { jobId } : {}), createdThread: false }\n}\n\n/** Where a resume left a paused turn. */\nexport type AgentTurnResume =\n | { readonly status: \"resumed\"; readonly run: ConversationAgentRunRecord }\n | { readonly status: Exclude<AgentTurnReadiness, \"ready\"> }\n\n/**\n * Resume a turn that paused on held calls, once its requester decided on all of them: a new turn\n * with the paused one's spec and the given mode, whose trigger message carries how each call ended,\n * and that the chat shows no text for. It checks what a retry checks, and throws what a retry\n * throws; there are no words for Sixb to pick a model from.\n *\n * It writes nothing while a call still waits or an approved one has not run (`waiting`), and once\n * the turn cannot resume (`closed`): a call was set aside, the turn was stopped or resumed already,\n * or a message moved the thread on.\n */\nexport async function resumeAgentTurn(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n models: LanguageModelCatalog | undefined,\n pausedRun: ConversationAgentRunRecord,\n input: { readonly approvalMode: AgentApprovalMode; readonly principal?: Principal }\n): Promise<AgentTurnResume> {\n const authority = resolveExecutionScopeAuthorization(runtime.projectId, {\n execution,\n authorization: runtime.runtimeAuthorization,\n })\n if (!isAwaitingApprovalRun(pausedRun)) return { status: \"closed\" }\n\n const agents = requireAgentStorage(runtime)\n const projectId = runtime.projectId\n const scope = { projectId, runId: pausedRun.id }\n // Read first, so a decision that leaves calls waiting never meets a check below.\n const readiness = turnResumeReadiness(await listTurnApprovals(agents, scope))\n if (readiness !== \"ready\") return { status: readiness }\n\n assertAuthorized(runtime, { kind: \"agent.run\" })\n assertRequestAuthorityCanRunAgent(runtime)\n const thread = await agents.threads.getById({ projectId, id: pausedRun.threadId })\n if (!thread) {\n throw new AgentRequestError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${pausedRun.threadId}' was not found.`\n )\n }\n assertSandboxExecutionAvailable(thread)\n\n const runId = createAgentRunId()\n const durableExecution = await prepareResumedExecution(runtime, execution, runId)\n await assertAiLimitPreflight(runtime, durableExecution)\n const spec = await resumedConversationRunSpec(models, pausedRun.spec, input.approvalMode)\n const principal =\n authority.type === \"principal\"\n ? authority.context.principal\n : (input.principal ?? SYSTEM_PRINCIPAL)\n const triggerMessageId = createAgentMessageId()\n\n let run: ConversationAgentRunRecord\n try {\n run = await runtime.storage.transaction(async (tx) => {\n const agents = tx.agents\n if (!agents) {\n throw new AgentRequestError(\n \"storage_unavailable\",\n \"[Sixb] Agent storage is not configured.\"\n )\n }\n // Checked again where it is written: a message sent meanwhile moved the thread on.\n const latest = await latestConversationRun(agents, projectId, pausedRun.threadId)\n if (latest?.id !== pausedRun.id) throw new TurnClosed()\n const approvals = await listTurnApprovals(agents, scope)\n if (turnResumeReadiness(approvals) !== \"ready\") throw new TurnClosed()\n\n // The report's compare-and-swap lets one of two racing final decisions resume the turn, and\n // a stop that lands first keeps it from resuming.\n const parts = await reportSettledAgentApprovals(agents, {\n projectId,\n threadId: pausedRun.threadId,\n messageId: triggerMessageId,\n resuming: true,\n })\n const reported = new Set(parts.map((part) => part.approvalId))\n const unreported = approvals.filter((approval) => approval.reportedInMessageId === undefined)\n if (!unreported.every((approval) => reported.has(approval.id))) throw new TurnClosed()\n\n await tx.executions.create(durableExecution)\n await agents.messages.append({\n id: triggerMessageId,\n projectId,\n threadId: pausedRun.threadId,\n runId: null,\n role: \"user\",\n parts,\n authorPrincipal: principal,\n })\n return agents.runs.create({\n id: runId,\n projectId,\n executionId: durableExecution.id,\n threadId: pausedRun.threadId,\n triggerMessageId,\n spec,\n })\n })\n } catch (error) {\n if (error instanceof TurnClosed) return { status: \"closed\" }\n // Another turn took the thread first; its message reports what this one would have.\n if (error instanceof AgentStorageError && error.code === \"active_run_exists\") {\n return { status: \"closed\" }\n }\n throw error\n }\n\n await publishRunActivity(runtime, run)\n await dispatchAgentRun(runtime, agents, runId)\n return { status: \"resumed\", run }\n}\n\n/** Rolls the resume's transaction back: the turn cannot resume. */\nclass TurnClosed extends Error {\n constructor() {\n super(\"[Sixb] The paused Agent turn can no longer resume.\")\n }\n}\n\n/**\n * A resumed turn's execution. From a request, it is that request's child, like a retry. From the\n * paused turn's own execution, as the worker resumes it, it is a sibling of the paused turn: a\n * child of the request that started it, so that resumes never nest.\n */\nasync function prepareResumedExecution(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n runId: string\n): Promise<Omit<ExecutionRecord, \"createdAt\">> {\n if (execution.executor.type !== \"agent\" || execution.source.type !== \"execution\") {\n return prepareDurableAgentExecution(runtime, execution, runId)\n }\n\n const parent = await runtime.storage.executions.getById({\n projectId: runtime.projectId,\n id: execution.source.executionId,\n })\n if (!parent) {\n throw new AgentRequestError(\n \"authority_not_inheritable\",\n `[Sixb] Agent execution '${execution.id}' has no parent to resume under.`\n )\n }\n return createInheritedAgentExecutionRecord({ id: `exec_${randomUUID()}`, parent, runId })\n}\n\n/** The paused turn's spec, with defaults for a model that has since left the catalog. */\nasync function resumedConversationRunSpec(\n models: LanguageModelCatalog | undefined,\n paused: ConversationAgentRunSpec | undefined,\n approvalMode: AgentApprovalMode\n): Promise<ConversationAgentRunSpec> {\n const kept =\n paused && models?.getByRef(paused.model)\n ? paused\n : await resolveConversationRunSpec({\n models,\n selection: {},\n settings: {\n ...(paused?.timeZone === undefined ? {} : { timeZone: paused.timeZone }),\n ...(paused?.locale === undefined ? {} : { locale: paused.locale }),\n },\n })\n return Object.freeze({ ...kept, approvalMode })\n}\n\n/** Every child a turn spawned, whatever its status. */\nasync function childRunIds(\n agents: AgentStorage,\n parent: ConversationAgentRunRecord\n): Promise<string[]> {\n const ids: string[] = []\n for (;;) {\n const page = await agents.runs.list({\n projectId: parent.projectId,\n kinds: [\"subagent\"],\n parentRunId: parent.id,\n order: \"asc\",\n limit: 100,\n offset: ids.length,\n })\n ids.push(...page.runs.map((run) => run.id))\n if (!page.hasMore || page.runs.length === 0) return ids\n }\n}\n\n/**\n * A continuation picks up where the cut-short turn stopped, with its model and reasoning unless the\n * request chooses others. A model that has since left the catalog falls back to the defaults.\n */\nasync function continuedSelection(\n runtime: SixbRuntimeContext,\n models: LanguageModelCatalog | undefined,\n input: RequestAgentRunInput\n): Promise<Pick<RequestAgentRunInput, \"model\" | \"reasoning\">> {\n const agents = requireAgentStorage(runtime)\n const threadId = input.threadId ?? \"\"\n if (!(await agents.threads.getById({ projectId: runtime.projectId, id: threadId }))) {\n throw new AgentRequestError(\n \"thread_not_found\",\n \"[Sixb] An Agent continuation needs an existing thread.\"\n )\n }\n if (input.model !== undefined || input.reasoning !== undefined) return {}\n const spec = (await latestConversationRun(agents, runtime.projectId, threadId))?.spec\n if (!spec || !models?.getByRef(spec.model)) return {}\n return {\n model: spec.model,\n ...(spec.reasoning === undefined ? {} : { reasoning: spec.reasoning }),\n }\n}\n\n/** A turn Sixb picks the model of, with the words it judges. */\ninterface RoutedTurn {\n readonly router: TurnModelRouter\n readonly text: string\n}\n\n/**\n * Naming a model or a reasoning opts a turn out of routing: it runs that model, or the default, as\n * chosen. A continuation has no text to judge, and keeps the cut-short turn's model.\n */\nfunction routedTurn(\n router: TurnModelRouter | undefined,\n selection: Pick<RequestAgentRunInput, \"model\" | \"reasoning\">,\n text: string | undefined\n): RoutedTurn | undefined {\n if (!router || text === undefined) return undefined\n if (selection.model !== undefined || selection.reasoning !== undefined) return undefined\n\n return { router, text }\n}\n\n/** The spec of a turn Sixb picks the model for, compared to the thread's previous turn. */\nasync function routedConversationRunSpec(\n agents: AgentStorage,\n input: RoutedTurn & {\n readonly projectId: string\n readonly threadId: string | undefined\n readonly settings: RequesterSettings\n readonly language: LanguageModelCatalog | undefined\n }\n): Promise<ConversationAgentRunSpec> {\n const previous = input.threadId\n ? await latestConversationRun(agents, input.projectId, input.threadId)\n : undefined\n const choice = await input.router.choose(input.text, previous)\n\n return resolveConversationRunSpec({\n models: input.language,\n selection: { model: choice.model },\n settings: input.settings,\n tierProbabilities: choice.tierProbabilities,\n })\n}\n\nasync function latestConversationRun(\n agents: AgentStorage,\n projectId: string,\n threadId: string\n): Promise<ConversationAgentRunRecord | undefined> {\n const { runs } = await agents.runs.list({\n projectId,\n threadId,\n kinds: [\"conversation\"],\n order: \"desc\",\n limit: 1,\n })\n return runs[0]?.kind === \"conversation\" ? runs[0] : undefined\n}\n\n/** The words of the user, or the continuation Sixb words for them. */\nfunction triggerParts(input: RequestAgentRunInput): readonly AgentMessagePart[] {\n if (input.continue === true) {\n if (input.text !== undefined || input.attachments?.length || input.context?.length) {\n throw new AgentRequestError(\n \"invalid_message\",\n \"[Sixb] An Agent continuation carries no text, attachments, or context.\"\n )\n }\n return [{ type: \"continuation\" }]\n }\n if (typeof input.text !== \"string\" || input.text.trim().length === 0) {\n throw new AgentRequestError(\n \"invalid_message\",\n \"[Sixb] An Agent message needs text, or `continue: true` to continue the previous answer.\"\n )\n }\n return [{ type: \"text\", text: input.text }]\n}\n\nfunction assertAttachments(attachments: readonly FileRef[] | undefined): void {\n for (const [index, attachment] of (attachments ?? []).entries()) {\n if (!isValidFileRef(attachment)) {\n throw new AgentRequestError(\n \"invalid_attachment\",\n `[Sixb] Attachment ${index} is not a valid file reference.`\n )\n }\n }\n}\n\nfunction assertThreadAcceptsRun(thread: AgentThreadRecord): void {\n assertConversationThread(thread)\n assertSandboxExecutionAvailable(thread)\n // Fast single-flight check for a clear error. `runs.create` is the atomic authority.\n if (thread.activeRunId !== null) {\n throw new AgentRequestError(\n \"active_run_exists\",\n `[Sixb] Agent thread '${thread.id}' already has an active run '${thread.activeRunId}'.`\n )\n }\n}\n\nfunction assertSandboxExecutionAvailable(thread: AgentThreadRecord): void {\n if (thread.sandboxState && ![\"new\", \"ready\"].includes(thread.sandboxState.status)) {\n throw new AgentRequestError(\n \"sandbox_execution_unavailable\",\n \"[Sixb] Sandbox recovery is required before another run. Reload the thread and explicitly recreate it to start fresh.\"\n )\n }\n}\n\nasync function assertAiLimitPreflight(\n runtime: SixbRuntimeContext,\n execution: Pick<ExecutionRecord, \"requestedBy\" | \"requesterGroupIds\">\n): Promise<void> {\n const limits = runtime.storage.aiLimits\n if (!limits) throw aiUsageLimitUnavailableError([\"limitStorageUnavailable\"])\n\n const subjects = aiLimitSubjectsFromAttribution(\n execution.requestedBy,\n execution.requesterGroupIds\n )\n let applicable: readonly AiLimitPolicyStatus[]\n try {\n applicable = applicableAiLimitPolicyStatuses(\n await limits.listPolicyStatuses({ projectId: runtime.projectId }),\n subjects\n )\n } catch {\n throw aiUsageLimitUnavailableError([\"limitStorageUnavailable\"])\n }\n\n const unavailable = applicable.filter((status) => status.accountingStatus === \"unavailable\")\n if (unavailable.length > 0) {\n throw aiUsageLimitUnavailableError([\"incompleteAccounting\"])\n }\n const exhausted = applicable.filter((status) => status.exhausted)\n if (exhausted.length > 0) {\n const resetAt = new Date(\n Math.min(...exhausted.map((status) => status.period.resetAt.getTime()))\n )\n throw aiUsageLimitExceededError(resetAt)\n }\n}\n\n/**\n * Freeze the model selection of a turn. The model's default reasoning is resolved here, not by the\n * worker, so a retry runs with the reasoning the turn was admitted with.\n */\nasync function resolveConversationRunSpec(input: {\n readonly models?: LanguageModelCatalog\n readonly selection: Pick<RequestAgentRunInput, \"model\" | \"reasoning\">\n readonly settings: RequesterSettings\n /** The decision model's answer, when Sixb picked the model. */\n readonly tierProbabilities?: LanguageModelTierProbabilities\n}): Promise<ConversationAgentRunSpec> {\n if (!input.models) {\n throw new AgentRequestError(\n \"model_not_found\",\n \"[Sixb] Configure models.language before starting the Agent.\"\n )\n }\n const selected = input.selection.model ?? input.models.default\n const model = input.models.getByRef(selected)\n if (model === null) {\n throw new AgentRequestError(\n \"model_not_found\",\n `[Sixb] Language model '${selected.provider}/${selected.modelId}' is not in the project model catalog.`\n )\n }\n\n const explicitReasoning = input.selection.reasoning\n if (explicitReasoning !== undefined) {\n await assertModelSupportsReasoning(model, explicitReasoning)\n }\n const reasoning = explicitReasoning ?? model.model.defaultReasoning\n const { timeZone, locale } = input.settings\n\n return Object.freeze({\n model: Object.freeze({ provider: selected.provider, modelId: selected.modelId }),\n ...(model.tier === undefined ? {} : { tier: model.tier }),\n ...(input.tierProbabilities === undefined\n ? {}\n : { tierProbabilities: Object.freeze({ ...input.tierProbabilities }) }),\n ...(reasoning === undefined ? {} : { reasoning }),\n ...(timeZone === undefined ? {} : { timeZone }),\n ...(locale === undefined ? {} : { locale }),\n })\n}\n\n/** Canonical settings of the person asking, as the run spec stores them. */\ntype RequesterSettings = Pick<ConversationAgentRunSpec, \"timeZone\" | \"locale\">\n\nfunction requesterSettings(\n input: Pick<RequestAgentRunInput, \"timeZone\" | \"locale\">\n): RequesterSettings {\n const timeZone = requestedSetting(\n \"timeZone\",\n input.timeZone,\n canonicalTimeZone,\n \"an IANA time zone\"\n )\n const locale = requestedSetting(\"locale\", input.locale, canonicalLocale, \"a BCP 47 language tag\")\n\n return {\n ...(timeZone === undefined ? {} : { timeZone }),\n ...(locale === undefined ? {} : { locale }),\n }\n}\n\nfunction requestedSetting(\n field: \"timeZone\" | \"locale\",\n value: string | undefined,\n canonical: (value: unknown) => string | undefined,\n expected: string\n): string | undefined {\n if (value === undefined) return undefined\n const resolved = canonical(value)\n if (resolved === undefined) {\n throw new AgentRequestError(\n \"invalid_locale\",\n `[Sixb] Agent request '${field}' must be ${expected}; received ${JSON.stringify(value)}.`\n )\n }\n return resolved\n}\n\n// Checked against the model's resolved capabilities, as `GET /api/models` reports them (its\n// configured ones when the provider catalog is unavailable). Undeclared capabilities accept any\n// level; the provider then falls back to its own default.\nasync function assertModelSupportsReasoning(\n entry: LanguageModelEntry,\n reasoning: unknown\n): Promise<void> {\n if (!isModelReasoning(reasoning)) {\n throw new AgentRequestError(\n \"invalid_model_selection\",\n `[Sixb] Agent reasoning must be one of: ${AGENT_REASONING_LEVELS.join(\", \")}, or a nonnegative budgetTokens object.`\n )\n }\n if (reasoning === \"provider-default\") return\n const model = await resolveLanguageModel(entry.model)\n const issue = modelReasoningSupportIssue(model.definition.capabilities.reasoning, reasoning)\n if (issue !== undefined) {\n throw new AgentRequestError(\n \"invalid_model_selection\",\n `[Sixb] Language model '${entry.provider}/${entry.modelId}' cannot use this reasoning: ${issue}.`\n )\n }\n}\n\nasync function prepareDurableAgentExecution(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n runId: string\n): Promise<Omit<ExecutionRecord, \"createdAt\">> {\n const parent = await ensureExecutionRecord(\n runtime.storage.executions,\n executionRecordInputFromRuntime({\n execution,\n runtimeAuthorization: runtime.runtimeAuthorization,\n })\n )\n return createInheritedAgentExecutionRecord({\n id: `exec_${randomUUID()}`,\n parent,\n runId,\n })\n}\n\nfunction assertRequestAuthorityCanRunAgent(runtime: SixbRuntimeContext): void {\n if (!canInheritAgentRequestAuthorization(runtime.runtimeAuthorization)) {\n throw new AgentRequestError(\n \"authority_not_inheritable\",\n \"[Sixb] The Agent requires an authenticated user request or disabled authorization.\"\n )\n }\n}\n\nasync function dispatchAgentRun(\n runtime: SixbRuntimeContext,\n agents: AgentStorage,\n runId: string\n): Promise<string | undefined> {\n // The queued run is the durable dispatch intent. Publication is best-effort; workers reconcile\n // it with the same deterministic queue job id if the queue is temporarily unavailable.\n try {\n const dispatch = await dispatchQueuedAgentRuns({\n projectId: runtime.projectId,\n storage: agents,\n queue: runtime.queues.agents,\n runIds: [runId],\n })\n const failure = dispatch.failures[0]\n if (failure) {\n console.error(\n `[Sixb] Could not dispatch queued agent run '${runId}'; retrying later.`,\n failure.error\n )\n }\n return dispatch.dispatched[0]?.jobId\n } catch (error) {\n console.error(`[Sixb] Could not dispatch queued agent run '${runId}'; retrying later.`, error)\n return undefined\n }\n}\n\n/** Activity delivery is observational: durable run admission remains successful if the feed is down. */\nasync function publishRunActivity(\n runtime: SixbRuntimeContext,\n run: ConversationAgentRunRecord\n): Promise<void> {\n try {\n await publishAgentRunActivity(runtime.broker, run)\n } catch (error) {\n console.error(`[Sixb] Agent run '${run.id}' activity stream publish failed:`, error)\n }\n}\n\nfunction createThread(\n agents: AgentStorage,\n params: {\n readonly projectId: string\n readonly threadId?: string\n readonly title?: string\n readonly principal: Principal\n }\n): Promise<AgentThreadRecord> {\n return agents.threads.create({\n id: params.threadId ?? createAgentThreadId(),\n projectId: params.projectId,\n ownerPrincipal: params.principal,\n ...(params.title === undefined ? {} : { title: params.title }),\n })\n}\n\nfunction requireAgentStorage(runtime: SixbRuntimeContext): AgentStorage {\n const agents = runtime.storage.agents\n if (!agents) {\n throw new AgentRequestError(\"storage_unavailable\", \"[Sixb] Agent storage is not configured.\")\n }\n return agents\n}\n",
48
+ "/** Language assumed when a project sets none. */\nexport const DEFAULT_PROJECT_LOCALE = \"en\"\n\n/** Time zone assumed when a project sets none; cron schedules have always used it. */\nexport const DEFAULT_PROJECT_TIME_ZONE = \"UTC\"\n\n/** The canonical form of a BCP 47 language tag (`fr-fr` → `fr-FR`), or `undefined` if invalid. */\nexport function canonicalLocale(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined\n try {\n const [locale] = Intl.getCanonicalLocales(value)\n return locale\n } catch {\n return undefined\n }\n}\n\n/** The canonical IANA name of a time zone (`europe/paris` → `Europe/Paris`), or `undefined`. */\nexport function canonicalTimeZone(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.trim() !== value || value === \"\") return undefined\n try {\n return new Intl.DateTimeFormat(\"en-US\", { timeZone: value }).resolvedOptions().timeZone\n } catch {\n return undefined\n }\n}\n",
49
+ "import type { SixbRuntimeContext } from \"../runtime/types\"\nimport {\n type AgentContextEntryInput,\n type AgentContextPart,\n normalizeAgentContextEntries,\n} from \"./context/entries\"\nimport { AgentRequestError } from \"./errors\"\n\n/** Resolve the exact context parts that will be persisted with the triggering user message. */\nexport async function resolveAgentContextParts(\n runtime: SixbRuntimeContext,\n input: readonly AgentContextEntryInput[] | undefined\n): Promise<readonly AgentContextPart[]> {\n const entries = normalizeAgentContextEntries(input)\n\n for (const entry of entries) {\n if (entry.context.kind !== \"object\") continue\n const { objectTypeId, primaryId } = entry.context.ref\n\n try {\n runtime.ontology.resolveObjectType(objectTypeId)\n } catch {\n invalidContext(`context references an unknown object type '${objectTypeId}'`)\n }\n\n const object = await runtime.objectReader.getByPrimaryId({\n objectTypeId,\n primaryId,\n })\n if (!object) {\n invalidContext(`context references an unknown object '${objectTypeId}:${primaryId}'`)\n }\n }\n\n return entries.map((entry) => ({ type: \"context\", ...entry }))\n}\n\nfunction invalidContext(message: string): never {\n throw new AgentRequestError(\"invalid_context\", `[Sixb] Invalid agent context: ${message}.`)\n}\n",
50
+ "import type { AgentQueueJob, Queue, SubagentQueueJob } from \"../queues\"\nimport type { AgentStorage } from \"../storage/agents\"\n\nexport interface DispatchQueuedAgentRunsInput {\n readonly projectId: string\n readonly storage: AgentStorage\n readonly queue: Queue<AgentQueueJob>\n /** Dispatch only these runs. Omitted scans the oldest queued runs. */\n readonly runIds?: readonly string[]\n readonly limit?: number\n}\n\nexport interface DispatchedAgentRun {\n readonly runId: string\n readonly jobId: string\n}\n\nexport interface AgentRunDispatchFailure {\n readonly runId: string\n readonly error: unknown\n}\n\nexport interface DispatchQueuedAgentRunsResult {\n readonly scanned: number\n readonly dispatched: readonly DispatchedAgentRun[]\n readonly failures: readonly AgentRunDispatchFailure[]\n}\n\n/** Stable queue identity: repeated publication of one durable run is idempotent. */\nexport function agentRunQueueJobId(runId: string): string {\n return `agt_job_${runId}`\n}\n\nexport function subagentRunQueueJobId(runId: string): string {\n return `agt_child_job_${runId}`\n}\n\n/** Stable queue identity shared by workflow dispatch and agent reconciliation. */\nexport function workflowAgentNodeQueueJobId(nodeRunId: string): string {\n return `wfa_job_${nodeRunId}`\n}\n\n/**\n * Publish durable queued runs to the agent queue.\n *\n * The queued run is the dispatch intent, so no parallel outbox record is needed. Callers may run\n * this concurrently: the deterministic queue job id collapses repeated publication to one active\n * job, while the worker's queued→running transition remains the execution authority.\n */\nexport async function dispatchQueuedAgentRuns(\n input: DispatchQueuedAgentRunsInput\n): Promise<DispatchQueuedAgentRunsResult> {\n const limit = normalizeLimit(input.limit)\n const runs = input.runIds\n ? await input.storage.runs.getByIds({\n projectId: input.projectId,\n ids: [...new Set(input.runIds)].slice(0, limit),\n })\n : (\n await input.storage.runs.list({\n projectId: input.projectId,\n kinds: [\"conversation\"],\n statuses: [\"queued\"],\n order: \"asc\",\n limit,\n })\n ).runs\n\n const queued = runs.filter((run) => run.kind === \"conversation\" && run.status === \"queued\")\n if (queued.length === 0) {\n return { scanned: 0, dispatched: [], failures: [] }\n }\n\n try {\n const jobs = await input.queue.enqueue({\n projectId: input.projectId,\n jobs: queued.map((run) => ({\n id: agentRunQueueJobId(run.id),\n type: \"agent.run.requested\" as const,\n payload: { runId: run.id },\n })),\n })\n const jobsById = new Map(jobs.map((job) => [job.id, job]))\n const dispatched = queued.map((run) => {\n const jobId = agentRunQueueJobId(run.id)\n if (!jobsById.has(jobId)) {\n throw new Error(`[Sixb] Agent queue did not return job '${jobId}'.`)\n }\n return { runId: run.id, jobId }\n })\n return { scanned: queued.length, dispatched, failures: [] }\n } catch (error) {\n return {\n scanned: queued.length,\n dispatched: [],\n failures: queued.map((run) => ({ runId: run.id, error })),\n }\n }\n}\n\nexport async function dispatchQueuedSubagentRuns(input: {\n readonly projectId: string\n readonly storage: AgentStorage\n readonly queue: Queue<SubagentQueueJob>\n readonly runIds?: readonly string[]\n readonly limit?: number\n}): Promise<DispatchQueuedAgentRunsResult> {\n const limit = normalizeLimit(input.limit)\n const runs = input.runIds\n ? await input.storage.runs.getByIds({\n projectId: input.projectId,\n ids: [...new Set(input.runIds)].slice(0, limit),\n })\n : (\n await input.storage.runs.list({\n projectId: input.projectId,\n kinds: [\"subagent\"],\n statuses: [\"queued\"],\n order: \"asc\",\n limit,\n })\n ).runs\n const queued = runs.filter((run) => run.kind === \"subagent\" && run.status === \"queued\")\n if (queued.length === 0) return { scanned: 0, dispatched: [], failures: [] }\n\n try {\n const jobs = await input.queue.enqueue({\n projectId: input.projectId,\n jobs: queued.map((run) => ({\n id: subagentRunQueueJobId(run.id),\n type: \"agent.subagent-run.requested\" as const,\n payload: { runId: run.id },\n })),\n })\n const jobsById = new Set(jobs.map((job) => job.id))\n const dispatched = queued.map((run) => {\n const jobId = subagentRunQueueJobId(run.id)\n if (!jobsById.has(jobId)) {\n throw new Error(`[Sixb] Subagent queue did not return job '${jobId}'.`)\n }\n return { runId: run.id, jobId }\n })\n return { scanned: queued.length, dispatched, failures: [] }\n } catch (error) {\n return {\n scanned: queued.length,\n dispatched: [],\n failures: queued.map((run) => ({ runId: run.id, error })),\n }\n }\n}\n\nfunction normalizeLimit(value: number | undefined): number {\n if (value === undefined) return 100\n if (!Number.isFinite(value) || value < 1) {\n throw new Error(\"[Sixb] Agent dispatch limit must be at least 1.\")\n }\n return Math.floor(value)\n}\n",
51
+ "import { RuntimeError } from \"../runtime/errors\"\nimport { AgentRequestError } from \"./errors\"\n\n/** Reject JavaScript callers too: old configuration must not silently change authority. */\nexport function assertNoAgentDefinitions(input: object): void {\n if (\"agents\" in input) {\n throw new RuntimeError(\n \"[Sixb] Agent definitions are no longer supported. Configure 'models' and 'tools' on createSixb() instead.\"\n )\n }\n}\n\nexport function assertNoAgentSelector(input: object): void {\n if (\"agentId\" in input || \"agentIds\" in input) {\n throw new AgentRequestError(\n \"agent_selector_removed\",\n \"[Sixb] There is one project Agent. Remove the agentId selector and use sixb.agent.\"\n )\n }\n}\n",
52
+ "import { principalsEqual, type UserPrincipal } from \"../auth\"\nimport { AuthorizationError, assertAuthorized, isRuntimeAllowed } from \"../authorization\"\nimport { isSixbError } from \"../errors/internal\"\nimport type { AuthorizablePrincipal, ExecutionContext } from \"../execution\"\nimport { canInheritAgentRequestAuthorization } from \"../execution/agent\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport type { DecisionModelsRuntime, ModelCatalog } from \"../models\"\nimport type { SixbDependencies } from \"../runtime/sixb\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type { SecurityDefinitionCatalog } from \"../security\"\nimport type {\n AgentApprovalMode,\n AgentApprovalRecord,\n AgentRunRecord,\n AgentStorage,\n AgentThreadRecord,\n ConversationAgentRunRecord,\n ListAgentApprovalsInput,\n ListAgentApprovalsResult,\n ListAgentRunsInput,\n ListAgentRunsResult,\n ListAgentThreadsInput,\n ListAgentThreadsResult,\n SubagentRunRecord,\n} from \"../storage/agents\"\nimport type { AiCostSummary } from \"../storage/ai-cost\"\nimport type { AiModelCallUsage } from \"../storage/ai-usage\"\nimport { resolveTurnAccounting } from \"./accounting\"\nimport { type AgentApprovalResume, registerAgentTurnResume } from \"./approval-continuation\"\nimport { getAgentApprovalExecutor } from \"./approval-executor\"\nimport {\n agentRunApprovalMode,\n approvalModeAllows,\n assertAgentApprovalMode,\n decideAgentApproval,\n defaultAgentApprovalMode,\n isAwaitingApprovalRun,\n leastApprovalModeAllowing,\n listTurnApprovals,\n type ResolvedAgentApprovalMode,\n resolveAgentApprovalMode,\n resumedApprovalMode,\n stopAgentTurn,\n} from \"./approvals\"\nimport { cancelAgentRun } from \"./cancel\"\nimport {\n type AgentChildView,\n cancelAgentChildRun,\n listAgentChildren,\n readAgentChild,\n} from \"./children\"\nimport { AgentRequestError } from \"./errors\"\nimport { forkAgentThread } from \"./fork\"\nimport { createAgentThreadId, createAgentThreadSandboxName } from \"./ids\"\nimport { type AgentMemoryRuntime, createAgentMemoryRuntime } from \"./memory-execution\"\nimport { createTurnModelRouter } from \"./model-routing\"\nimport {\n type AgentThreadParticipantInput,\n addAgentThreadParticipants,\n removeAgentThreadParticipant,\n} from \"./participants\"\nimport {\n type RequestAgentRunInput,\n type RequestAgentRunResult,\n requestAgentRun,\n resumeAgentTurn,\n retryAgentRun,\n} from \"./request\"\nimport { assertNoAgentSelector } from \"./retired-config\"\nimport { normalizeSandboxBinding } from \"./sandbox\"\nimport { listSubagentThreadRuns } from \"./subagent-runs\"\nimport {\n type AgentThreadView,\n agentThreadViews,\n assertConversationThread,\n createAgentThreadAccessRule,\n} from \"./thread-access\"\nimport type { AgentDescriptor } from \"./types\"\n\nexport type ExecutionAgentRequestInput = Omit<RequestAgentRunInput, \"principal\">\n\nexport type ListExecutionAgentThreadsInput = Omit<\n ListAgentThreadsInput,\n \"projectId\" | \"ownerPrincipal\" | \"participantPrincipal\"\n> & {\n /** The threads other users added the caller to, instead of the caller's own. */\n readonly sharedWithMe?: boolean\n}\n\nexport interface ListAgentThreadViewsResult extends Omit<ListAgentThreadsResult, \"threads\"> {\n readonly threads: readonly AgentThreadView[]\n}\n\nexport type CreateExecutionAgentThreadInput<\n TParams extends Record<string, unknown> = Record<string, unknown>,\n> = {\n readonly id?: string\n readonly title?: string\n readonly sandbox?: TParams\n}\n\nexport type AgentThreadsRuntime<TParams extends Record<string, unknown> = Record<string, unknown>> =\n {\n /** Start fresh after uncertain recovery; never deletes the previous sandbox. Owner only. */\n recreateSandbox(\n threadId: string,\n input: { readonly expectedSandboxName: string }\n ): Promise<AgentThreadView>\n create(input: CreateExecutionAgentThreadInput<TParams>): Promise<AgentThreadView>\n /**\n * Copy a thread of the caller's, or one shared with them, into a new one the caller owns alone,\n * with a new sandbox. A turn still running is not copied.\n */\n fork(threadId: string): Promise<AgentThreadView>\n /** A thread the caller owns or takes part in. */\n getById(threadId: string): Promise<AgentThreadView | null>\n /** The caller's own threads, or with `sharedWithMe` the ones other users added it to. */\n list(input?: ListExecutionAgentThreadsInput): Promise<ListAgentThreadViewsResult>\n /**\n * The sub-agents a conversation's turns spawned, oldest first, each the thread it works in with\n * every run it took; `null` when the caller cannot read the conversation. `runId` keeps those\n * one turn spawned. A sub-agent is visible exactly when its conversation is.\n */\n listChildren(\n threadId: string,\n input?: ListAgentChildrenInput\n ): Promise<AgentChildListResult | null>\n /** The sub-agent that works in a thread, read as `listChildren` lists it. */\n getChild(threadId: string): Promise<AgentChildView | null>\n /** Who else reads the conversation and talks in it. */\n readonly participants: AgentThreadParticipantsRuntime\n /**\n * The caller's mode in a thread they read, and where it comes from: their choice there, else\n * their default, else the fallback.\n */\n getApprovalMode(threadId: string): Promise<ResolvedAgentApprovalMode | null>\n /**\n * Choose the caller's own mode for their next turns in a thread; `null` follows their default\n * again. Others keep theirs.\n */\n setApprovalMode(\n threadId: string,\n mode: AgentApprovalMode | null\n ): Promise<ResolvedAgentApprovalMode>\n }\n\n/**\n * The calls the Agent held for approval. Whoever reads a thread reads its approvals; only whoever\n * asked for the turn decides, since the call runs with their rights.\n */\nexport interface AgentApprovalsRuntime {\n /**\n * A thread's approvals, oldest first; without `threadId`, the caller's own in the threads they\n * can open.\n */\n list(input?: ListExecutionAgentApprovalsInput): Promise<ListAgentApprovalsResult>\n getById(approvalId: string): Promise<AgentApprovalRecord | null>\n /**\n * Approve or deny a pending call. An approved call runs now, and the approval comes back with its\n * outcome. Once every call the turn held is decided, the turn resumes: `run` is the turn that\n * continues it, and the model reads how each call ended. `always` also sets the caller's mode in\n * the thread to the least that runs such a call without asking, and approves the turn's other\n * calls that mode runs.\n */\n decide(\n approvalId: string,\n input: DecideExecutionAgentApprovalInput\n ): Promise<AgentApprovalDecision>\n}\n\nexport interface AgentApprovalDecision {\n readonly approval: AgentApprovalRecord\n /** The turn that resumed the paused one, when this decision was its last. */\n readonly run?: ConversationAgentRunView\n /**\n * Present when the paused turn could not resume: the decision and the call's outcome stand.\n * `retrying`: Sixb resumes it once it can, for example when an AI limit resets; otherwise the\n * thread's next message tells the model how its calls ended.\n */\n readonly resume?: {\n readonly status: \"refused\"\n readonly code: string\n readonly message: string\n readonly retrying: boolean\n }\n}\n\nexport type ListExecutionAgentApprovalsInput = Omit<\n ListAgentApprovalsInput,\n \"projectId\" | \"requestedBy\" | \"reported\"\n>\n\nexport interface DecideExecutionAgentApprovalInput {\n readonly decision: \"approve\" | \"deny\"\n readonly always?: boolean\n}\n\n/** The caller's own Agent settings. */\nexport interface AgentPreferences {\n /** The mode of the caller's turns in threads where they chose none. */\n readonly approvalMode: AgentApprovalMode\n /** `fallback` until the caller chooses a default. */\n readonly approvalModeSource: \"default\" | \"fallback\"\n}\n\nexport interface AgentPreferencesRuntime {\n get(): Promise<AgentPreferences>\n update(input: { readonly approvalMode?: AgentApprovalMode }): Promise<AgentPreferences>\n}\n\n/**\n * Participants read the whole conversation, its files and its live stream, and send messages that\n * run with their own rights. Nothing checks what they may see: the conversation holds what the\n * Agent read with the rights of whoever asked.\n */\nexport interface AgentThreadParticipantsRuntime {\n /**\n * Add active users of the project, by id or by email; only the thread's owner can. Someone\n * already taking part keeps when and by whom they were added. Returns the thread with every\n * participant.\n */\n add(threadId: string, users: readonly AgentThreadParticipantInput[]): Promise<AgentThreadView>\n /**\n * The owner removes anyone; a participant removes only themself, to leave. Removing someone who\n * does not take part changes nothing.\n */\n remove(threadId: string, user: UserPrincipal): Promise<void>\n}\n\n/**\n * Any user's conversation, read-only, for a caller with `can.observe(agent.threads)`. Nothing here\n * checks who owns or takes part in a thread, and nothing writes: those stay on `threads` and `runs`.\n */\nexport interface ObservedAgentThreadsRuntime {\n /** Throws an `AuthorizationError` without `can.observe(agent.threads)`. */\n getById(threadId: string): Promise<AgentThreadView | null>\n /** The thread's conversation runs; `null` when the thread does not exist. */\n listRuns(\n threadId: string,\n input?: Omit<ListAgentRunsInput, \"projectId\" | \"threadId\">\n ): Promise<AgentRunListResult | null>\n /** The sub-agents the thread's turns spawned; `null` when the thread is not a conversation. */\n listChildren(\n threadId: string,\n input?: ListAgentChildrenInput\n ): Promise<AgentChildListResult | null>\n /** The sub-agent that works in a thread; `null` when it is not a sub-agent's. */\n getChild(threadId: string): Promise<AgentChildView | null>\n}\n\nexport interface AgentRunsRuntime {\n request(input: ExecutionAgentRequestInput): Promise<ExecutionAgentRunResult>\n /**\n * Retry a failed or interrupted turn; only whoever asked for it can, as it runs with their rights.\n * A sub-agent's run is never retried: its turn decides whether to spawn it again.\n */\n retry(runId: string): Promise<ExecutionAgentRunResult>\n /**\n * Stop a turn; whoever asked for it, or the thread's owner, can. A queued turn is cancelled when\n * this returns; a running one is still running, with the stop signal sent to its worker. A turn\n * paused for approval stays as it ended, with its held calls cancelled: it never resumes. A\n * sub-agent's run stops as its turn would: whoever asked for that turn, or the conversation's\n * owner, can, and its parent's `wait_agent` reads that it was stopped.\n */\n cancel(runId: string): Promise<AgentRunView>\n /** A turn, or a sub-agent's run, read through its thread. */\n getById(runId: string): Promise<AgentRunView | null>\n /** A conversation's turns, or the runs of a sub-agent's thread. */\n listForThread(\n threadId: string,\n input?: Omit<ListAgentRunsInput, \"projectId\" | \"threadId\">\n ): Promise<AgentRunListResult | null>\n}\n\nexport interface ListAgentChildrenInput {\n /** Only those this turn of the conversation spawned. */\n readonly runId?: string\n}\n\nexport interface AgentChildListResult {\n /** Oldest first. */\n readonly children: readonly AgentChildView[]\n}\n\n/**\n * Execution-facing run view with provenance resolved from the immutable execution ledger: a\n * conversation turn, or a sub-agent's run.\n */\nexport type AgentRunView = ConversationAgentRunView | SubagentRunView\n\n/** A conversation turn's view: what a request, a retry or a resume returns. */\nexport type ConversationAgentRunView = ConversationAgentRunRecord & AgentRunViewFields\n\n/** A sub-agent's run, read through its thread. */\nexport type SubagentRunView = SubagentRunRecord & AgentRunViewFields\n\ninterface AgentRunViewFields {\n readonly requestedBy?: AuthorizablePrincipal\n /**\n * Derived from the model-call ledger; never persisted on the Agent run row. Covers the turn and\n * everything below its execution: its children and what its tools ran, including what a workflow\n * it started spends after the turn ends, as Activity counts it.\n */\n readonly usage?: AiModelCallUsage\n /** Preferred valuation of the same calls; omitted without calls or cost storage. */\n readonly cost?: AiCostSummary\n}\n\nexport interface AgentRunListResult extends Omit<ListAgentRunsResult, \"runs\"> {\n readonly runs: readonly AgentRunView[]\n}\n\nexport interface ExecutionAgentRunResult extends Omit<RequestAgentRunResult, \"run\"> {\n readonly run: ConversationAgentRunView\n}\n\nexport type AgentRuntime<TParams extends Record<string, unknown> = Record<string, unknown>> = {\n /** Null when no language models are configured or the caller cannot run the Agent. */\n get(): AgentDescriptor | null\n readonly threads: AgentThreadsRuntime<TParams>\n readonly runs: AgentRunsRuntime\n /** Other users' conversations, read-only, with `can.observe(agent.threads)`. */\n readonly observed: ObservedAgentThreadsRuntime\n readonly memory: AgentMemoryRuntime\n readonly approvals: AgentApprovalsRuntime\n readonly preferences: AgentPreferencesRuntime\n}\n\nexport function createAgentRuntime<\n TParams extends Record<string, unknown> = Record<string, unknown>,\n>(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n models: ModelCatalog | undefined,\n decision: DecisionModelsRuntime,\n sandbox: SixbDependencies[\"sandbox\"] | undefined,\n security: SecurityDefinitionCatalog\n): AgentRuntime<TParams> {\n const authority = resolveRuntimeAuthorizationForProject(runtime)\n const turnModels = {\n language: models?.language,\n router: createTurnModelRouter(models, decision),\n }\n const rule = createAgentThreadAccessRule(runtime, authority)\n const principal = rule.caller\n const allowed = () => isRuntimeAllowed(runtime, { kind: \"agent.run\" })\n\n const getVisibleThreadRecord = async (threadId: string): Promise<AgentThreadView | null> =>\n (await rule.read(threadId))?.thread ?? null\n\n const getAgent = (): AgentDescriptor | null => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const model = models?.language?.default\n if (!model || !allowed()) return null\n return {\n name: \"Sixb\",\n model: { provider: model.provider, modelId: model.modelId },\n }\n }\n\n /** A turn, or a sub-agent's run, when the caller reads its thread. */\n const getVisibleRunRecord = async (runId: string): Promise<AgentRunRecord | null> => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const run =\n (await runtime.storage.agents?.runs.getById({\n projectId: runtime.projectId,\n id: runId,\n })) ?? null\n if (!run) return null\n const thread = await getVisibleThreadRecord(run.threadId)\n return thread ? run : null\n }\n\n const getRun = async (runId: string): Promise<AgentRunView | null> => {\n const run = await getVisibleRunRecord(runId)\n return run ? attachRunView(runtime, run) : null\n }\n\n /**\n * A turn the caller may stop or retry. Whoever asked for it may do both; the thread's owner may\n * also stop any turn, but retrying one would run it again with the owner's rights on someone\n * else's words. Code without a caller acts on every turn.\n */\n const getControllableRun = async (\n runId: string,\n action: \"cancel\" | \"retry\"\n ): Promise<ConversationAgentRunRecord> => {\n const run = await runtime.storage.agents?.runs.getById({\n projectId: runtime.projectId,\n id: runId,\n })\n const readable = run ? await rule.read(run.threadId) : null\n if (!run || !readable) {\n throw new AgentRequestError(\"run_not_found\", `[Sixb] Agent run '${runId}' was not found.`)\n }\n if (run.kind !== \"conversation\") {\n throw new AgentRequestError(\n action === \"retry\" ? \"run_not_retryable\" : \"run_not_found\",\n action === \"retry\"\n ? `[Sixb] Agent run '${runId}' is a sub-agent's: its turn spawns it again if it needs to.`\n : `[Sixb] Agent run '${runId}' was not found.`\n )\n }\n\n if (authority.type !== \"principal\") return run\n if (action === \"cancel\" && readable.access === \"owner\") return run\n\n const execution = await runtime.storage.executions.getById({\n projectId: runtime.projectId,\n id: run.executionId,\n })\n if (execution?.requestedBy && principalsEqual(execution.requestedBy, principal)) return run\n\n throw new AgentRequestError(\n \"not_run_requester\",\n action === \"cancel\"\n ? `[Sixb] Only whoever asked for Agent run '${runId}', or the thread's owner, can stop it.`\n : `[Sixb] Only whoever asked for Agent run '${runId}' can retry it: it runs again with their rights.`\n )\n }\n\n const requireAgents = (): AgentStorage => {\n const storage = runtime.storage.agents\n if (!storage) {\n throw new AgentRequestError(\"storage_unavailable\", \"[Sixb] Agent storage is not configured.\")\n }\n return storage\n }\n\n /** Settings belong to whoever calls: a shared link or a delegated execution has none. */\n const settingsPrincipal = () => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") {\n throw new AgentRequestError(\"agent_not_found\", \"[Sixb] The project Agent is unavailable.\")\n }\n return principal\n }\n\n const getVisibleApproval = async (approvalId: string): Promise<AgentApprovalRecord | null> => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const approval = await runtime.storage.agents?.approvals.getById({\n projectId: runtime.projectId,\n id: approvalId,\n })\n return approval && (await rule.read(approval.threadId)) ? approval : null\n }\n\n const getThreadApprovalMode = async (\n threadId: string\n ): Promise<ResolvedAgentApprovalMode | null> => {\n const thread = await getVisibleThreadRecord(threadId)\n if (!thread) return null\n if (thread.kind === \"subagent\") {\n // A child's mode is its run's, copied from the turn it works under, whoever reads it.\n const latest = (\n await listSubagentThreadRuns(requireAgents(), { projectId: runtime.projectId, threadId })\n ).at(-1)\n return latest\n ? { approvalMode: agentRunApprovalMode(latest), approvalModeSource: \"run\" }\n : null\n }\n return resolveAgentApprovalMode(requireAgents(), {\n projectId: runtime.projectId,\n principal: settingsPrincipal(),\n threadId,\n })\n }\n\n const setThreadApprovalMode = async (\n threadId: string,\n mode: AgentApprovalMode | null\n ): Promise<ResolvedAgentApprovalMode> => {\n if (mode !== null) assertAgentApprovalMode(mode)\n const thread = await getVisibleThreadRecord(threadId)\n if (!thread) {\n throw new AgentRequestError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${threadId}' not found.`\n )\n }\n assertConversationThread(thread)\n const agents = requireAgents()\n const scope = { projectId: runtime.projectId, principal: settingsPrincipal() }\n await agents.approvalModes.setForThread({ ...scope, threadId, mode })\n return resolveAgentApprovalMode(agents, { ...scope, threadId })\n }\n\n /** The caller's own approvals, in the threads they can still open. */\n const listOwnApprovals = async (\n storage: AgentStorage,\n { limit, offset = 0, ...input }: ListExecutionAgentApprovalsInput\n ): Promise<ListAgentApprovalsResult> => {\n const { approvals } = await storage.approvals.list({\n ...input,\n projectId: runtime.projectId,\n requestedBy: principal,\n })\n const readable = new Map<string, Promise<boolean>>()\n const canRead = (threadId: string) => {\n const known = readable.get(threadId)\n if (known) return known\n const read = rule.read(threadId).then((thread) => thread !== null)\n readable.set(threadId, read)\n return read\n }\n\n const visible: AgentApprovalRecord[] = []\n for (const approval of approvals) {\n if (await canRead(approval.threadId)) visible.push(approval)\n }\n const end = limit === undefined ? visible.length : offset + limit\n return {\n approvals: visible.slice(offset, end),\n hasMore: end < visible.length,\n total: visible.length,\n }\n }\n\n const approvals: AgentApprovalsRuntime = {\n list: async (input = {}) => {\n const none = { approvals: [], hasMore: false, total: 0 }\n if (authority.type === \"denied\" || authority.type === \"delegated\") return none\n const storage = runtime.storage.agents\n if (!storage) return none\n\n if (input.threadId === undefined) return listOwnApprovals(storage, input)\n if (!(await getVisibleThreadRecord(input.threadId))) return none\n return storage.approvals.list({ ...input, projectId: runtime.projectId })\n },\n getById: getVisibleApproval,\n decide: async (approvalId, input) => {\n const approval = await getVisibleApproval(approvalId)\n if (!approval) {\n throw new AgentRequestError(\n \"approval_not_found\",\n `[Sixb] Agent approval '${approvalId}' was not found.`\n )\n }\n\n // The call runs with the deciding request's authority: it must be one a turn can inherit.\n if (!canInheritAgentRequestAuthorization(runtime.runtimeAuthorization)) {\n throw new AgentRequestError(\n \"authority_not_inheritable\",\n \"[Sixb] Deciding on an Agent call requires an authenticated user request or disabled authorization.\"\n )\n }\n\n // \"Always allow\" raises the thread's mode first: nothing has run yet if that fails.\n const always = input.always === true && input.decision === \"approve\"\n const raisedMode = always ? leastApprovalModeAllowing(approval.call) : undefined\n if (raisedMode !== undefined && approval.status === \"pending\") {\n await allowInThread(approval, raisedMode)\n }\n\n const decided = await decide(\n approval,\n input.decision === \"approve\" ? \"approved\" : \"denied\",\n raisedMode\n )\n if (raisedMode !== undefined && decided.status === \"approved\") {\n await approveAllowed(decided, raisedMode)\n }\n\n // The decision and the call's outcome stand from here: a resume that fails is reported.\n const resume = await resumeDecidedTurn(decided.runId)\n if (resume.status === \"refused\") return { approval: decided, resume }\n if (resume.status !== \"resumed\") return { approval: decided }\n\n // The resume reported it to the model.\n const reported = await requireAgents().approvals.getById({\n projectId: runtime.projectId,\n id: decided.id,\n })\n return { approval: reported ?? decided, run: await attachRunView(runtime, resume.run) }\n },\n }\n\n const decide = (\n approval: AgentApprovalRecord,\n decision: \"approved\" | \"denied\",\n raisedMode?: AgentApprovalMode\n ) =>\n decideAgentApproval(requireAgents(), getAgentApprovalExecutor(runtime), {\n approval,\n decision,\n decidedBy: principal,\n decider: { execution, authorization: runtime.runtimeAuthorization },\n ...(raisedMode === undefined ? {} : { raisedMode }),\n broker: runtime.broker,\n })\n\n /**\n * \"Always allow\": the caller's thread mode rises to the least that runs such a call, unless what\n * they chose already runs it. The fallback is no choice: it would hide the raise.\n */\n const allowInThread = async (\n approval: AgentApprovalRecord,\n raised: AgentApprovalMode\n ): Promise<void> => {\n const current = await getThreadApprovalMode(approval.threadId)\n const chosen = current?.approvalModeSource === \"fallback\" ? undefined : current?.approvalMode\n if (chosen === undefined || !approvalModeAllows(chosen, approval.call)) {\n await setThreadApprovalMode(approval.threadId, raised)\n }\n }\n\n /** \"Always allow\" also approves the turn's other calls the raised mode runs. */\n const approveAllowed = async (\n approval: AgentApprovalRecord,\n raised: AgentApprovalMode\n ): Promise<void> => {\n const { approvals: waiting } = await requireAgents().approvals.list({\n projectId: runtime.projectId,\n runId: approval.runId,\n requestedBy: principal,\n statuses: [\"pending\"],\n })\n for (const other of waiting) {\n if (!approvalModeAllows(raised, other.call)) continue\n try {\n await decide(other, \"approved\", raised)\n } catch (error) {\n // Decided, set aside or expired meanwhile: that outcome stands.\n if (!(error instanceof AgentRequestError)) throw error\n }\n }\n }\n\n /**\n * Resume a paused turn once its requester decided on every call it held, as that requester. It\n * never throws: what keeps the turn from resuming comes back as `refused`, and unless Sixb can\n * try again, the turn is stopped so that the thread's next message reports its calls.\n */\n const resumeDecidedTurn = async (runId: string): Promise<AgentApprovalResume> => {\n const agents = requireAgents()\n const run = await agents.runs.getById({ projectId: runtime.projectId, id: runId })\n if (run?.kind !== \"conversation\" || !isAwaitingApprovalRun(run)) return { status: \"closed\" }\n\n const requester = (\n await runtime.storage.executions.getById({\n projectId: runtime.projectId,\n id: run.executionId,\n })\n )?.requestedBy\n if (authority.type === \"principal\" && !(requester && principalsEqual(requester, principal))) {\n return { status: \"closed\" }\n }\n\n const stop = () => stopAgentTurn(agents, runtime.broker, run)\n try {\n // A requester who left the thread no longer runs turns in it.\n if (!(await rule.read(run.threadId))) {\n throw new AgentRequestError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${run.threadId}' is no longer readable by whoever asked for its turn.`\n )\n }\n\n const approvalMode = resumedApprovalMode(\n agentRunApprovalMode(run),\n await listTurnApprovals(agents, { projectId: runtime.projectId, runId: run.id }),\n await agents.approvalModes.getForThread({\n projectId: runtime.projectId,\n threadId: run.threadId,\n principal,\n })\n )\n const resumed = await resumeAgentTurn(runtime, execution, models?.language, run, {\n approvalMode,\n principal,\n })\n if (resumed.status === \"closed\") await stop()\n return resumed\n } catch (error) {\n const refused = refusedResume(error)\n if (!refused.retrying) await stop()\n return refused\n }\n }\n\n const preferences: AgentPreferencesRuntime = {\n get: async () => {\n const { approvalMode, approvalModeSource } = await defaultAgentApprovalMode(requireAgents(), {\n projectId: runtime.projectId,\n principal: settingsPrincipal(),\n })\n return {\n approvalMode,\n approvalModeSource: approvalModeSource === \"default\" ? \"default\" : \"fallback\",\n }\n },\n update: async (input) => {\n if (input.approvalMode !== undefined) {\n await requireAgents().approvalModes.setDefault({\n projectId: runtime.projectId,\n principal: settingsPrincipal(),\n mode: assertAgentApprovalMode(input.approvalMode),\n })\n }\n return preferences.get()\n },\n }\n\n const agentRuntime: AgentRuntime<TParams> = {\n get: getAgent,\n memory: createAgentMemoryRuntime(runtime),\n approvals,\n preferences,\n threads: {\n recreateSandbox: async (threadId, input) => {\n const readable = await rule.read(threadId)\n if (!readable)\n throw new AgentRequestError(\"thread_not_found\", \"[Sixb] Agent thread not found.\")\n assertConversationThread(readable.thread)\n if (readable.access !== \"owner\") {\n throw new AgentRequestError(\n \"not_thread_owner\",\n `[Sixb] Only the owner of Agent thread '${threadId}' can recreate its sandbox.`\n )\n }\n\n const thread = readable.thread\n const storage = runtime.storage.agents\n if (!storage)\n throw new AgentRequestError(\n \"storage_unavailable\",\n \"[Sixb] Agent storage is not configured.\"\n )\n const sandboxState = await storage.threads.transitionSandbox({\n projectId: runtime.projectId,\n id: threadId,\n action: \"recreate\",\n expectedSandboxName: input.expectedSandboxName,\n name: createAgentThreadSandboxName(runtime.projectId, threadId),\n })\n const [view] = await agentThreadViews(runtime, [{ ...thread, sandboxState }])\n return view ?? thread\n },\n create: async (input) => {\n assertNoAgentSelector(input)\n const agent = getAgent()\n if (!agent) {\n throw new AgentRequestError(\"agent_not_found\", \"[Sixb] The project Agent is unavailable.\")\n }\n const storage = runtime.storage.agents\n if (!storage) {\n throw new AgentRequestError(\n \"storage_unavailable\",\n \"[Sixb] Agent storage is not configured.\"\n )\n }\n if (input.sandbox !== undefined && !sandbox?.supportsPersistence) {\n throw new AgentRequestError(\n \"sandbox_not_configured\",\n \"[Sixb] Thread sandboxes require a provider with persistence support.\"\n )\n }\n const binding =\n input.sandbox === undefined\n ? undefined\n : normalizeSandboxBinding(sandbox?.definition, input.sandbox, runtime.ontology)\n const created = await storage.threads.create({\n ...(binding === undefined ? {} : { sandboxParams: binding }),\n id: input.id ?? createAgentThreadId(),\n projectId: runtime.projectId,\n ownerPrincipal: principal,\n ...(input.title === undefined ? {} : { title: input.title }),\n })\n return { ...created, participants: [] }\n },\n listChildren: async (threadId, { runId } = {}) => {\n const thread = await getVisibleThreadRecord(threadId)\n if (thread?.kind !== \"conversation\") return null\n return {\n children: await listAgentChildren(runtime, thread, {\n ...(runId === undefined ? {} : { spawnedBy: runId }),\n }),\n }\n },\n getChild: async (threadId) => {\n const thread = await getVisibleThreadRecord(threadId)\n const conversation = thread?.parent\n ? await getVisibleThreadRecord(thread.parent.threadId)\n : null\n return thread && conversation ? readAgentChild(runtime, conversation, thread) : null\n },\n fork: async (threadId) => {\n // Checked before the copy's transaction: an access removed in between can still fork once.\n const readable = await rule.read(threadId)\n if (!readable) {\n throw new AgentRequestError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${threadId}' not found.`\n )\n }\n // A sub-agent's work is continued by its conversation, never on its own.\n assertConversationThread(readable.thread)\n\n if (!getAgent()) {\n throw new AgentRequestError(\"agent_not_found\", \"[Sixb] The project Agent is unavailable.\")\n }\n\n const fork = await forkAgentThread(runtime, {\n source: readable.thread,\n ownerPrincipal: principal,\n sandbox,\n })\n const [view] = await agentThreadViews(runtime, [fork])\n return view ?? { ...fork, participants: [] }\n },\n getById: getVisibleThreadRecord,\n list: async ({ sharedWithMe, ...input } = {}) => {\n assertNoAgentSelector(input)\n const none = { threads: [], hasMore: false, total: 0 }\n if (authority.type === \"denied\" || authority.type === \"delegated\") return none\n\n const storage = runtime.storage.agents\n if (!storage || !allowed()) return none\n\n // Code without a caller owns every thread, so nothing is shared with it.\n const caller = authority.type === \"principal\" ? principal : undefined\n if (sharedWithMe && caller?.type !== \"user\") return none\n\n const result = await storage.threads.list({\n ...input,\n projectId: runtime.projectId,\n ...(sharedWithMe && caller?.type === \"user\"\n ? { participantPrincipal: caller }\n : { ownerPrincipal: caller }),\n })\n return { ...result, threads: await agentThreadViews(runtime, result.threads) }\n },\n participants: {\n add: (threadId, users) =>\n addAgentThreadParticipants(runtime, rule, security, threadId, users),\n remove: (threadId, user) => removeAgentThreadParticipant(runtime, rule, threadId, user),\n },\n getApprovalMode: getThreadApprovalMode,\n setApprovalMode: setThreadApprovalMode,\n },\n runs: {\n request: async (input) => {\n assertNoAgentSelector(input)\n const agent = getAgent()\n if (!agent) {\n throw new AgentRequestError(\"agent_not_found\", \"[Sixb] The project Agent is unavailable.\")\n }\n assertAuthorized(runtime, { kind: \"agent.run\" })\n if (input.threadId && !(await getVisibleThreadRecord(input.threadId))) {\n throw new AgentRequestError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${input.threadId}' not found.`\n )\n }\n const result = await requestAgentRun(runtime, execution, turnModels, {\n ...input,\n principal,\n })\n return { ...result, run: await attachRunView(runtime, result.run) }\n },\n retry: async (runId) => {\n const failedRun = await getControllableRun(runId, \"retry\")\n const agent = getAgent()\n if (!agent) {\n throw new AgentRequestError(\"agent_not_found\", \"[Sixb] The project Agent is unavailable.\")\n }\n const result = await retryAgentRun(runtime, execution, models?.language, failedRun)\n return { ...result, run: await attachRunView(runtime, result.run) }\n },\n cancel: async (runId) => {\n const run = await getVisibleRunRecord(runId)\n if (run?.kind !== \"subagent\") {\n const turn = await getControllableRun(runId, \"cancel\")\n return attachRunView(runtime, await cancelAgentRun(runtime, turn))\n }\n\n // A sub-agent's run stops as the turn it works under would.\n await getControllableRun(run.parentRunId, \"cancel\")\n return attachRunView(runtime, await cancelAgentChildRun(runtime, run))\n },\n getById: getRun,\n listForThread: async (threadId, input = {}) => {\n assertNoAgentSelector(input)\n const thread = await getVisibleThreadRecord(threadId)\n if (!thread) return null\n return listThreadRuns(runtime, thread, input)\n },\n },\n observed: createObservedAgentThreadsRuntime(runtime),\n }\n registerAgentTurnResume(agentRuntime, resumeDecidedTurn)\n return agentRuntime\n}\n\nfunction createObservedAgentThreadsRuntime(\n runtime: SixbRuntimeContext\n): ObservedAgentThreadsRuntime {\n const getById = async (threadId: string): Promise<AgentThreadView | null> => {\n assertAuthorized(runtime, { kind: \"agentThreads.observe\" })\n\n const thread = await runtime.storage.agents?.threads.getById({\n projectId: runtime.projectId,\n id: threadId,\n })\n if (!thread) return null\n\n const [view] = await agentThreadViews(runtime, [thread])\n return view ?? null\n }\n\n return {\n getById,\n\n async listRuns(threadId, input = {}) {\n assertNoAgentSelector(input)\n const thread = await getById(threadId)\n if (!thread) return null\n return listThreadRuns(runtime, thread, input)\n },\n\n async getChild(threadId) {\n const thread = await getById(threadId)\n const conversation = thread?.parent ? await getById(thread.parent.threadId) : null\n return thread && conversation ? readAgentChild(runtime, conversation, thread) : null\n },\n\n async listChildren(threadId, { runId } = {}) {\n const thread = await getById(threadId)\n if (thread?.kind !== \"conversation\") return null\n return {\n children: await listAgentChildren(runtime, thread, {\n ...(runId === undefined ? {} : { spawnedBy: runId }),\n }),\n }\n },\n }\n}\n\n/**\n * A thread's runs with their views: a conversation's turns, or a sub-agent's runs. Whoever calls it\n * has decided who may read them.\n */\nasync function listThreadRuns(\n runtime: SixbRuntimeContext,\n thread: Pick<AgentThreadRecord, \"id\" | \"kind\">,\n input: Omit<ListAgentRunsInput, \"projectId\" | \"threadId\">\n): Promise<AgentRunListResult | null> {\n const storage = runtime.storage.agents\n if (!storage) return null\n\n const result = await storage.runs.list({\n ...input,\n projectId: runtime.projectId,\n threadId: thread.id,\n kinds: [thread.kind],\n })\n return { ...result, runs: await attachRunViews(runtime, result.runs) }\n}\n\nasync function attachRunView<TRun extends AgentRunRecord>(\n runtime: SixbRuntimeContext,\n run: TRun\n): Promise<TRun & AgentRunViewFields> {\n const [view] = await attachRunViews(runtime, [run])\n if (!view) throw new Error(`[Sixb] Could not build Agent run '${run.id}' view.`)\n return view\n}\n\nasync function attachRunViews<TRun extends AgentRunRecord>(\n runtime: SixbRuntimeContext,\n runs: readonly TRun[]\n): Promise<readonly (TRun & AgentRunViewFields)[]> {\n const executionIds = runs.map((run) => run.executionId)\n const [executions, accounting] = await Promise.all([\n Promise.all(\n runs.map((run) =>\n runtime.storage.executions.getById({\n projectId: runtime.projectId,\n id: run.executionId,\n })\n )\n ),\n resolveTurnAccounting(runtime, executionIds),\n ])\n\n return runs.map((run, index) => {\n const execution = executions[index]\n if (!execution) {\n throw new Error(\n `[Sixb] Agent run '${run.id}' references missing execution '${run.executionId}'.`\n )\n }\n const { usage, cost } = accounting[index] ?? {}\n return {\n ...run,\n ...(execution.requestedBy === undefined\n ? {}\n : { requestedBy: structuredClone(execution.requestedBy) }),\n ...(usage === undefined ? {} : { usage }),\n ...(cost === undefined ? {} : { cost }),\n }\n })\n}\n\n/**\n * Why a resume was refused. An AI limit, or a failure Sixb did not expect, is tried again by the\n * worker's repair pass; a lost grant, a thread left or a sandbox to recreate is not.\n */\nfunction refusedResume(error: unknown): Extract<AgentApprovalResume, { status: \"refused\" }> {\n if (error instanceof AgentRequestError) {\n return { status: \"refused\", code: error.code, message: error.message, retrying: false }\n }\n if (error instanceof AuthorizationError) {\n return { status: \"refused\", code: \"forbidden\", message: error.message, retrying: false }\n }\n if (isSixbError(error)) {\n return { status: \"refused\", code: error.code, message: error.message, retrying: true }\n }\n console.error(\"[Sixb] Could not resume an Agent turn after its approvals; retrying later.\", error)\n return {\n status: \"refused\",\n code: \"internal.unexpected\",\n message: \"[Sixb] The Agent turn could not resume. Sixb tries again.\",\n retrying: true,\n }\n}\n",
53
+ "import { randomUUID } from \"node:crypto\"\nimport { assertAuthorized, isRuntimeAllowed } from \"../authorization\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type { SecurityDefinitionCatalog } from \"../security\"\nimport type {\n AiAccountingOverview,\n AiLimitPolicy,\n AiLimitPolicyStatus,\n CreateAiLimitPolicyInput,\n ListAiLimitPoliciesInput,\n ListAiLimitPolicyStatusesInput,\n ListAiModelCallAccountingInput,\n ListAiModelCallAccountingResult,\n ListAiModelCallGroupsInput,\n ListAiModelCallGroupsResult,\n QueryAiAccountingOverviewInput,\n ServiceAccountStatus,\n UpdateAiLimitPolicyInput,\n UserStatus,\n} from \"../storage\"\n\nexport type QueryAiUsageOverviewInput = Omit<QueryAiAccountingOverviewInput, \"projectId\">\nexport type ListAiUsageModelCallsInput = Omit<ListAiModelCallAccountingInput, \"projectId\">\nexport type ListAiUsageModelCallGroupsInput = Omit<ListAiModelCallGroupsInput, \"projectId\">\nexport type ListAiUsageLimitPoliciesInput = Omit<ListAiLimitPoliciesInput, \"projectId\">\nexport type ListAiUsageLimitStatusesInput = Omit<\n ListAiLimitPolicyStatusesInput,\n \"projectId\" | \"existingGroupIds\" | \"at\"\n>\nexport type CreateAiUsageLimitPolicyInput = Omit<\n CreateAiLimitPolicyInput,\n \"id\" | \"projectId\" | \"createdAt\"\n> & { readonly id?: string }\nexport type UpdateAiUsageLimitPolicyInput = Omit<\n UpdateAiLimitPolicyInput,\n \"projectId\" | \"updatedAt\"\n>\n\nexport interface AiUsageLimitGroupOption {\n readonly id: string\n readonly label?: string\n readonly description?: string\n}\n\nexport interface AiUsageLimitUserOption {\n readonly id: string\n readonly email: string\n readonly displayName?: string\n readonly status: UserStatus\n}\n\nexport interface AiUsageLimitServiceAccountOption {\n readonly id: string\n readonly name: string\n readonly description?: string\n readonly status: ServiceAccountStatus\n}\n\nexport interface AiUsageLimitSubjectOptions {\n readonly groups: readonly AiUsageLimitGroupOption[]\n readonly users: readonly AiUsageLimitUserOption[]\n readonly serviceAccounts: readonly AiUsageLimitServiceAccountOption[]\n}\n\n/** Project AI accounting and limit controls bound to one execution's authority. */\nexport interface AiUsageRuntime {\n readonly accountingConfigured: boolean\n readonly limitsConfigured: boolean\n assertObservable(): void\n assertManageable(): void\n canManageLimits(): boolean\n queryOverview(input: QueryAiUsageOverviewInput): Promise<AiAccountingOverview>\n listModelCalls(input: ListAiUsageModelCallsInput): Promise<ListAiModelCallAccountingResult>\n listModelCallGroups(input: ListAiUsageModelCallGroupsInput): Promise<ListAiModelCallGroupsResult>\n listLimitPolicies(input?: ListAiUsageLimitPoliciesInput): Promise<readonly AiLimitPolicy[]>\n listLimitStatuses(input?: ListAiUsageLimitStatusesInput): Promise<readonly AiLimitPolicyStatus[]>\n listLimitSubjectOptions(): Promise<AiUsageLimitSubjectOptions>\n createLimitPolicy(input: CreateAiUsageLimitPolicyInput): Promise<AiLimitPolicy>\n updateLimitPolicy(input: UpdateAiUsageLimitPolicyInput): Promise<AiLimitPolicy>\n deleteLimitPolicy(id: string): Promise<boolean>\n}\n\nexport function createAiUsageRuntime(\n runtime: SixbRuntimeContext,\n security: SecurityDefinitionCatalog\n): AiUsageRuntime {\n const assertObservable = () => assertAuthorized(runtime, { kind: \"aiUsage.observe\" })\n const assertManageable = () => assertAuthorized(runtime, { kind: \"aiUsage.manage\" })\n const assertPolicyReadable = () => {\n if (\n !isRuntimeAllowed(runtime, { kind: \"aiUsage.observe\" }) &&\n !isRuntimeAllowed(runtime, { kind: \"aiUsage.manage\" })\n ) {\n assertObservable()\n }\n }\n const requireCosts = () => {\n if (!runtime.storage.aiCosts) {\n throw new Error(\"[Sixb] AI cost storage is not configured.\")\n }\n return runtime.storage.aiCosts\n }\n const requireLimits = () => {\n if (!runtime.storage.aiLimits) {\n throw new Error(\"[Sixb] AI limit storage is not configured.\")\n }\n return runtime.storage.aiLimits\n }\n\n return {\n accountingConfigured: runtime.storage.aiCosts !== undefined,\n limitsConfigured: runtime.storage.aiLimits !== undefined,\n assertObservable,\n assertManageable,\n canManageLimits: () => isRuntimeAllowed(runtime, { kind: \"aiUsage.manage\" }),\n queryOverview: (input) => {\n assertObservable()\n return requireCosts().queryProjectOverview({ ...input, projectId: runtime.projectId })\n },\n listModelCalls: (input) => {\n assertObservable()\n return requireCosts().listModelCalls({ ...input, projectId: runtime.projectId })\n },\n listModelCallGroups: (input) => {\n assertObservable()\n return requireCosts().listModelCallGroups({ ...input, projectId: runtime.projectId })\n },\n listLimitPolicies: (input = {}) => {\n assertPolicyReadable()\n return requireLimits().listPolicies({ ...input, projectId: runtime.projectId })\n },\n listLimitStatuses: (input = {}) => {\n assertObservable()\n return requireLimits().listPolicyStatuses({\n ...(input.includeDisabled === undefined ? {} : { includeDisabled: input.includeDisabled }),\n projectId: runtime.projectId,\n existingGroupIds: security.listGroups().map((group) => group.id),\n })\n },\n listLimitSubjectOptions: async () => {\n assertManageable()\n const groups = security.listGroups().map((group) => ({\n id: group.id,\n ...(group.label === undefined ? {} : { label: group.label }),\n ...(group.description === undefined ? {} : { description: group.description }),\n }))\n const auth = runtime.storage.auth\n if (!auth) return { groups, users: [], serviceAccounts: [] }\n\n const [users, serviceAccounts] = await Promise.all([\n auth.users.list({ projectId: runtime.projectId, order: \"asc\" }),\n auth.serviceAccounts.list({ projectId: runtime.projectId, order: \"asc\" }),\n ])\n return {\n groups,\n users: users.users.map((user) => ({\n id: user.id,\n email: user.email,\n ...(user.displayName === undefined ? {} : { displayName: user.displayName }),\n status: user.status,\n })),\n serviceAccounts: serviceAccounts.serviceAccounts.map((serviceAccount) => ({\n id: serviceAccount.id,\n name: serviceAccount.name,\n ...(serviceAccount.description === undefined\n ? {}\n : { description: serviceAccount.description }),\n status: serviceAccount.status,\n })),\n }\n },\n createLimitPolicy: (input) => {\n assertManageable()\n return requireLimits().createPolicy({\n ...input,\n id: input.id ?? `ailim_${randomUUID()}`,\n projectId: runtime.projectId,\n })\n },\n updateLimitPolicy: (input) => {\n assertManageable()\n return requireLimits().updatePolicy({ ...input, projectId: runtime.projectId })\n },\n deleteLimitPolicy: (id) => {\n assertManageable()\n return requireLimits().deletePolicy({ id, projectId: runtime.projectId })\n },\n }\n}\n",
54
+ "import { assertProviderAccess } from \"../authorization\"\nimport type { ExecutionContext } from \"../execution\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport {\n type CreateFileDownloadUrlOptions,\n createFileDownloadUrl,\n type FileDownloadUrl,\n type FileDownloadUrlContext,\n revokeFileDownloadUrl,\n} from \"./download-urls\"\nimport { canonicalMediaType } from \"./media-type\"\nimport type {\n AbortBlobUploadInput,\n BlobByteRange,\n BlobInfo,\n BlobStorage,\n BlobUploadSession,\n CompleteBlobUploadInput,\n CreateBlobUploadInput,\n FileRef,\n PutBlobInput,\n SignBlobUploadPartInput,\n SignedBlobUploadPart,\n} from \"./types\"\nimport { supportsDirectUpload, supportsRangeRead } from \"./validation\"\n\n/** Blob operations bound to one execution. Provider lifecycle is deliberately host-only. */\nexport interface BlobsRuntime {\n put(input: PutBlobInput): Promise<FileRef>\n open(blobId: string): Promise<ReadableStream<Uint8Array>>\n stat(blobId: string): Promise<BlobInfo | null>\n /**\n * A URL anyone can use to read this file until it expires or is revoked, for services that\n * fetch media themselves. Requires the API's public origin (`SIXB_API_PUBLIC_ORIGIN`).\n */\n createDownloadUrl(file: FileRef, options?: CreateFileDownloadUrlOptions): Promise<FileDownloadUrl>\n /** Stop a URL from `createDownloadUrl()` before it expires. */\n revokeDownloadUrl(id: string): Promise<void>\n openRange?(blobId: string, range: BlobByteRange): Promise<ReadableStream<Uint8Array>>\n createUpload?(input: CreateBlobUploadInput): Promise<BlobUploadSession>\n signUploadPart?(input: SignBlobUploadPartInput): Promise<SignedBlobUploadPart>\n completeUpload?(input: CompleteBlobUploadInput): Promise<FileRef>\n abortUpload?(input: AbortBlobUploadInput): Promise<void>\n}\n\nexport function createBlobsRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n blobStorage: BlobStorage,\n apiPublicOrigin: () => string | undefined\n): BlobsRuntime {\n const assertAccess = () => assertProviderAccess(runtime, execution, \"blobs.access\")\n // Read the origin per call: the server or CLI may record it after this SDK was bound.\n const downloadUrlContext = (): FileDownloadUrlContext => ({\n projectId: runtime.projectId,\n storage: runtime.storage,\n blobStorage,\n executionId: execution.id,\n apiPublicOrigin: apiPublicOrigin(),\n })\n const executionBlobs: BlobsRuntime = {\n put: (input) => {\n assertAccess()\n assertMediaType(\"put\", input.mediaType)\n return blobStorage.put(input)\n },\n open: (blobId) => {\n assertAccess()\n return blobStorage.open(blobId)\n },\n stat: (blobId) => {\n assertAccess()\n return blobStorage.stat(blobId)\n },\n createDownloadUrl: async (file, options) => {\n assertAccess()\n return createFileDownloadUrl(downloadUrlContext(), file, options)\n },\n revokeDownloadUrl: async (id) => {\n assertAccess()\n return revokeFileDownloadUrl(downloadUrlContext(), id)\n },\n }\n\n if (supportsRangeRead(blobStorage)) {\n executionBlobs.openRange = (blobId, range) => {\n assertAccess()\n return blobStorage.openRange(blobId, range)\n }\n }\n if (supportsDirectUpload(blobStorage)) {\n executionBlobs.createUpload = (input) => {\n assertAccess()\n assertMediaType(\"createUpload\", input.mediaType)\n return blobStorage.createUpload(input)\n }\n executionBlobs.signUploadPart = (input) => {\n assertAccess()\n return blobStorage.signUploadPart(input)\n }\n executionBlobs.completeUpload = (input) => {\n assertAccess()\n assertMediaType(\"completeUpload\", input.mediaType)\n return blobStorage.completeUpload(input)\n }\n executionBlobs.abortUpload = (input) => {\n assertAccess()\n return blobStorage.abortUpload(input)\n }\n }\n\n return Object.freeze(executionBlobs)\n}\n\nfunction assertMediaType(method: string, mediaType: string | undefined): void {\n if (mediaType !== undefined && canonicalMediaType(mediaType) === null) {\n throw new Error(\n `[Sixb] blobs.${method}() mediaType must be one media type, such as \"application/pdf\". Received ${JSON.stringify(mediaType)}.`\n )\n }\n}\n",
55
+ "import { AuthorizationError, assertCanManageConnector } from \"../../authorization\"\nimport { resolveExecutionScopeAuthorization } from \"../../execution/authorization\"\nimport { executionRecordInputFromRuntime } from \"../../execution/durable\"\nimport type { ExecutionContext } from \"../../execution/types\"\nimport type { SixbRuntimeContext } from \"../../runtime/types\"\nimport type {\n AddConnectorConnectionInput,\n CompleteConnectorAuthorizationInput,\n CompleteConnectorAuthorizationResult,\n ConnectorConnectionCommandContext,\n ConnectorConnectionProcess,\n ConnectorConnectionRunView,\n ConnectorConnectionView,\n RevokeConnectorAuthorizationResult,\n SelectConnectorAccountInput,\n SelectConnectorConnectionRunAccountInput,\n StartConnectorAuthorizationInput,\n StartConnectorAuthorizationResult,\n StartConnectorConnectionRunInput,\n StartConnectorConnectionRunResult,\n} from \"./contracts\"\n\n/** Internal connector-connection lifecycle API bound to one authenticated request execution. */\nexport interface ConnectorConnectionsRuntime {\n listConnections(connectorId: string): Promise<readonly ConnectorConnectionView[]>\n startConnectionRun(\n connectorId: string,\n input: StartConnectorConnectionRunInput\n ): Promise<StartConnectorConnectionRunResult>\n addConnection(\n connectorId: string,\n input: AddConnectorConnectionInput\n ): Promise<ConnectorConnectionRunView>\n listPendingConnectionRuns(connectorId: string): Promise<readonly ConnectorConnectionRunView[]>\n getConnectionRun(connectorId: string, runId: string): Promise<ConnectorConnectionRunView | null>\n selectConnectionRunAccount(\n connectorId: string,\n input: SelectConnectorConnectionRunAccountInput\n ): Promise<ConnectorConnectionRunView>\n startReauthorization(\n connectorId: string,\n connectionId: string,\n input: Pick<StartConnectorConnectionRunInput, \"redirectUri\" | \"returnTo\">\n ): Promise<StartConnectorConnectionRunResult>\n revokeConnection(\n connectorId: string,\n connectionId: string\n ): Promise<RevokeConnectorAuthorizationResult>\n startAuthorization(\n connectorId: string,\n input: StartConnectorAuthorizationInput\n ): Promise<StartConnectorAuthorizationResult>\n completeAuthorization(\n connectorId: string,\n input: CompleteConnectorAuthorizationInput\n ): Promise<CompleteConnectorAuthorizationResult>\n selectAccount(\n connectorId: string,\n input: SelectConnectorAccountInput\n ): Promise<ConnectorConnectionView>\n disconnect(connectorId: string, connectionId: string): Promise<ConnectorConnectionView | null>\n revokeAuthorization(\n connectorId: string,\n authorizationId: string\n ): Promise<RevokeConnectorAuthorizationResult>\n}\n\nexport function createConnectorConnectionsRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n process: ConnectorConnectionProcess\n): ConnectorConnectionsRuntime {\n const contextFor = (connectorId: string) => commandContext(runtime, execution, connectorId)\n\n const connections: ConnectorConnectionsRuntime = {\n listConnections: (connectorId) => process.listConnections(contextFor(connectorId), connectorId),\n startConnectionRun: (connectorId, input) =>\n process.startConnectionRun(contextFor(connectorId), connectorId, input),\n addConnection: (connectorId, input) =>\n process.addConnection(contextFor(connectorId), connectorId, input),\n listPendingConnectionRuns: (connectorId) =>\n process.listPendingConnectionRuns(contextFor(connectorId), connectorId),\n getConnectionRun: (connectorId, runId) =>\n process.getConnectionRun(contextFor(connectorId), connectorId, runId),\n selectConnectionRunAccount: (connectorId, input) =>\n process.selectConnectionRunAccount(contextFor(connectorId), connectorId, input),\n startReauthorization: (connectorId, connectionId, input) =>\n process.startReauthorization(contextFor(connectorId), connectorId, connectionId, input),\n revokeConnection: (connectorId, connectionId) =>\n process.revokeConnection(contextFor(connectorId), connectorId, connectionId),\n startAuthorization: (connectorId, input) =>\n process.startAuthorization(contextFor(connectorId), connectorId, input),\n completeAuthorization: (connectorId, input) =>\n process.completeAuthorization(contextFor(connectorId), connectorId, input),\n selectAccount: (connectorId, input) =>\n process.selectAccount(contextFor(connectorId), connectorId, input),\n disconnect: (connectorId, connectionId) =>\n process.disconnect(contextFor(connectorId), connectorId, connectionId),\n revokeAuthorization: (connectorId, authorizationId) =>\n process.revokeAuthorization(contextFor(connectorId), connectorId, authorizationId),\n }\n return Object.freeze(connections)\n}\n\nfunction commandContext(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n connectorId: string\n): ConnectorConnectionCommandContext {\n const resolved = resolveExecutionScopeAuthorization(runtime.projectId, {\n execution,\n authorization: runtime.runtimeAuthorization,\n })\n\n if (\n execution.executor.type !== \"request\" ||\n resolved.type !== \"principal\" ||\n resolved.ref.type !== \"principal\"\n ) {\n throw new AuthorizationError(\n `manage:connector:${connectorId}`,\n \"[Sixb] Connector connections can only be managed by an authenticated request.\"\n )\n }\n if (!resolved.ref.credential) {\n throw new AuthorizationError(\n `manage:connector:${connectorId}`,\n \"[Sixb] Connector connection management requires a session or access token.\"\n )\n }\n\n assertCanManageConnector(runtime, connectorId)\n return Object.freeze({\n execution: Object.freeze(\n executionRecordInputFromRuntime({\n execution,\n runtimeAuthorization: runtime.runtimeAuthorization,\n })\n ),\n })\n}\n",
56
+ "import {\n assertAuthorized,\n assertPrivileged,\n assertRuntimeAuthorizationBound,\n isRuntimeAllowed,\n} from \"../authorization\"\nimport type { BlobStorage } from \"../blob-storage\"\nimport type { ExecutionContext } from \"../execution\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport type { DatasetMergeCommitResult } from \"../lake-storage/merge\"\nimport { getDatasetPrimaryKeyColumns } from \"../lake-storage/merge-validation\"\nimport type { DatasetRow, DatasetVersion, LakeStorage } from \"../lake-storage/types\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type { DatasetVersionMarkings } from \"../security/dataset-version-markings\"\nimport { missingClearanceRedactions } from \"../security/redactions\"\nimport type { Redactions } from \"../security/types\"\nimport type { MergeChange } from \"./changes\"\nimport type { DatasetDefinition } from \"./types\"\nimport { writeDataset } from \"./write\"\n\nexport interface DatasetIngestInput {\n readonly changes:\n | Iterable<MergeChange<DatasetRow, DatasetRow>>\n | AsyncIterable<MergeChange<DatasetRow, DatasetRow>>\n readonly signal?: AbortSignal\n}\n\n/** Source commit result; downstream pipelines and projections run asynchronously. */\nexport type DatasetIngestResult = DatasetMergeCommitResult & { readonly rowsRead: number }\n\nexport interface DatasetReadRowsInput {\n /** Defaults to the latest version. */\n readonly versionId?: string\n /** Defaults to every column of the version, in schema order. */\n readonly columns?: readonly string[]\n readonly limit?: number\n readonly offset?: number\n readonly signal?: AbortSignal\n}\n\nexport interface DatasetRows {\n readonly version: DatasetVersion\n /** Columns each row holds. Redacted columns are left out. */\n readonly columns: readonly string[]\n /**\n * Every column of the version the reader cannot read, whether or not it was requested. Absent\n * when the reader can read every column.\n */\n readonly redactions?: Redactions\n readonly rows: AsyncIterable<DatasetRow>\n}\n\nexport interface DatasetsRuntime {\n list(): readonly DatasetDefinition[]\n getById(datasetId: string): DatasetDefinition | null\n /**\n * Read rows of one version. Returns null when the dataset has no version yet or the requested\n * version does not exist.\n */\n readRows(dataset: DatasetDefinition, input?: DatasetReadRowsInput): Promise<DatasetRows | null>\n ingest(dataset: DatasetDefinition, input: DatasetIngestInput): Promise<DatasetIngestResult>\n}\n\nexport function createDatasetsRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n source: Pick<DatasetsRuntime, \"list\" | \"getById\">,\n lakeStorage: LakeStorage,\n blobStorage: Pick<BlobStorage, \"stat\">,\n versionMarkings: DatasetVersionMarkings\n): DatasetsRuntime {\n const authority = resolveRuntimeAuthorizationForProject(runtime)\n const allowed = (datasetId: string) =>\n isRuntimeAllowed(runtime, { kind: \"dataset.view\", datasetId })\n\n return {\n list: () =>\n authority.type === \"denied\" || authority.type === \"delegated\"\n ? []\n : source.list().filter((dataset) => allowed(dataset.id)),\n getById: (datasetId) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const dataset = source.getById(datasetId)\n return dataset && allowed(datasetId) ? dataset : null\n },\n async readRows(dataset, input = {}) {\n assertAuthorized(runtime, { kind: \"dataset.view\", datasetId: dataset.id })\n const registered = source.getById(dataset.id)\n if (!registered) throw new Error(`[Sixb] Dataset '${dataset.id}' is not registered.`)\n const version =\n input.versionId === undefined\n ? await lakeStorage.getLatestVersion(registered.id)\n : await lakeStorage.getVersion(registered.id, input.versionId)\n if (!version) return null\n\n const redacted = redactedColumns(\n version,\n versionMarkings,\n assertRuntimeAuthorizationBound(runtime)\n )\n const selected = selectColumns(version, input.columns)\n const columns = selected.filter((column) => !redacted.has(column))\n const read = (readColumns: readonly string[] | undefined) =>\n lakeStorage.readRows({\n datasetId: registered.id,\n versionId: version.versionId,\n columns: readColumns,\n limit: input.limit,\n offset: input.offset,\n signal: input.signal,\n })\n\n // Redacted columns are not read. A provider reads every column when given none, so a page\n // made only of redacted columns reads one of them to count its rows and returns them empty.\n const rows =\n columns.length === selected.length\n ? read(input.columns)\n : columns.length > 0\n ? read(columns)\n : emptyRows(read(selected.slice(0, 1)))\n return {\n version,\n columns,\n ...(redacted.size > 0 ? { redactions: missingClearanceRedactions(redacted) } : {}),\n rows,\n }\n },\n async ingest(dataset, input) {\n assertPrivileged(runtime, \"datasets.ingest\")\n const registered = source.getById(dataset.id)\n if (!registered) throw new Error(`[Sixb] Dataset '${dataset.id}' is not registered.`)\n if (getDatasetPrimaryKeyColumns(registered) === null) {\n throw new Error(`[Sixb] Dataset '${dataset.id}' must define a primaryKey before ingestion.`)\n }\n if (typeof lakeStorage.beginMerge !== \"function\") {\n throw new Error(\"[Sixb] Dataset ingestion requires a lake provider with merge support.\")\n }\n const producer = { kind: \"ingest\" as const, id: execution.id }\n const result = await writeDataset({\n lakeStorage,\n blobStorage,\n dataset: registered,\n mode: \"merge\",\n signal: input.signal ?? new AbortController().signal,\n producer,\n readValues: async () =>\n (async function* () {\n for await (const value of input.changes) yield { value }\n })(),\n })\n if (result.outcome === \"created\") {\n await runtime.events.emit(\n {\n events: [\n {\n type: \"dataset.version.committed\",\n payload: {\n datasetId: registered.id,\n versionId: result.version.versionId,\n createdAt: result.version.createdAt.toISOString(),\n producer,\n },\n },\n ],\n correlationId: execution.correlationId,\n },\n { source: \"SixbDatasets\" }\n )\n }\n return result\n },\n }\n}\n\n/** Requested columns, or every column of the version. Like the lake, an empty list means all. */\nfunction selectColumns(version: DatasetVersion, requested: readonly string[] | undefined) {\n const available = version.schema.columns.map((column) => column.name)\n if (requested === undefined || requested.length === 0) return available\n for (const column of requested) {\n if (!available.includes(column)) {\n throw new Error(\n `[Sixb] Dataset '${version.datasetId}' does not have column '${column}' at version '${version.versionId}'.`\n )\n }\n }\n return [...requested]\n}\n\n/**\n * Columns of the version the reader cannot read. Trusted code reads every column, a principal reads\n * what its roles clear, and any other authority is cleared for nothing.\n *\n * No version carries a marking the project does not declare on a column, so a reader cleared for\n * every declared marking (all readers, when none is declared) reads every column without\n * classifying the version.\n */\nfunction redactedColumns(\n version: DatasetVersion,\n versionMarkings: DatasetVersionMarkings,\n authority: ReturnType<typeof assertRuntimeAuthorizationBound>\n): ReadonlySet<string> {\n if (authority.type === \"unrestricted\") return new Set()\n const clearances =\n authority.type === \"principal\" ? (authority.context.clearances ?? new Set()) : new Set()\n if ([...versionMarkings.everyMarking()].every((id) => clearances.has(id))) return new Set()\n\n const { columns } = versionMarkings.classify(version)\n return new Set(\n [...columns]\n .filter(([, columnMarkings]) => [...columnMarkings].some((id) => !clearances.has(id)))\n .map(([column]) => column)\n )\n}\n\nasync function* emptyRows(rows: AsyncIterable<DatasetRow>): AsyncIterable<DatasetRow> {\n for await (const _row of rows) yield {}\n}\n",
57
+ "import { type ObjectBatchKey, objectBatchKey } from \"../storage\"\nimport type { AuthorizedObjectReader } from \"./authorized-object-reader\"\n\nexport interface ObjectKey {\n readonly objectTypeId: string\n readonly primaryId: string\n}\n\n/**\n * The objects among these that a reader sees now, by {@link objectBatchKey}: read through the\n * reader in one call, so its conditions decide. Each object type must be viewable by the reader.\n */\nexport async function visibleObjects(\n reader: AuthorizedObjectReader,\n objects: readonly ObjectKey[]\n): Promise<ReadonlySet<ObjectBatchKey>> {\n const items = new Map<ObjectBatchKey, ObjectKey>()\n for (const { objectTypeId, primaryId } of objects) {\n items.set(objectBatchKey(objectTypeId, primaryId), { objectTypeId, primaryId })\n }\n\n if (items.size === 0) return new Set()\n\n const rows = await reader.getByPrimaryIdBatch({ items: [...items.values()] })\n return new Set(rows.keys())\n}\n",
58
+ "import type {\n AuthorizedObjectReader,\n ReaderViewCondition,\n} from \"../execution/authorized-object-reader\"\nimport type { Clearance } from \"../execution/object-reader-clearance\"\nimport { type ObjectKey, visibleObjects } from \"../execution/visible-objects\"\nimport { matchesPredicate } from \"../objects/query/matches-predicate\"\nimport { type ObjectBatchKey, objectBatchKey } from \"../storage\"\nimport type { PropertyChangeMap } from \"./property-changes\"\nimport type {\n StoredDomainEvent,\n StoredObjectDeletedEvent,\n StoredObjectMutationEvent,\n} from \"./types\"\n\n/** Decided from the state the event carries, or by whether the reader sees the objects it names. */\ntype Decision = boolean | { readonly named: readonly ObjectKey[] }\n\n/** Where the state of an object that no longer exists is found. */\nexport interface ObjectHistory {\n /** The objects among these that exist, whoever may see them. */\n existing(objects: readonly ObjectKey[]): Promise<ReadonlySet<ObjectBatchKey>>\n\n /** The last event of an object before this event, or undefined when the log keeps none. */\n lastEventBefore(\n event: StoredDomainEvent,\n object: ObjectKey\n ): Promise<StoredObjectMutationEvent | StoredObjectDeletedEvent | undefined>\n}\n\n/**\n * The events, in order, whose objects a reader sees under the conditions it views their types\n * through. An event that names no conditioned type passes: its grants decided it.\n *\n * - An object's creation or update is decided on the state it carries, its deletion on the last\n * state the object held.\n * - Link events, telemetry and rule transitions carry no state to decide on. The objects they name\n * of a conditioned type are read through the reader as they are now, in one call for the batch.\n * - One that no longer exists is decided on the state it held when the event happened, from its\n * last event before it. A reader who saw an object is told what its deletion removed, and\n * one who never saw it is told nothing, as for a hidden object.\n */\nexport async function visibleUnderConditions(\n reader: AuthorizedObjectReader,\n events: readonly StoredDomainEvent[],\n conditions: ReadonlyMap<string, ReaderViewCondition>,\n clearanceFor: (event: StoredDomainEvent) => Clearance,\n history: ObjectHistory\n): Promise<readonly StoredDomainEvent[]> {\n if (conditions.size === 0) return events\n\n const decisions = events.map((event) => decide(event, conditions, clearanceFor(event)))\n\n const named = decisions.flatMap((decision) =>\n typeof decision === \"boolean\" ? [] : decision.named\n )\n const seenNow = await visibleObjects(reader, named)\n const seenThen = await seenBeforeDeletion(events, decisions, seenNow, conditions, history)\n\n return events.filter((_, index) => {\n const decision = decisions[index]!\n if (typeof decision === \"boolean\") return decision\n\n return decision.named.every((object) => {\n const key = objectBatchKey(object.objectTypeId, object.primaryId)\n return seenNow.has(key) || seenThen.has(eventObjectKey(index, key))\n })\n })\n}\n\n/**\n * Among the objects the reader does not see now, those that no longer exist and that it saw when\n * the event naming them happened, keyed by {@link eventObjectKey}.\n *\n * One that still exists is hidden, and its events with it. Only the others are looked up in the\n * log, so a reader pays for it only when an event names an object since deleted.\n */\nasync function seenBeforeDeletion(\n events: readonly StoredDomainEvent[],\n decisions: readonly Decision[],\n seenNow: ReadonlySet<ObjectBatchKey>,\n conditions: ReadonlyMap<string, ReaderViewCondition>,\n history: ObjectHistory\n): Promise<ReadonlySet<string>> {\n const unseen = decisions.flatMap((decision, index) =>\n typeof decision === \"boolean\"\n ? []\n : decision.named\n .map((object) => ({\n index,\n object,\n key: objectBatchKey(object.objectTypeId, object.primaryId),\n }))\n .filter(({ key }) => !seenNow.has(key))\n )\n if (unseen.length === 0) return new Set()\n\n const unique = new Map(unseen.map(({ object, key }) => [key, object]))\n const existing = await history.existing([...unique.values()])\n const deleted = unseen.filter(({ key }) => !existing.has(key))\n\n const seenThen = await Promise.all(\n deleted.map(async ({ index, object }) => {\n const last = await history.lastEventBefore(events[index]!, object)\n if (!last) return false\n\n const properties =\n last.type === \"object.deleted\"\n ? lastState(last.payload.propertyChanges)\n : last.payload.properties\n\n return matchesPredicate({ properties }, conditions.get(object.objectTypeId)!.predicate)\n })\n )\n\n return new Set(\n deleted.flatMap(({ index, key }, at) => (seenThen[at] ? [eventObjectKey(index, key)] : []))\n )\n}\n\n/** An object as one event of the batch names it. */\nfunction eventObjectKey(index: number, key: ObjectBatchKey): string {\n return `${index}\\u0000${key}`\n}\n\nfunction decide(\n event: StoredDomainEvent,\n conditions: ReadonlyMap<string, ReaderViewCondition>,\n clearance: Clearance\n): Decision {\n switch (event.topic) {\n case \"objects\": {\n const condition = conditions.get(event.payload.objectTypeId)\n if (!condition) return true\n if (condition.hiddenBy(clearance)) return false\n\n const properties =\n event.type === \"object.deleted\"\n ? lastState(event.payload.propertyChanges)\n : event.payload.properties\n\n // The object is visible in the state the event carries. An update after which it no longer\n // is delivers nothing: the reader's copy stays stale until it reads the object again.\n return matchesPredicate({ properties }, condition.predicate)\n }\n\n case \"links\": {\n const { sourceTypeId, sourceId, targetTypeId, targetId } = event.payload\n return namedObjects(conditions, clearance, [\n { objectTypeId: sourceTypeId, primaryId: sourceId },\n { objectTypeId: targetTypeId, primaryId: targetId },\n ])\n }\n\n case \"telemetry\": {\n const { objectTypeId, objectId } = event.payload\n return namedObjects(conditions, clearance, [{ objectTypeId, primaryId: objectId }])\n }\n\n case \"rules\": {\n const { objectTypeId, primaryId } = event.payload.subject\n return namedObjects(conditions, clearance, [{ objectTypeId, primaryId }])\n }\n\n default:\n return true\n }\n}\n\n/**\n * An update shown to a reader who could not see the object before it: what the object held then\n * is not this reader's to know. Decided on the event as stored, applied to the event as shown.\n *\n * Each change then reads as the object appearing with its new value. A property the update cleared\n * did not exist for this reader, so its change is left out.\n */\nexport function withoutHiddenPriorState(\n stored: StoredDomainEvent,\n shown: StoredDomainEvent,\n conditions: ReadonlyMap<string, ReaderViewCondition>\n): StoredDomainEvent {\n if (stored.type !== \"object.updated\" || shown.type !== \"object.updated\") return shown\n\n const condition = conditions.get(stored.payload.objectTypeId)\n if (!condition) return shown\n\n const prior = priorState(stored.payload.properties, stored.payload.propertyChanges)\n if (matchesPredicate({ properties: prior }, condition.predicate)) return shown\n\n const propertyChanges = Object.fromEntries(\n Object.entries(shown.payload.propertyChanges).flatMap(([propertyId, change]) =>\n change.operation === \"cleared\"\n ? []\n : [[propertyId, { operation: \"created\" as const, after: change.after }]]\n )\n )\n\n return { ...shown, payload: { ...shown.payload, propertyChanges } }\n}\n\n/** The properties an object held before an update, from its new state and what changed. */\nfunction priorState(\n properties: Readonly<Record<string, unknown>>,\n changes: PropertyChangeMap\n): Record<string, unknown> {\n const prior: Record<string, unknown> = { ...properties }\n\n for (const [propertyId, change] of Object.entries(changes)) {\n if (change.operation === \"created\") delete prior[propertyId]\n else prior[propertyId] = change.before\n }\n\n return prior\n}\n\n/** The objects of a conditioned type among these, which the reader must see. */\nfunction namedObjects(\n conditions: ReadonlyMap<string, ReaderViewCondition>,\n clearance: Clearance,\n objects: readonly ObjectKey[]\n): Decision {\n const conditioned = objects.filter((object) => conditions.has(object.objectTypeId))\n if (conditioned.length === 0) return true\n\n if (conditioned.some((object) => conditions.get(object.objectTypeId)!.hiddenBy(clearance))) {\n return false\n }\n\n return { named: conditioned }\n}\n\n/** A deletion records every property the object held as cleared, with the value it had. */\nfunction lastState(changes: PropertyChangeMap): Record<string, unknown> {\n const properties: Record<string, unknown> = {}\n\n for (const [propertyId, change] of Object.entries(changes)) {\n if (change.operation !== \"created\") properties[propertyId] = change.before\n }\n\n return properties\n}\n",
59
+ "import { assertPrivileged, canViewEvent } from \"../authorization\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport {\n type AuthorizedObjectReader,\n readerClearance,\n readerEventClearance,\n readerViewConditions,\n} from \"../execution/authorized-object-reader\"\nimport type { EventSources } from \"../execution/object-reader-clearance\"\nimport { redactDomainEvent } from \"../objects/clearance-redaction\"\nimport type { PropertyClearance } from \"../objects/property-clearance\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type {\n EventsAppendInput,\n EventsEmitOptions,\n EventsReadInput,\n EventsSubscribeInput,\n} from \"./service\"\nimport type { StoredDomainEvent } from \"./types\"\nimport {\n type ObjectHistory,\n visibleUnderConditions,\n withoutHiddenPriorState,\n} from \"./view-conditions\"\n\nexport interface EventsRuntime {\n /**\n * The events this execution may read, in order: hidden events are dropped, the others redacted.\n * Markings apply as they are now, with those of the versions an object event's values came from:\n * the version a projection's event applied, and every marking a column declares for projected\n * values that came from earlier versions.\n */\n visible(events: readonly StoredDomainEvent[]): Promise<readonly StoredDomainEvent[]>\n append(input: EventsAppendInput): Promise<readonly StoredDomainEvent[]>\n emit(input: EventsAppendInput, options: EventsEmitOptions): Promise<void>\n read(input?: EventsReadInput): Promise<readonly StoredDomainEvent[]>\n latestCursor(): Promise<string | undefined>\n /**\n * Deliver the events this execution may read as they are appended. A batch whose markings cannot\n * be enforced, because the versions projections applied cannot be read, is dropped with a\n * warning: read it again with `read({ afterCursor })`.\n */\n subscribe(\n input: EventsSubscribeInput,\n handler: (events: readonly StoredDomainEvent[]) => unknown\n ): Promise<() => void>\n}\n\nexport function createEventsRuntime(runtime: SixbRuntimeContext): EventsRuntime {\n const authority = resolveRuntimeAuthorizationForProject(runtime)\n\n // Objects an event names that the reader cannot read: storage tells which still exist, and the\n // log what the others held. Neither answer is shown.\n const history: ObjectHistory = {\n existing: async (objects) => {\n const rows = await runtime.storage.objects.getByPrimaryIdBatch({\n projectId: runtime.projectId,\n items: objects,\n })\n return new Set(rows.keys())\n },\n lastEventBefore: (event, object) =>\n runtime.events.lastObjectEventBefore({ cursor: event.cursor, ...object }),\n }\n\n const visible = async (\n events: readonly StoredDomainEvent[]\n ): Promise<readonly StoredDomainEvent[]> => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return []\n case \"unrestricted\":\n return events\n case \"principal\": {\n const reader = runtime.objectReader\n const conditions = readerViewConditions(reader)\n const viewable = events.filter((event) =>\n canViewEvent(authority.context, event, conditions)\n )\n if (viewable.length === 0) return viewable\n\n const clearance = await readerClearance(reader)\n const clearanceFor = await eventClearances(reader, viewable, clearance)\n\n const readable = clearance\n ? viewable.filter((event) => !readsUnreadable(event, clearance))\n : viewable\n const shown = await visibleUnderConditions(\n reader,\n readable,\n conditions,\n clearanceFor,\n history\n )\n\n return shown.map((event) => {\n const redacting = clearanceFor(event)\n const redacted = redacting ? redactDomainEvent(event, redacting) : event\n return withoutHiddenPriorState(event, redacted, conditions)\n })\n }\n }\n }\n\n return {\n visible,\n append: (input) => {\n assertPrivileged(runtime, \"events.append\")\n return runtime.events.append(input)\n },\n emit: (input, options) => {\n assertPrivileged(runtime, \"events.emit\")\n return runtime.events.emit(input, options)\n },\n read: async (input) => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return []\n case \"principal\":\n case \"unrestricted\":\n break\n }\n return visible(await runtime.events.read(input))\n },\n latestCursor: () => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return Promise.resolve(undefined)\n case \"principal\":\n case \"unrestricted\":\n return runtime.events.latestCursor()\n }\n },\n subscribe: (input, handler) => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return Promise.resolve(() => {})\n case \"principal\":\n case \"unrestricted\":\n break\n }\n return runtime.events.subscribe(input, async (events) => {\n let shown: readonly StoredDomainEvent[]\n try {\n shown = await visible(events)\n } catch (error) {\n // Fail closed. Delivery is live and keeps no progress, and a handler error is not a\n // negative acknowledgement, so the batch is dropped and reported rather than retried.\n const message = error instanceof Error ? error.message : String(error)\n console.warn(\n `[Sixb] Dropped ${events.length} event(s) from cursor '${events[0]?.cursor}' of a subscription, whose markings could not be enforced: ${message}`\n )\n return\n }\n\n if (shown.length > 0) return handler(shown)\n })\n },\n }\n}\n\n/**\n * The clearance each event is redacted with, resolved once per kind of event for the whole batch.\n * An event that holds only values the current markings describe uses the reader's clearance.\n */\nasync function eventClearances(\n reader: AuthorizedObjectReader,\n events: readonly StoredDomainEvent[],\n clearance: PropertyClearance | undefined\n): Promise<(event: StoredDomainEvent) => PropertyClearance | undefined> {\n const kinds = new Map<string, EventSources>()\n for (const event of events) {\n const kind = eventSources(event)\n if (kind) kinds.set(kind.key, kind.sources)\n }\n\n const resolved = await Promise.all(\n [...kinds].map(\n async ([key, sources]) => [key, await readerEventClearance(reader, sources)] as const\n )\n )\n const byKind = new Map(resolved)\n\n return (event) => {\n const kind = eventSources(event)\n return kind ? byKind.get(kind.key) : clearance\n }\n}\n\n/**\n * Where an object event's values came from, when the current markings do not describe them all.\n *\n * - A projection's event holds the values of the version it applied.\n * - An update or a deletion also holds the values it replaced. An action's or a direct write's\n * record of an object holds the values projections had applied then. Both came from versions\n * applied before the event, which it does not name: they read like a version that cannot be read.\n * - Only an object created by an action or a direct write holds nothing but its own values.\n */\nfunction eventSources(\n event: StoredDomainEvent\n): { readonly key: string; readonly sources: EventSources } | undefined {\n if (event.topic !== \"objects\") return undefined\n\n const objectTypeId = event.payload.objectTypeId\n const earlier = event.type !== \"object.created\"\n\n if (event.origin?.kind !== \"projection\") {\n if (!earlier) return undefined\n return { key: JSON.stringify([objectTypeId]), sources: { objectTypeId, earlier } }\n }\n\n const { projectionId, datasetId, datasetVersionId } = event.origin\n const origin = { projectionId, datasetId, datasetVersionId, objectTypeId }\n return {\n key: JSON.stringify([objectTypeId, projectionId, datasetId, datasetVersionId, earlier]),\n sources: { objectTypeId, origin, earlier },\n }\n}\n\n/**\n * Whether the event is about an object type or a link the reader cannot read: it reveals ids and\n * keys, so it is not delivered, as for a type the reader has no view grant for.\n */\nfunction readsUnreadable(event: StoredDomainEvent, clearance: PropertyClearance): boolean {\n switch (event.topic) {\n case \"objects\":\n case \"telemetry\":\n return clearance.unreadableType(event.payload.objectTypeId) !== undefined\n case \"rules\":\n return clearance.unreadableType(event.payload.subject.objectTypeId) !== undefined\n case \"links\":\n return (\n clearance.unreadableType(event.payload.sourceTypeId) !== undefined ||\n clearance.unreadableType(event.payload.targetTypeId) !== undefined ||\n clearance.unreadableLink(event.payload.sourceTypeId, event.payload.linkId) !== undefined\n )\n default:\n return false\n }\n}\n",
60
+ "export class WorkflowDefinitionError extends Error {\n readonly name = \"WorkflowDefinitionError\"\n}\n\nexport class WorkflowValidationError extends Error {\n readonly name = \"WorkflowValidationError\"\n override readonly cause?: unknown\n\n constructor(message: string, options?: { readonly cause?: unknown }) {\n super(message)\n this.cause = options?.cause\n }\n}\n",
61
+ "import { randomUUID } from \"node:crypto\"\nimport { isDeepStrictEqual } from \"node:util\"\nimport { SYSTEM_PRINCIPAL } from \"../auth\"\nimport { reportRunFailure } from \"../error-reporting/capability\"\nimport { captureSixbFailure } from \"../errors/internal\"\nimport type { DomainEventLog } from \"../events\"\nimport type { RunDispatcher } from \"../execution/dispatch\"\nimport { createPrimitiveExecutionRecord } from \"../execution/durable\"\nimport type { SchemaOrRef, ValueType } from \"../ontology\"\nimport type { Queues } from \"../queues\"\nimport type { SixbDefinitions } from \"../runtime/definitions\"\nimport { assertParamUsersActive } from \"../shared/params/user-refs\"\nimport type { CreateExecutionInput, Storage, WorkflowRunRecord } from \"../storage\"\nimport { WORKFLOW_RUN_FAILURE_CODES, WorkflowRunError } from \"../storage\"\nimport { WorkflowValidationError } from \"./errors\"\nimport type { WorkflowRunRequestResult } from \"./request\"\nimport { snapshotWorkflowInput } from \"./snapshot\"\nimport type { WorkflowDefinition, WorkflowIOSnapshot, WorkflowRunSource } from \"./types\"\n\nexport type AutomaticWorkflowExecutionSource =\n | { readonly type: \"schedule\"; readonly eventId: string }\n | { readonly type: \"event\"; readonly eventId: string }\n\n/** One automatic match already resolved to a stable workflow run identity by the orchestrator. */\nexport interface AutomaticWorkflowRunDispatchInput {\n readonly workflowId: string\n readonly runId: string\n readonly input?: Readonly<Record<string, unknown>>\n readonly scheduleId: string\n readonly source: AutomaticWorkflowExecutionSource\n readonly correlationId: string\n readonly metadata?: Readonly<Record<string, string>>\n}\n\nexport type WorkflowRunDispatchPort = RunDispatcher<\n AutomaticWorkflowRunDispatchInput,\n WorkflowRunRequestResult\n>\n\nexport interface WorkflowRunDispatcherDependencies {\n readonly id: string\n readonly definitions: Pick<SixbDefinitions, \"ontology\" | \"workflows\">\n readonly storage: Storage\n readonly queues: Pick<Queues, \"workflows\">\n readonly events: DomainEventLog\n}\n\ninterface DispatchWorkflowRunInput {\n readonly errorReporterHost: object\n readonly projectId: string\n readonly workflow: WorkflowDefinition\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n readonly storage: Storage\n readonly queue: Queues[\"workflows\"]\n readonly events: DomainEventLog\n readonly runId?: string\n readonly input?: Readonly<Record<string, unknown>>\n readonly source?: WorkflowRunSource\n readonly metadata?: Readonly<Record<string, string>>\n readonly queueJobId?: string\n /** Automatic callers own publication retries; validate provenance before any replay effect. */\n readonly validateExistingRun?: (run: WorkflowRunRecord) => Promise<void>\n readonly createExecution: (executionId: string, runId: string) => Promise<CreateExecutionInput>\n}\n\ninterface PreparedWorkflowRun {\n readonly runId: string\n readonly snapshot: WorkflowIOSnapshot\n}\n\ntype PersistedWorkflowRun =\n | {\n readonly created: false\n readonly run: WorkflowRunRecord\n }\n | {\n readonly created: true\n readonly run: WorkflowRunRecord\n readonly execution: CreateExecutionInput\n readonly queuedAt: Date\n }\n\n/** Core-owned durable dispatch boundary used by automatic trigger runtimes. */\nexport class WorkflowRunDispatcher implements WorkflowRunDispatchPort {\n constructor(private readonly dependencies: WorkflowRunDispatcherDependencies) {}\n\n async dispatch(input: AutomaticWorkflowRunDispatchInput): Promise<WorkflowRunRequestResult> {\n assertAutomaticDispatchInput(input)\n const workflow = this.dependencies.definitions.workflows.getById(input.workflowId)\n if (!workflow) {\n throw new WorkflowValidationError(`[Sixb] Unknown workflow '${input.workflowId}'`)\n }\n\n return dispatchWorkflowRun({\n errorReporterHost: this.dependencies,\n projectId: this.dependencies.id,\n workflow,\n valueTypesById: this.dependencies.definitions.ontology.getValueTypesById(),\n storage: this.dependencies.storage,\n queue: this.dependencies.queues.workflows,\n events: this.dependencies.events,\n runId: input.runId,\n input: input.input,\n source: {\n type: \"schedule\",\n scheduleId: input.scheduleId,\n eventId: input.source.eventId,\n principal: SYSTEM_PRINCIPAL,\n },\n metadata: input.metadata,\n queueJobId: input.runId,\n validateExistingRun: (run) => assertAutomaticExecutionIdentity(this.dependencies, input, run),\n createExecution: async (executionId, runId) =>\n createPrimitiveExecutionRecord({\n id: executionId,\n primitive: { kind: \"workflow\", id: workflow.id, runId },\n origin: {\n type: \"automatic\",\n projectId: this.dependencies.id,\n source: input.source,\n correlationId: input.correlationId,\n },\n }),\n })\n }\n}\n\n/** Persist a workflow execution and run before publishing its queue job. */\nexport async function dispatchWorkflowRun(\n input: DispatchWorkflowRunInput\n): Promise<WorkflowRunRequestResult> {\n const request = prepareWorkflowRun(input)\n const persisted = await persistWorkflowRun(input, request)\n if (!persisted.created) {\n await input.validateExistingRun?.(persisted.run)\n if (input.validateExistingRun && persisted.run.status === \"queued\") {\n // A queued run is also the recoverable intent when publication never completed.\n // Reuse the provider job identity, including after a successful but unacknowledged enqueue.\n await enqueueWorkflowRun(input, persisted.run)\n }\n return existingWorkflowRunResult(persisted.run)\n }\n return publishWorkflowRun(input, persisted)\n}\n\nfunction prepareWorkflowRun(input: DispatchWorkflowRunInput): PreparedWorkflowRun {\n const value = input.input ?? {}\n return {\n runId: resolveWorkflowRunId(input.runId),\n snapshot: snapshotWorkflowInput({\n workflow: input.workflow,\n value,\n valueTypesById: input.valueTypesById,\n }),\n }\n}\n\nasync function persistWorkflowRun(\n input: DispatchWorkflowRunInput,\n request: PreparedWorkflowRun\n): Promise<PersistedWorkflowRun> {\n const workflowRuns = input.storage.workflowRuns\n if (!workflowRuns) {\n throw new WorkflowValidationError(\"[Sixb] Workflow run storage is not configured.\")\n }\n\n const existing = await workflowRuns.getById({\n projectId: input.projectId,\n id: request.runId,\n })\n if (existing) {\n assertExistingWorkflowRun(existing, input.workflow.id, request.snapshot)\n return { run: existing, created: false }\n }\n\n // A replayed run keeps the input it was accepted with; only a new run checks its users.\n await assertParamUsersActive({\n auth: input.storage.auth,\n projectId: input.projectId,\n schemas: input.workflow.input as Readonly<Record<string, SchemaOrRef>>,\n values: request.snapshot,\n valueTypesById: input.valueTypesById,\n describe: (fieldId) => `Workflow \"${input.workflow.id}\" input '${fieldId}'`,\n invalid: (message) => new WorkflowValidationError(message),\n })\n const execution = await input.createExecution(`exec_${randomUUID()}`, request.runId)\n const queuedAt = new Date()\n try {\n return await input.storage.transaction(\n async (tx): Promise<PersistedWorkflowRun> => {\n const raced = await tx.workflowRuns?.getById({\n projectId: input.projectId,\n id: request.runId,\n })\n if (raced) {\n assertExistingWorkflowRun(raced, input.workflow.id, request.snapshot)\n return { run: raced, created: false }\n }\n if (!tx.workflowRuns) {\n throw new WorkflowValidationError(\"[Sixb] Workflow run storage is not configured.\")\n }\n\n await tx.executions.create(execution)\n const run = await tx.workflowRuns.queue({\n projectId: input.projectId,\n id: request.runId,\n executionId: execution.id,\n workflowId: input.workflow.id,\n input: request.snapshot,\n queuedAt,\n })\n return { run, execution, queuedAt, created: true }\n },\n { isolation: \"serializable\" }\n )\n } catch (error) {\n if (!(error instanceof WorkflowRunError)) throw error\n const raced = await workflowRuns.getById({\n projectId: input.projectId,\n id: request.runId,\n })\n if (!raced) throw error\n assertExistingWorkflowRun(raced, input.workflow.id, request.snapshot)\n return { run: raced, created: false }\n }\n}\n\nasync function publishWorkflowRun(\n input: DispatchWorkflowRunInput,\n persisted: Extract<PersistedWorkflowRun, { readonly created: true }>\n): Promise<WorkflowRunRequestResult> {\n let job: Awaited<ReturnType<Queues[\"workflows\"][\"enqueue\"]>>[number] | undefined\n try {\n job = await enqueueWorkflowRun(input, persisted.run)\n } catch (error) {\n // Automatic dispatch retries the same run. Do not turn an uncertain enqueue into\n // a terminal business failure: the queue may have accepted it before losing the reply.\n if (!input.validateExistingRun) await failWorkflowRunPublication(input, persisted.run, error)\n throw error\n }\n\n await input.events.emit(\n {\n events: [\n {\n type: \"workflow.run.queued\",\n payload: {\n workflowId: persisted.run.workflowId,\n runId: persisted.run.id,\n queuedAt: persisted.queuedAt.toISOString(),\n ...(job?.id ? { jobId: job.id } : {}),\n ...(input.source === undefined ? {} : { source: input.source }),\n },\n },\n ],\n correlationId: persisted.execution.correlationId,\n },\n { source: \"Sixb\" }\n )\n\n return {\n workflowId: persisted.run.workflowId,\n runId: persisted.run.id,\n queuedAt: persisted.queuedAt.toISOString(),\n jobId: job?.id,\n created: true,\n }\n}\n\nasync function enqueueWorkflowRun(\n input: DispatchWorkflowRunInput,\n run: WorkflowRunRecord\n): Promise<Awaited<ReturnType<Queues[\"workflows\"][\"enqueue\"]>>[number]> {\n const [job] = await input.queue.enqueue({\n projectId: input.projectId,\n jobs: [\n {\n ...(input.queueJobId === undefined ? {} : { id: input.queueJobId }),\n type: \"workflow.run.requested\",\n payload: { runId: run.id },\n ...(input.metadata === undefined ? {} : { metadata: input.metadata }),\n },\n ],\n })\n if (!job || (input.queueJobId !== undefined && job.id !== input.queueJobId)) {\n throw new WorkflowRunError(`[Sixb] Queue did not acknowledge workflow run '${run.id}'.`)\n }\n return job\n}\n\nasync function failWorkflowRunPublication(\n input: DispatchWorkflowRunInput,\n run: WorkflowRunRecord,\n error: unknown\n): Promise<void> {\n const workflowRuns = input.storage.workflowRuns\n if (!workflowRuns) {\n throw new WorkflowValidationError(\"[Sixb] Workflow run storage is not configured.\")\n }\n const failure = captureSixbFailure(error, {\n allowedCodes: WORKFLOW_RUN_FAILURE_CODES,\n defaultCode: \"internal.unexpected\",\n details: { workflowId: run.workflowId, runId: run.id },\n })\n await workflowRuns.finish({\n projectId: input.projectId,\n id: run.id,\n status: \"failed\",\n error: failure,\n })\n reportRunFailure(input.errorReporterHost, error, {\n projectId: input.projectId,\n runKind: \"workflow\",\n run: { runId: run.id, workflowId: run.workflowId },\n failure,\n })\n}\n\nfunction resolveWorkflowRunId(runId: string | undefined): string {\n if (runId === undefined) return `run_${randomUUID()}`\n if (!runId.trim()) {\n throw new WorkflowValidationError(\"[Sixb] Workflow run id must not be empty\")\n }\n return runId\n}\n\nfunction assertExistingWorkflowRun(\n existing: WorkflowRunRecord,\n workflowId: string,\n input: WorkflowRunRecord[\"input\"]\n): void {\n if (existing.workflowId !== workflowId || !isDeepStrictEqual(existing.input, input)) {\n throw new WorkflowValidationError(\n `[Sixb] Workflow run '${existing.id}' already exists with a different request payload.`\n )\n }\n}\n\nfunction existingWorkflowRunResult(existing: WorkflowRunRecord): WorkflowRunRequestResult {\n return {\n workflowId: existing.workflowId,\n runId: existing.id,\n queuedAt: (existing.queuedAt ?? existing.startedAt).toISOString(),\n created: false,\n }\n}\n\nfunction assertAutomaticDispatchInput(input: AutomaticWorkflowRunDispatchInput): void {\n assertNonBlank(input.workflowId, \"Workflow id\")\n assertNonBlank(input.runId, \"Workflow run id\")\n assertNonBlank(input.scheduleId, \"Workflow schedule id\")\n assertNonBlank(input.source.eventId, \"Workflow source event id\")\n assertNonBlank(input.correlationId, \"Workflow correlation id\")\n}\n\nasync function assertAutomaticExecutionIdentity(\n dependencies: WorkflowRunDispatcherDependencies,\n input: AutomaticWorkflowRunDispatchInput,\n run: WorkflowRunRecord\n): Promise<void> {\n const execution = await dependencies.storage.executions.getById({\n projectId: dependencies.id,\n id: run.executionId,\n })\n if (\n !execution ||\n execution.source.type !== input.source.type ||\n execution.source.eventId !== input.source.eventId ||\n execution.correlationId !== input.correlationId ||\n execution.requestedBy !== undefined\n ) {\n throw new WorkflowValidationError(\n `[Sixb] Workflow run '${run.id}' already exists with different automatic provenance.`\n )\n }\n}\n\nfunction assertNonBlank(value: string, label: string): void {\n if (!value.trim()) throw new WorkflowValidationError(`[Sixb] ${label} must not be empty.`)\n}\n",
62
+ "import type { ObjectTypeWithPropertyTokens } from \"../../ontology/tokens\"\nimport { ActionDefinitionError, effectsWithoutEditsMessage } from \"../errors\"\nimport type {\n ActionBuilder,\n ActionEditsHandler,\n ActionEffectsHandler,\n ActionParamsConfig,\n ActionValidator,\n ActionWritebackHandler,\n GlobalActionDefinition,\n GlobalActionEditsHandler,\n GlobalActionEffectsHandler,\n GlobalActionPhaseBuilder,\n GlobalActionValidator,\n GlobalActionWritebackHandler,\n ObjectActionDefinition,\n ObjectActionPhaseBuilder,\n} from \"../types\"\nimport { assertNonEmpty } from \"../validation\"\n\ntype ActionOptions = {\n description?: string\n}\n\nexport function defineAction<const TId extends string>(\n id: TId,\n options?: ActionOptions\n): ActionBuilder<TId> {\n assertNonEmpty(id, \"id\")\n\n return asPublicActionType<ActionBuilder<TId>>(createActionBuilder(id, options))\n}\n\nfunction createActionBuilder(id: string, options?: ActionOptions) {\n const builder = {\n params(params: ActionParamsConfig) {\n return createGlobalActionPhaseBuilder(id, params, options)\n },\n on(objectType: ObjectTypeWithPropertyTokens) {\n assertNonEmpty(objectType.id, \"target id\")\n return createObjectActionParamsBuilder(id, objectType, options)\n },\n }\n\n return builder\n}\n\nfunction createGlobalActionPhaseBuilder(\n id: string,\n params: ActionParamsConfig,\n options?: ActionOptions\n): GlobalActionPhaseBuilder<string, ActionParamsConfig> {\n const validators: GlobalActionValidator<Record<string, unknown>>[] = []\n\n const builder = {\n validate(validator: GlobalActionValidator<Record<string, unknown>>) {\n validators.push(validator)\n return builder\n },\n writeback(handler: GlobalActionWritebackHandler<Record<string, unknown>, unknown>) {\n return createGlobalDefinition({\n id,\n params,\n description: options?.description,\n validators,\n writeback: handler,\n })\n },\n edits(handler: GlobalActionEditsHandler<Record<string, unknown>, undefined>) {\n return createGlobalDefinition({\n id,\n params,\n description: options?.description,\n validators,\n edits: handler,\n })\n },\n }\n\n return asPublicActionType<GlobalActionPhaseBuilder<string, ActionParamsConfig>>(builder)\n}\n\nfunction createObjectActionParamsBuilder(\n id: string,\n objectType: ObjectTypeWithPropertyTokens,\n options?: ActionOptions\n) {\n return {\n params(params: ActionParamsConfig) {\n return createObjectActionPhaseBuilder(id, objectType, params, options)\n },\n }\n}\n\nfunction createObjectActionPhaseBuilder(\n id: string,\n objectType: ObjectTypeWithPropertyTokens,\n params: ActionParamsConfig,\n options?: ActionOptions\n): ObjectActionPhaseBuilder<string, ObjectTypeWithPropertyTokens, ActionParamsConfig> {\n const validators: ActionValidator<ObjectTypeWithPropertyTokens, Record<string, unknown>>[] = []\n\n const builder = {\n validate(validator: ActionValidator<ObjectTypeWithPropertyTokens, Record<string, unknown>>) {\n validators.push(validator)\n return builder\n },\n writeback(\n handler: ActionWritebackHandler<\n ObjectTypeWithPropertyTokens,\n Record<string, unknown>,\n unknown\n >\n ) {\n return createObjectDefinition({\n id,\n objectType,\n params,\n description: options?.description,\n validators,\n writeback: handler,\n })\n },\n edits(\n handler: ActionEditsHandler<ObjectTypeWithPropertyTokens, Record<string, unknown>, undefined>\n ) {\n return createObjectDefinition({\n id,\n objectType,\n params,\n description: options?.description,\n validators,\n edits: handler,\n })\n },\n }\n\n return asPublicActionType<\n ObjectActionPhaseBuilder<string, ObjectTypeWithPropertyTokens, ActionParamsConfig>\n >(builder)\n}\n\nfunction createGlobalDefinition(input: {\n readonly id: string\n readonly params: ActionParamsConfig\n readonly description?: string\n readonly validators: readonly unknown[]\n readonly writeback?: unknown\n readonly edits?: unknown\n readonly effects?: unknown\n}): GlobalActionDefinition {\n const definition = {\n kind: \"action\",\n id: input.id,\n binding: { kind: \"global\" },\n params: input.params,\n phases: {\n validate: [...input.validators],\n ...(input.writeback ? { writeback: input.writeback } : {}),\n ...(input.edits ? { edits: input.edits } : {}),\n ...(input.effects ? { effects: input.effects } : {}),\n },\n ...(input.description !== undefined ? { description: input.description } : {}),\n }\n\n return asPublicActionType<GlobalActionDefinition>(\n Object.assign(definition, {\n edits(handler: GlobalActionEditsHandler<Record<string, unknown>, unknown>) {\n return createGlobalDefinition({\n ...input,\n edits: handler,\n })\n },\n effects(handler: GlobalActionEffectsHandler<Record<string, unknown>, unknown>) {\n if (!input.edits) {\n throw new ActionDefinitionError(effectsWithoutEditsMessage(input.id))\n }\n return createGlobalDefinition({\n ...input,\n effects: handler,\n })\n },\n })\n )\n}\n\nfunction createObjectDefinition(input: {\n readonly id: string\n readonly objectType: ObjectTypeWithPropertyTokens\n readonly params: ActionParamsConfig\n readonly description?: string\n readonly validators: readonly unknown[]\n readonly writeback?: unknown\n readonly edits?: unknown\n readonly effects?: unknown\n}): ObjectActionDefinition {\n const definition = {\n kind: \"action\",\n id: input.id,\n binding: { kind: \"object\", objectType: input.objectType },\n params: input.params,\n phases: {\n validate: [...input.validators],\n ...(input.writeback ? { writeback: input.writeback } : {}),\n ...(input.edits ? { edits: input.edits } : {}),\n ...(input.effects ? { effects: input.effects } : {}),\n },\n ...(input.description !== undefined ? { description: input.description } : {}),\n }\n\n return asPublicActionType<ObjectActionDefinition>(\n Object.assign(definition, {\n edits(\n handler: ActionEditsHandler<ObjectTypeWithPropertyTokens, Record<string, unknown>, unknown>\n ) {\n return createObjectDefinition({\n ...input,\n edits: handler,\n })\n },\n effects(\n handler: ActionEffectsHandler<\n ObjectTypeWithPropertyTokens,\n Record<string, unknown>,\n unknown\n >\n ) {\n if (!input.edits) {\n throw new ActionDefinitionError(effectsWithoutEditsMessage(input.id))\n }\n return createObjectDefinition({\n ...input,\n effects: handler,\n })\n },\n })\n )\n}\n\n// Runtime builders are plain objects; public builder types carry phase-order inference.\nfunction asPublicActionType<TPublic>(value: unknown): TPublic {\n return value as TPublic\n}\n",
63
+ "import type { SchemaOrRef } from \"../../ontology\"\nimport type { QuantitativeTypeId } from \"../../ontology/units\"\nimport type { ParamConfig } from \"./types\"\n\nexport interface ParamOptions {\n readonly description?: string\n readonly semanticType?: QuantitativeTypeId\n readonly nullable?: boolean\n}\n\ntype FieldFromOptions<TOptions, TKey extends string, TFallback> =\n TOptions extends Record<TKey, infer TValue>\n ? { [K in TKey]: TValue }\n : { [K in TKey]?: TFallback }\n\ntype ParamResult<\n TSchema extends SchemaOrRef,\n TRequired extends boolean,\n TOptions extends ParamOptions | undefined,\n> = {\n schema: TSchema\n required: TRequired\n} & FieldFromOptions<TOptions, \"description\", string> &\n FieldFromOptions<TOptions, \"semanticType\", QuantitativeTypeId> &\n FieldFromOptions<TOptions, \"nullable\", boolean>\n\n/** Declare one required parameter. */\nexport function param<\n const TSchema extends SchemaOrRef,\n const TOptions extends ParamOptions | undefined = undefined,\n>(schema: TSchema, options?: TOptions): ParamResult<TSchema, true, TOptions> {\n const result: ParamConfig & { required: true } = {\n schema,\n required: true,\n ...(options?.description !== undefined ? { description: options.description } : {}),\n ...(options?.semanticType !== undefined ? { semanticType: options.semanticType } : {}),\n ...(options?.nullable !== undefined ? { nullable: options.nullable } : {}),\n }\n return result as ParamResult<TSchema, true, TOptions>\n}\n\n/** Derive an optional parameter without changing its schema or metadata. */\nexport function optional<const TParam extends ParamConfig>(\n paramConfig: TParam\n): Omit<TParam, \"required\"> & { readonly required: false } {\n return {\n ...paramConfig,\n required: false,\n }\n}\n",
64
+ "import type { ObjectType, OntologyDefinitionCatalog } from \"../ontology\"\nimport {\n ActionDefinitionError,\n effectsWithoutEditsMessage,\n missingActionMutationMessage,\n} from \"./errors\"\nimport type { ActionDefinition, ObjectActionDefinition } from \"./types\"\nimport { isObjectActionDefinition } from \"./validation\"\n\nexport interface ActionDefinitionCatalog {\n list(): readonly ActionDefinition[]\n getById(id: string): ActionDefinition | null\n listGlobal(): readonly ActionDefinition[]\n listForType(type: ObjectType): readonly ObjectActionDefinition[]\n}\n\nexport interface ActionRegistryOptions {\n readonly actions: readonly ActionDefinition[]\n readonly ontology: OntologyDefinitionCatalog\n}\n\nexport class ActionRegistry implements ActionDefinitionCatalog {\n private readonly byId = new Map<string, ActionDefinition>()\n private readonly globalActions: ActionDefinition[] = []\n private readonly byTargetId = new Map<string, ObjectActionDefinition[]>()\n\n private readonly ontology: OntologyDefinitionCatalog\n\n constructor(options: ActionRegistryOptions) {\n this.ontology = options.ontology\n\n for (const action of options.actions) {\n const previous = this.byId.get(action.id)\n if (previous) {\n const chainDuplicate = this.getInheritanceDuplicate(action, previous)\n if (chainDuplicate) {\n throw new ActionDefinitionError(\n `Duplicate action id \"${action.id}\" in inheritance chain of \"${chainDuplicate.objectTypeId}\": defined on both \"${chainDuplicate.firstTargetId}\" and \"${chainDuplicate.secondTargetId}\".`\n )\n }\n\n throw new ActionDefinitionError(\n `Duplicate action id \"${action.id}\" declared in multiple files.`\n )\n }\n\n this.validatePhases(action)\n this.byId.set(action.id, action)\n\n if (!isObjectActionDefinition(action)) {\n this.globalActions.push(action)\n continue\n }\n\n const objectType = action.binding.objectType\n const target = this.ontology.getObjectTypeById(objectType.id)\n if (!target) {\n throw new ActionDefinitionError(\n `Action \"${action.id}\" targets unknown object type \"${objectType.id}\". Add the object type to ontology before registering the action.`\n )\n }\n\n const bucket = this.byTargetId.get(objectType.id) ?? []\n bucket.push(action)\n this.byTargetId.set(objectType.id, bucket)\n }\n }\n\n private validatePhases(action: ActionDefinition): void {\n const hasWriteback = action.phases.writeback !== undefined\n const hasEdits = action.phases.edits !== undefined\n const hasEffects = action.phases.effects !== undefined\n\n if (!hasWriteback && !hasEdits) {\n throw new ActionDefinitionError(missingActionMutationMessage(action.id))\n }\n\n if (hasEffects && !hasEdits) {\n throw new ActionDefinitionError(effectsWithoutEditsMessage(action.id))\n }\n }\n\n list(): readonly ActionDefinition[] {\n return [...this.byId.values()]\n }\n\n getById(id: string): ActionDefinition | null {\n return this.byId.get(id) ?? null\n }\n\n listGlobal(): readonly ActionDefinition[] {\n return [...this.globalActions]\n }\n\n listForType(type: ObjectType): readonly ObjectActionDefinition[] {\n this.ontology.resolveObjectType(type.id)\n\n const seen = new Set<string>()\n const result: ObjectActionDefinition[] = []\n\n for (const ancestor of this.ontology.listAncestorChain(type)) {\n for (const action of this.byTargetId.get(ancestor.id) ?? []) {\n if (seen.has(action.id)) continue\n seen.add(action.id)\n result.push(action)\n }\n }\n\n return result\n }\n\n private getInheritanceDuplicate(\n action: ActionDefinition,\n previous: ActionDefinition\n ): { objectTypeId: string; firstTargetId: string; secondTargetId: string } | null {\n if (!isObjectActionDefinition(action) || !isObjectActionDefinition(previous)) {\n return null\n }\n\n const actionObjectType = action.binding.objectType\n const previousObjectType = previous.binding.objectType\n\n if (actionObjectType.id === previousObjectType.id) {\n return null\n }\n\n const actionChain = this.ontology.listAncestorChain(actionObjectType)\n if (actionChain.some((ancestor) => ancestor.id === previousObjectType.id)) {\n return {\n objectTypeId: actionObjectType.id,\n firstTargetId: previousObjectType.id,\n secondTargetId: actionObjectType.id,\n }\n }\n\n const previousChain = this.ontology.listAncestorChain(previousObjectType)\n if (previousChain.some((ancestor) => ancestor.id === actionObjectType.id)) {\n return {\n objectTypeId: previousObjectType.id,\n firstTargetId: actionObjectType.id,\n secondTargetId: previousObjectType.id,\n }\n }\n\n return null\n }\n}\n",
65
+ "import { isActionDefinition } from \"../actions\"\nimport type { AgentSkillCatalog, AgentToolCatalog } from \"../agents\"\nimport type { ModelCatalog } from \"../models\"\nimport {\n assertValidLanguageModel,\n isLanguageModelTier,\n selectLanguageModel,\n} from \"../models/catalog\"\nimport { isModelReasoning, modelReasoningSupportIssue } from \"../models/language-model\"\nimport type { SchemaOrRef, ValueType } from \"../ontology\"\nimport { validateSchemaOrRefValue } from \"../ontology/refs\"\nimport type { SandboxFactory } from \"../sandboxes\"\nimport {\n type SandboxEnvironment,\n sandboxCredentialIssue,\n staticSandboxRecipe,\n} from \"../sandboxes/configuration\"\nimport { SandboxError } from \"../sandboxes/errors\"\nimport type { ScheduleDefinition } from \"../schedules\"\nimport type { SecurityDefinitionCatalog } from \"../security\"\nimport { WorkflowDefinitionError, WorkflowValidationError } from \"./errors\"\nimport type {\n AgentStepDefinition,\n InterventionDefinition,\n InterventionFieldConfig,\n InterventionResponseConfig,\n StepDefinition,\n WorkflowActionNodeDefinition,\n WorkflowAgentNodeDefinition,\n WorkflowDefinition,\n WorkflowInterventionNodeDefinition,\n WorkflowNodeDefinition,\n WorkflowStepNodeDefinition,\n WorkflowTriggerDefinition,\n} from \"./types\"\n\nexport function assertNonEmpty(\n value: string,\n subject: \"Step\" | \"Agent step\" | \"Workflow\" | \"Intervention\",\n field: string\n): void {\n if (!value.trim()) {\n throw new WorkflowDefinitionError(`${subject} ${field} must not be empty.`)\n }\n}\n\nexport function isStepDefinition(value: unknown): value is StepDefinition {\n return (\n isRecord(value) &&\n value.kind === \"step\" &&\n typeof value.id === \"string\" &&\n isRecord(value.input) &&\n isRecord(value.output) &&\n typeof value.handler === \"function\"\n )\n}\n\nexport function isAgentStepDefinition(value: unknown): value is AgentStepDefinition {\n return (\n isRecord(value) &&\n value.kind === \"agentStep\" &&\n typeof value.id === \"string\" &&\n (value.model === undefined ||\n isLanguageModelTier(value.model) ||\n isLanguageModel(value.model)) &&\n (value.reasoning === undefined || isModelReasoning(value.reasoning)) &&\n typeof value.instructions === \"string\" &&\n isStringArray(value.groupIds) &&\n isStringArray(value.toolNames) &&\n isStringArray(value.skillNames) &&\n isRecord(value.input) &&\n isRecord(value.output) &&\n typeof value.prompt === \"function\"\n )\n}\n\nexport function isInterventionDefinition(value: unknown): value is InterventionDefinition {\n return (\n isRecord(value) &&\n value.kind === \"intervention\" &&\n typeof value.id === \"string\" &&\n isRecord(value.input) &&\n isRecord(value.response) &&\n (value.defaults === undefined || typeof value.defaults === \"function\")\n )\n}\n\nexport function isWorkflowDefinition(value: unknown): value is WorkflowDefinition {\n return (\n isRecord(value) &&\n value.kind === \"workflow\" &&\n typeof value.id === \"string\" &&\n isRecord(value.input) &&\n Array.isArray(value.triggers) &&\n Array.isArray(value.nodes)\n )\n}\n\nexport function validateWorkflowDefinition(value: unknown): asserts value is WorkflowDefinition {\n if (!isWorkflowDefinition(value)) {\n throw new WorkflowDefinitionError(\"Invalid workflow definition.\")\n }\n\n assertNonEmpty(value.id, \"Workflow\", \"id\")\n\n if (value.nodes.length === 0) {\n throw new WorkflowDefinitionError(`Workflow \"${value.id}\" must contain at least one node.`)\n }\n\n const nodeIds = new Set<string>()\n const nodeKeys = new Set<string>()\n\n for (const node of value.nodes) {\n validateWorkflowNodeDefinition(value.id, node)\n\n if (nodeIds.has(node.id)) {\n throw new WorkflowDefinitionError(\n `Duplicate workflow node id \"${node.id}\" in workflow \"${value.id}\".`\n )\n }\n nodeIds.add(node.id)\n\n if (nodeKeys.has(node.key)) {\n throw new WorkflowDefinitionError(\n `Duplicate workflow node key \"${node.key}\" in workflow \"${value.id}\".`\n )\n }\n nodeKeys.add(node.key)\n }\n}\n\nexport function validateWorkflowsAtStartup(options: {\n workflows: readonly WorkflowDefinition[]\n registeredSchedules: ReadonlyMap<string, ScheduleDefinition>\n registeredActionIds: ReadonlySet<string>\n models?: ModelCatalog\n tools: AgentToolCatalog\n skills: AgentSkillCatalog\n}): readonly WorkflowDefinition[] {\n for (const workflow of options.workflows) {\n validateWorkflowDefinition(workflow)\n\n for (const trigger of workflow.triggers) {\n validateWorkflowTriggerAtStartup(\n workflow.id,\n trigger,\n options.registeredSchedules,\n Object.keys(workflow.input)\n )\n }\n\n for (const node of workflow.nodes) {\n if (node.type === \"action\" && !options.registeredActionIds.has(node.action.id)) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflow.id}\" references unknown action \"${node.action.id}\". Add it to 'actions' in createSixb() or export it from 'actions/'.`\n )\n }\n if (node.type === \"agent\") {\n validateWorkflowAgentStepRuntimeReferences(workflow.id, node.agentStep, options)\n }\n }\n }\n\n return options.workflows\n}\n\n/** Validate workflow task memberships once the security catalog has been composed. */\nexport function validateWorkflowAgentStepGroupReferences(\n workflows: readonly WorkflowDefinition[],\n security: SecurityDefinitionCatalog\n): void {\n for (const workflow of workflows) {\n for (const node of workflow.nodes) {\n if (node.type !== \"agent\") continue\n for (const groupId of node.agentStep.groupIds) {\n if (!security.getGroupById(groupId)) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflow.id}\" agent step \"${node.id}\" references unknown group \"${groupId}\". Add it to 'security/groups/' or pass it to createSixb({ groups }).`\n )\n }\n }\n }\n }\n}\n\nfunction validateWorkflowAgentStepRuntimeReferences(\n workflowId: string,\n step: AgentStepDefinition,\n options: {\n readonly models?: ModelCatalog\n readonly tools: AgentToolCatalog\n readonly skills: AgentSkillCatalog\n }\n): void {\n if (step.model === undefined && options.models?.language === undefined) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" agent step \"${step.id}\" needs a model. Configure 'models.language' or pass 'model' to defineAgentStep().`\n )\n }\n if (typeof step.model === \"string\" && options.models?.language === undefined) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" agent step \"${step.id}\" needs a model for tier \"${step.model}\". Configure 'models.language' or pass a model to defineAgentStep().`\n )\n }\n // The step's own model runs as given, so it passes the checks a catalog model passes.\n if (step.model !== undefined && typeof step.model !== \"string\") {\n assertValidLanguageModel(\n step.model,\n (detail) =>\n new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" agent step \"${step.id}\" has an invalid language model: ${detail}.`\n )\n )\n }\n // Same rule as a catalog default: checked against the capabilities the model declares, so an\n // effort or token budget outside them fails at startup rather than on the step's first run.\n const model = selectLanguageModel(options.models?.language, step.model)\n if (step.reasoning !== undefined && model !== undefined) {\n const issue = modelReasoningSupportIssue(\n model.definition.capabilities.reasoning,\n step.reasoning\n )\n if (issue !== undefined) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" agent step \"${step.id}\" cannot use its reasoning with language model \"${model.providerId}/${model.modelId}\": ${issue}.`\n )\n }\n }\n for (const toolName of step.toolNames) {\n if (options.tools.getByName(toolName) === null) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" agent step \"${step.id}\" uses unknown project tool \"${toolName}\". Add it to 'tools' in createSixb().`\n )\n }\n }\n for (const skillName of step.skillNames) {\n if (options.skills.getByName(skillName) === null) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" agent step \"${step.id}\" uses unknown Agent Skill \"${skillName}\". Add it as 'skills/${skillName}/SKILL.md'.`\n )\n }\n }\n}\n\nexport function validateWorkflowInput(params: {\n readonly workflow: WorkflowDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): Readonly<Record<string, unknown>> {\n return validateWorkflowContractRecord({\n shape: params.workflow.input,\n value: params.value,\n path: `Workflow \"${params.workflow.id}\" input`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function validateWorkflowStepInput(params: {\n readonly workflowId: string\n readonly step: StepDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): Readonly<Record<string, unknown>> {\n return validateWorkflowContractRecord({\n shape: params.step.input,\n value: params.value,\n path: `Workflow \"${params.workflowId}\" step \"${params.step.id}\" input`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function validateWorkflowStepOutput(params: {\n readonly workflowId: string\n readonly step: StepDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): Readonly<Record<string, unknown>> {\n return validateWorkflowContractRecord({\n shape: params.step.output,\n value: params.value,\n path: `Workflow \"${params.workflowId}\" step \"${params.step.id}\" output`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function validateWorkflowInterventionInput(params: {\n readonly workflowId: string\n readonly intervention: InterventionDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): Readonly<Record<string, unknown>> {\n return validateWorkflowContractRecord({\n shape: params.intervention.input,\n value: params.value,\n path: `Workflow \"${params.workflowId}\" intervention \"${params.intervention.id}\" input`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function validateWorkflowInterventionResponse(params: {\n readonly workflowId: string\n readonly intervention: InterventionDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): Readonly<Record<string, unknown>> {\n return validateWorkflowInterventionResponseRecord({\n response: params.intervention.response,\n value: params.value,\n path: `Workflow \"${params.workflowId}\" intervention \"${params.intervention.id}\" response`,\n partial: false,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function validateWorkflowInterventionDefaultResponse(params: {\n readonly workflowId: string\n readonly intervention: InterventionDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): Readonly<Record<string, unknown>> {\n return validateWorkflowInterventionResponseRecord({\n response: params.intervention.response,\n value: params.value,\n path: `Workflow \"${params.workflowId}\" intervention \"${params.intervention.id}\" defaultResponse`,\n partial: true,\n valueTypesById: params.valueTypesById,\n })\n}\n\nfunction validateWorkflowTriggerAtStartup(\n workflowId: string,\n trigger: WorkflowTriggerDefinition,\n registeredSchedules: ReadonlyMap<string, ScheduleDefinition>,\n inputFields: readonly string[]\n): void {\n if (!isRecord(trigger) || trigger.type !== \"schedule\") {\n throw new WorkflowDefinitionError(`Workflow \"${workflowId}\" contains an unsupported trigger.`)\n }\n validateScheduleWorkflowTrigger(workflowId, trigger, registeredSchedules, inputFields)\n}\n\nfunction validateScheduleWorkflowTrigger(\n workflowId: string,\n trigger: Extract<WorkflowTriggerDefinition, { readonly type: \"schedule\" }>,\n registeredSchedules: ReadonlyMap<string, ScheduleDefinition>,\n inputFields: readonly string[]\n): void {\n if (typeof trigger.scheduleId !== \"string\" || !trigger.scheduleId.trim()) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" contains a schedule trigger with an empty schedule id.`\n )\n }\n\n const schedule = registeredSchedules.get(trigger.scheduleId)\n if (!schedule) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" references unknown schedule \"${trigger.scheduleId}\". Add it to 'schedules' in createSixb() or export it from 'schedules/'.`\n )\n }\n\n if (trigger.mapper !== undefined && typeof trigger.mapper !== \"function\") {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" schedule \"${trigger.scheduleId}\" mapper must be a function.`\n )\n }\n\n if (trigger.mapper !== undefined && schedule.trigger.type !== \"event\") {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" cron schedule \"${trigger.scheduleId}\" does not accept a mapper.`\n )\n }\n\n if (trigger.mapper === undefined && inputFields.length > 0) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" schedule \"${trigger.scheduleId}\" requires a mapper because workflow input is not empty: ${inputFields.join(\", \")}.`\n )\n }\n}\n\nfunction validateWorkflowNodeDefinition(workflowId: string, node: WorkflowNodeDefinition): void {\n if (!isRecord(node)) {\n throw new WorkflowDefinitionError(`Workflow \"${workflowId}\" contains an invalid node.`)\n }\n\n if (node.type === \"step\") {\n validateStepNodeDefinition(workflowId, node)\n return\n }\n\n if (node.type === \"agent\") {\n validateAgentNodeDefinition(workflowId, node)\n return\n }\n\n if (node.type === \"intervention\") {\n validateInterventionNodeDefinition(workflowId, node)\n return\n }\n\n if (node.type === \"action\") {\n validateActionNodeDefinition(workflowId, node)\n return\n }\n\n throw new WorkflowDefinitionError(`Workflow \"${workflowId}\" contains an unsupported node type.`)\n}\n\nfunction validateAgentNodeDefinition(workflowId: string, node: WorkflowAgentNodeDefinition): void {\n if (typeof node.id !== \"string\" || !node.id.trim()) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" contains an agent step with an empty id.`\n )\n }\n if (typeof node.key !== \"string\" || !node.key.trim()) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" contains agent step \"${node.id}\" with an empty derived key.`\n )\n }\n if (!isAgentStepDefinition(node.agentStep)) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" contains an invalid agent node \"${node.id}\".`\n )\n }\n if (node.id !== node.agentStep.id) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" agent node id \"${node.id}\" does not match agent step definition id \"${node.agentStep.id}\".`\n )\n }\n if (!node.agentStep.instructions.trim()) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" agent step \"${node.id}\" instructions must not be empty.`\n )\n }\n assertUniqueNonEmptyAgentStepValues(workflowId, node.id, \"group\", node.agentStep.groupIds)\n assertUniqueNonEmptyAgentStepValues(workflowId, node.id, \"tool\", node.agentStep.toolNames)\n assertUniqueNonEmptyAgentStepValues(workflowId, node.id, \"skill\", node.agentStep.skillNames)\n\n // A hand-built node skips defineAgentStep, so its sandbox is checked again here.\n if (node.agentStep.sandbox !== undefined) {\n assertAgentStepSandbox(\n node.agentStep.sandbox,\n `Workflow \"${workflowId}\" agent step \"${node.id}\"`\n )\n }\n\n if (node.mapper !== undefined && typeof node.mapper !== \"function\") {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" agent node \"${node.id}\" mapper must be a function.`\n )\n }\n}\n\n/**\n * Reject a value that cannot be an Agent step's sandbox; `step` names it in the error. A step has\n * no thread to bind params to, so only a static recipe applies. Its network must let the agent\n * reach the Sixb API. Its source access must pass the rule a project factory passes at startup.\n */\nexport function assertAgentStepSandbox(\n value: unknown,\n step: string\n): asserts value is SandboxFactory {\n const fail = (issue: string, cause?: unknown): never => {\n throw new WorkflowDefinitionError(\n `${step} sandbox ${issue}`,\n cause === undefined ? undefined : { cause }\n )\n }\n\n if (!isRecord(value) || typeof value.create !== \"function\") {\n return fail(\"must be a sandbox factory with a create function.\")\n }\n\n const { configuration } = value\n if (configuration === undefined) return\n if (!isRecord(configuration)) return fail(\"configuration must be a sandbox recipe object.\")\n if (configuration.params !== undefined || configuration.resolve !== undefined) {\n return fail(\"must use a static recipe: params and resolve are not supported in workflow steps.\")\n }\n\n let recipe: SandboxEnvironment\n try {\n recipe = staticSandboxRecipe(configuration)\n } catch (error) {\n if (!(error instanceof SandboxError)) throw error\n // Recipe validation names the invalid field, never its value.\n return fail(`recipe is invalid: ${error.message.replace(/^\\[Sixb\\] /, \"\")}`, error)\n }\n\n // Sixb adds its API to every other policy when the step runs, so only none cannot reach it.\n if (recipe.network?.mode === \"none\") {\n return fail(\n 'network mode \"none\" cannot run an agent: the agent needs the Sixb API. Use { mode: \"restricted\", allow: [...] } with the origins the project needs; Sixb adds its own.'\n )\n }\n\n const { auth } = configuration\n if (auth !== undefined && !(isRecord(auth) && typeof auth.authorize === \"function\")) {\n return fail(\"auth requires an authorize function.\")\n }\n\n const credentialIssue = sandboxCredentialIssue({\n supportsRequestCredentials: value.supportsRequestCredentials === true,\n auth,\n source: recipe.source,\n })\n if (credentialIssue) fail(`is invalid: ${credentialIssue}`)\n}\n\nfunction assertUniqueNonEmptyAgentStepValues(\n workflowId: string,\n stepId: string,\n kind: \"group\" | \"tool\" | \"skill\",\n values: readonly string[]\n): void {\n const seen = new Set<string>()\n for (const value of values) {\n if (!value.trim()) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" agent step \"${stepId}\" has an empty ${kind} id.`\n )\n }\n if (seen.has(value)) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" agent step \"${stepId}\" has duplicate ${kind} '${value}'.`\n )\n }\n seen.add(value)\n }\n}\n\nfunction isLanguageModel(value: unknown): boolean {\n return (typeof value === \"object\" || typeof value === \"function\") && value !== null\n}\n\nfunction isStringArray(value: unknown): value is readonly string[] {\n if (!Array.isArray(value)) return false\n for (let index = 0; index < value.length; index += 1) {\n if (!Object.hasOwn(value, index) || typeof value[index] !== \"string\") return false\n }\n return true\n}\n\nexport function validateWorkflowAgentStepInput(params: {\n readonly workflowId: string\n readonly agentStep: AgentStepDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): Readonly<Record<string, unknown>> {\n return validateWorkflowContractRecord({\n shape: params.agentStep.input,\n value: params.value,\n path: `Workflow \"${params.workflowId}\" agent step \"${params.agentStep.id}\" input`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function validateWorkflowAgentStepOutput(params: {\n readonly workflowId: string\n readonly agentStep: AgentStepDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): Readonly<Record<string, unknown>> {\n return validateWorkflowContractRecord({\n shape: params.agentStep.output,\n value: params.value,\n path: `Workflow \"${params.workflowId}\" agent step \"${params.agentStep.id}\" output`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nfunction validateStepNodeDefinition(workflowId: string, node: WorkflowStepNodeDefinition): void {\n if (typeof node.id !== \"string\" || !node.id.trim()) {\n throw new WorkflowDefinitionError(`Workflow \"${workflowId}\" contains a step with an empty id.`)\n }\n\n if (typeof node.key !== \"string\" || !node.key.trim()) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" contains step \"${node.id}\" with an empty derived key.`\n )\n }\n\n if (!isStepDefinition(node.step)) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" contains an invalid step node \"${node.id}\".`\n )\n }\n\n if (node.id !== node.step.id) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" step node id \"${node.id}\" does not match step definition id \"${node.step.id}\".`\n )\n }\n\n if (node.mapper !== undefined && typeof node.mapper !== \"function\") {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" step node \"${node.id}\" mapper must be a function.`\n )\n }\n}\n\nfunction validateInterventionNodeDefinition(\n workflowId: string,\n node: WorkflowInterventionNodeDefinition\n): void {\n if (typeof node.id !== \"string\" || !node.id.trim()) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" contains an intervention with an empty id.`\n )\n }\n\n if (typeof node.key !== \"string\" || !node.key.trim()) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" contains intervention \"${node.id}\" with an empty derived key.`\n )\n }\n\n if (!isInterventionDefinition(node.intervention)) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" contains an invalid intervention node \"${node.id}\".`\n )\n }\n\n if (node.id !== node.intervention.id) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" intervention node id \"${node.id}\" does not match intervention definition id \"${node.intervention.id}\".`\n )\n }\n\n if (node.mapper !== undefined && typeof node.mapper !== \"function\") {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" intervention node \"${node.id}\" mapper must be a function.`\n )\n }\n}\n\nfunction validateActionNodeDefinition(\n workflowId: string,\n node: WorkflowActionNodeDefinition\n): void {\n if (typeof node.id !== \"string\" || !node.id.trim()) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" contains an action with an empty id.`\n )\n }\n\n if (typeof node.key !== \"string\" || !node.key.trim()) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" contains action \"${node.id}\" with an empty derived key.`\n )\n }\n\n if (!isActionDefinition(node.action)) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" contains an invalid action node \"${node.id}\".`\n )\n }\n\n if (node.id !== node.action.id) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" action node id \"${node.id}\" does not match action definition id \"${node.action.id}\".`\n )\n }\n\n if (node.mapper !== undefined && typeof node.mapper !== \"function\") {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" action node \"${node.id}\" mapper must be a function.`\n )\n }\n}\n\nfunction validateWorkflowContractRecord(params: {\n readonly shape: Readonly<Record<string, unknown>>\n readonly value: unknown\n readonly path: string\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): Readonly<Record<string, unknown>> {\n if (!isRecord(params.value)) {\n throw new WorkflowValidationError(`[Sixb] ${params.path} must be an object`)\n }\n\n const fieldIds = new Set(Object.keys(params.shape))\n for (const fieldId of Object.keys(params.value)) {\n if (!fieldIds.has(fieldId)) {\n throw new WorkflowValidationError(`[Sixb] Unknown field '${params.path}.${fieldId}'`)\n }\n }\n\n for (const [fieldId, schema] of Object.entries(params.shape)) {\n const fieldValue = params.value[fieldId]\n if (fieldValue === undefined) {\n throw new WorkflowValidationError(`[Sixb] Missing required field '${params.path}.${fieldId}'`)\n }\n\n try {\n validateSchemaOrRefValue(\n schema as SchemaOrRef,\n fieldValue,\n `${params.path}.${fieldId}`,\n params.valueTypesById\n )\n } catch (error) {\n throw toWorkflowValidationError(error)\n }\n }\n\n return params.value\n}\n\nfunction validateWorkflowInterventionResponseRecord(params: {\n readonly response: InterventionResponseConfig\n readonly value: unknown\n readonly path: string\n readonly partial: boolean\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): Readonly<Record<string, unknown>> {\n if (!isRecord(params.value)) {\n throw new WorkflowValidationError(`[Sixb] ${params.path} must be an object`)\n }\n\n const fieldIds = new Set(Object.keys(params.response))\n for (const fieldId of Object.keys(params.value)) {\n if (!fieldIds.has(fieldId)) {\n throw new WorkflowValidationError(`[Sixb] Unknown field '${params.path}.${fieldId}'`)\n }\n }\n\n for (const [fieldId, field] of Object.entries(params.response)) {\n const fieldValue = params.value[fieldId]\n if (fieldValue === undefined) {\n if (!params.partial && isInterventionResponseFieldRequired(field)) {\n throw new WorkflowValidationError(\n `[Sixb] Missing required field '${params.path}.${fieldId}'`\n )\n }\n continue\n }\n\n try {\n validateSchemaOrRefValue(\n interventionResponseFieldSchema(field),\n fieldValue,\n `${params.path}.${fieldId}`,\n params.valueTypesById\n )\n } catch (error) {\n throw toWorkflowValidationError(error)\n }\n }\n\n return params.value\n}\n\nexport function isInterventionFieldConfig(value: unknown): value is InterventionFieldConfig {\n return isRecord(value) && \"schema\" in value\n}\n\nexport function interventionResponseFieldSchema(field: unknown): SchemaOrRef {\n return (isInterventionFieldConfig(field) ? field.schema : field) as SchemaOrRef\n}\n\nexport function isInterventionResponseFieldRequired(field: unknown): boolean {\n return !isInterventionFieldConfig(field) || field.required !== false\n}\n\nfunction toWorkflowValidationError(error: unknown): WorkflowValidationError {\n if (error instanceof WorkflowValidationError) {\n return error\n }\n\n if (error instanceof Error) {\n return new WorkflowValidationError(error.message, { cause: error })\n }\n\n return new WorkflowValidationError(String(error), { cause: error })\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n",
66
+ "import type { ActionSubject } from \"../actions\"\nimport { isPlainRecord, type JsonValue } from \"../json\"\nimport { isObjectRefSchema, type Schema, type SchemaOrRef, type ValueType } from \"../ontology\"\nimport { WorkflowValidationError } from \"./errors\"\nimport type {\n AgentStepDefinition,\n InterventionDefinition,\n InterventionResponseConfig,\n StepDefinition,\n WorkflowDefinition,\n WorkflowIOSnapshot,\n} from \"./types\"\nimport {\n interventionResponseFieldSchema,\n validateWorkflowAgentStepInput,\n validateWorkflowAgentStepOutput,\n validateWorkflowInput,\n validateWorkflowInterventionDefaultResponse,\n validateWorkflowInterventionInput,\n validateWorkflowInterventionResponse,\n validateWorkflowStepInput,\n validateWorkflowStepOutput,\n} from \"./validation\"\n\nexport function snapshotWorkflowAgentStepInput(params: {\n readonly workflowId: string\n readonly agentStep: AgentStepDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): WorkflowIOSnapshot {\n const value = validateWorkflowAgentStepInput(params)\n return snapshotWorkflowContractRecord({\n shape: params.agentStep.input as Readonly<Record<string, SchemaOrRef>>,\n value,\n path: `Workflow \"${params.workflowId}\" agent step \"${params.agentStep.id}\" input`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function snapshotWorkflowAgentStepOutput(params: {\n readonly workflowId: string\n readonly agentStep: AgentStepDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): WorkflowIOSnapshot {\n const value = validateWorkflowAgentStepOutput(params)\n return snapshotWorkflowContractRecord({\n shape: params.agentStep.output as Readonly<Record<string, SchemaOrRef>>,\n value,\n path: `Workflow \"${params.workflowId}\" agent step \"${params.agentStep.id}\" output`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function snapshotWorkflowInput(params: {\n readonly workflow: WorkflowDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): WorkflowIOSnapshot {\n const value = validateWorkflowInput(params)\n return snapshotWorkflowContractRecord({\n shape: params.workflow.input as Readonly<Record<string, SchemaOrRef>>,\n value,\n path: `Workflow \"${params.workflow.id}\" input`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function snapshotWorkflowStepInput(params: {\n readonly workflowId: string\n readonly step: StepDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): WorkflowIOSnapshot {\n const value = validateWorkflowStepInput(params)\n return snapshotWorkflowContractRecord({\n shape: params.step.input as Readonly<Record<string, SchemaOrRef>>,\n value,\n path: `Workflow \"${params.workflowId}\" step \"${params.step.id}\" input`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function snapshotWorkflowStepOutput(params: {\n readonly workflowId: string\n readonly step: StepDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): WorkflowIOSnapshot {\n const value = validateWorkflowStepOutput(params)\n return snapshotWorkflowContractRecord({\n shape: params.step.output as Readonly<Record<string, SchemaOrRef>>,\n value,\n path: `Workflow \"${params.workflowId}\" step \"${params.step.id}\" output`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function snapshotWorkflowInterventionInput(params: {\n readonly workflowId: string\n readonly intervention: InterventionDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): WorkflowIOSnapshot {\n const value = validateWorkflowInterventionInput(params)\n return snapshotWorkflowContractRecord({\n shape: params.intervention.input as Readonly<Record<string, SchemaOrRef>>,\n value,\n path: `Workflow \"${params.workflowId}\" intervention \"${params.intervention.id}\" input`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function snapshotWorkflowInterventionResponse(params: {\n readonly workflowId: string\n readonly intervention: InterventionDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): WorkflowIOSnapshot {\n const value = validateWorkflowInterventionResponse(params)\n return snapshotWorkflowInterventionResponseRecord({\n response: params.intervention.response,\n value,\n path: `Workflow \"${params.workflowId}\" intervention \"${params.intervention.id}\" response`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function snapshotWorkflowInterventionDefaultResponse(params: {\n readonly workflowId: string\n readonly intervention: InterventionDefinition\n readonly value: unknown\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): WorkflowIOSnapshot {\n const value = validateWorkflowInterventionDefaultResponse(params)\n return snapshotWorkflowInterventionResponseRecord({\n response: params.intervention.response,\n value,\n path: `Workflow \"${params.workflowId}\" intervention \"${params.intervention.id}\" defaultResponse`,\n valueTypesById: params.valueTypesById,\n })\n}\n\nexport function snapshotWorkflowActionInput(params: {\n readonly subject?: ActionSubject\n readonly params: Readonly<Record<string, unknown>>\n}): WorkflowIOSnapshot {\n const snapshot: Record<string, JsonValue> = {\n params: snapshotJsonValue(params.params, \"Workflow action params\"),\n }\n\n if (params.subject && params.subject.kind !== \"none\") {\n snapshot.subject = snapshotJsonValue(params.subject, \"Workflow action subject\")\n }\n\n return snapshot\n}\n\nfunction snapshotWorkflowContractRecord(params: {\n readonly shape: Readonly<Record<string, SchemaOrRef>>\n readonly value: Readonly<Record<string, unknown>>\n readonly path: string\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): WorkflowIOSnapshot {\n const snapshot: Record<string, JsonValue> = {}\n\n for (const [fieldId, schema] of Object.entries(params.shape)) {\n snapshot[fieldId] = snapshotSchemaOrRefValue({\n schema,\n value: params.value[fieldId],\n path: `${params.path}.${fieldId}`,\n valueTypesById: params.valueTypesById,\n })\n }\n\n return snapshot\n}\n\nfunction snapshotWorkflowInterventionResponseRecord(params: {\n readonly response: InterventionResponseConfig\n readonly value: Readonly<Record<string, unknown>>\n readonly path: string\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): WorkflowIOSnapshot {\n const snapshot: Record<string, JsonValue> = {}\n\n for (const [fieldId, value] of Object.entries(params.value)) {\n if (value === undefined) {\n continue\n }\n\n snapshot[fieldId] = snapshotSchemaOrRefValue({\n schema: interventionResponseFieldSchema(params.response[fieldId]),\n value,\n path: `${params.path}.${fieldId}`,\n valueTypesById: params.valueTypesById,\n })\n }\n\n return snapshot\n}\n\nfunction snapshotSchemaOrRefValue(params: {\n readonly schema: SchemaOrRef\n readonly value: unknown\n readonly path: string\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): JsonValue {\n if (isObjectRefSchema(params.schema)) {\n if (!isRecord(params.value)) {\n throw cannotSerialize(params.path)\n }\n\n return {\n objectTypeId: String(params.value.objectTypeId),\n primaryId: String(params.value.primaryId),\n }\n }\n\n return snapshotSchemaValue({\n schema: params.schema,\n value: params.value,\n path: params.path,\n valueTypesById: params.valueTypesById,\n })\n}\n\nfunction snapshotSchemaValue(params: {\n readonly schema: Schema\n readonly value: unknown\n readonly path: string\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): JsonValue {\n const { schema, value, path, valueTypesById } = params\n\n if (typeof schema === \"string\") {\n switch (schema) {\n case \"date\":\n case \"timestamp\":\n return value instanceof Date ? snapshotDate(value, path) : snapshotJsonValue(value, path)\n case \"string\":\n case \"uuid\":\n case \"integer\":\n case \"double\":\n case \"decimal\":\n case \"boolean\":\n case \"fileRef\":\n case \"userRef\":\n return snapshotJsonValue(value, path)\n default:\n schema satisfies never\n return snapshotJsonValue(value, path)\n }\n }\n\n if (schema.type === \"enum\") {\n return snapshotJsonValue(value, path)\n }\n\n if (schema.type === \"array\") {\n if (!Array.isArray(value)) {\n throw cannotSerialize(path)\n }\n\n return value.map((item, index) =>\n snapshotSchemaValue({\n schema: schema.items,\n value: item,\n path: `${path}[${index}]`,\n valueTypesById,\n })\n )\n }\n\n if (schema.type === \"map\") {\n if (!isRecord(value)) {\n throw cannotSerialize(path)\n }\n\n const snapshot: Record<string, JsonValue> = {}\n for (const [key, entry] of Object.entries(value)) {\n snapshot[key] = snapshotSchemaValue({\n schema: schema.valueSchema,\n value: entry,\n path: `${path}.${key}`,\n valueTypesById,\n })\n }\n return snapshot\n }\n\n if (schema.type === \"object\") {\n if (!isRecord(value)) {\n throw cannotSerialize(path)\n }\n\n const snapshot: Record<string, JsonValue> = {}\n for (const [fieldId, field] of Object.entries(schema.properties)) {\n const fieldValue = value[fieldId]\n if (fieldValue === undefined) {\n continue\n }\n\n if (fieldValue === null) {\n snapshot[fieldId] = null\n continue\n }\n\n snapshot[fieldId] = snapshotSchemaValue({\n schema: field.schema,\n value: fieldValue,\n path: `${path}.${fieldId}`,\n valueTypesById,\n })\n }\n return snapshot\n }\n\n if (schema.type === \"valueTypeRef\") {\n const valueType = valueTypesById.get(schema.valueTypeId)\n if (!valueType) {\n throw new WorkflowValidationError(\n `[Sixb] Unknown valueTypeRef '${schema.valueTypeId}' at ${path}`\n )\n }\n\n return snapshotSchemaValue({\n schema: valueType.schema,\n value,\n path,\n valueTypesById,\n })\n }\n\n return snapshotJsonValue(value, path)\n}\n\nfunction snapshotJsonValue(value: unknown, path: string): JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n return value\n }\n\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw cannotSerialize(path)\n }\n return value\n }\n\n if (value instanceof Date) {\n return snapshotDate(value, path)\n }\n\n if (Array.isArray(value)) {\n return value.map((item, index) => snapshotJsonValue(item, `${path}[${index}]`))\n }\n\n if (isPlainRecord(value)) {\n const snapshot: Record<string, JsonValue> = {}\n for (const [key, entry] of Object.entries(value)) {\n snapshot[key] = snapshotJsonValue(entry, `${path}.${key}`)\n }\n return snapshot\n }\n\n throw cannotSerialize(path)\n}\n\nfunction snapshotDate(value: Date, path: string): string {\n if (Number.isNaN(value.getTime())) {\n throw cannotSerialize(path)\n }\n\n return value.toISOString()\n}\n\nfunction cannotSerialize(path: string): WorkflowValidationError {\n return new WorkflowValidationError(`[Sixb] ${path} cannot be serialized as workflow IO`)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n",
67
+ "import { assertAuthorized } from \"../authorization\"\nimport { resolveExecutionScopeAuthorization } from \"../execution/authorization\"\nimport {\n createPrimitiveExecutionRecord,\n ensureExecutionRecord,\n executionRecordInputFromRuntime,\n} from \"../execution/durable\"\nimport type { ExecutionContext } from \"../execution/types\"\nimport { assertValidFileRefs } from \"../ontology/validation\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport { dispatchWorkflowRun } from \"./run-dispatch\"\nimport { snapshotWorkflowInput } from \"./snapshot\"\nimport type { WorkflowDefinition, WorkflowIOSnapshot, WorkflowRunSource } from \"./types\"\n\nexport interface WorkflowRunRequestOptions {\n readonly input?: Readonly<Record<string, unknown>>\n readonly runId?: string\n readonly source?: WorkflowRunSource\n}\n\nexport interface RequestWorkflowRunInput extends WorkflowRunRequestOptions {\n readonly workflowId: string\n}\n\nexport interface WorkflowRunRequestResult {\n readonly workflowId: string\n readonly runId: string\n readonly queuedAt: string\n readonly jobId?: string\n /**\n * `false` when a deterministic `runId` already existed for the same workflow,\n * so no second queue job was enqueued.\n */\n readonly created: boolean\n}\n\n/**\n * Validate, snapshot, persist, queue, and announce a workflow run request.\n *\n * Operates on an already-resolved workflow definition and the shared runtime\n * context, so it stays decoupled from how workflows are registered or looked up.\n */\nexport async function requestWorkflowRun(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n workflow: WorkflowDefinition,\n options: WorkflowRunRequestOptions = {}\n): Promise<WorkflowRunRequestResult> {\n admitWorkflowRequest(runtime, execution, workflow, options.input)\n return dispatchWorkflowRun({\n errorReporterHost: runtime,\n projectId: runtime.projectId,\n workflow,\n valueTypesById: runtime.ontology.getValueTypesById(),\n storage: runtime.storage,\n queue: runtime.queues.workflows,\n events: runtime.events,\n runId: options.runId,\n input: options.input,\n source: options.source,\n createExecution: async (executionId, runId) => {\n const caller = await ensureExecutionRecord(\n runtime.storage.executions,\n executionRecordInputFromRuntime({\n execution,\n runtimeAuthorization: runtime.runtimeAuthorization,\n })\n )\n return createPrimitiveExecutionRecord({\n id: executionId,\n primitive: { kind: \"workflow\", id: workflow.id, runId },\n origin: { type: \"execution\", parent: caller },\n })\n },\n })\n}\n\n/** A workflow start as it would run: authorized, with its input as the run would snapshot it. */\nexport interface PreparedWorkflowRequest {\n readonly workflowId: string\n readonly input: WorkflowIOSnapshot\n}\n\n/**\n * Admit a workflow start without starting it: the checks `requestWorkflowRun` applies, and the\n * input snapshot the run would store. The agent API gateway prepares the starts it holds for\n * approval.\n */\nexport function prepareWorkflowRequest(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n workflow: WorkflowDefinition,\n input: Readonly<Record<string, unknown>> = {}\n): PreparedWorkflowRequest {\n admitWorkflowRequest(runtime, execution, workflow, input)\n return {\n workflowId: workflow.id,\n input: snapshotWorkflowInput({\n workflow,\n value: input,\n valueTypesById: runtime.ontology.getValueTypesById(),\n }),\n }\n}\n\nfunction admitWorkflowRequest(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n workflow: WorkflowDefinition,\n input: Readonly<Record<string, unknown>> | undefined\n): void {\n resolveExecutionScopeAuthorization(runtime.projectId, {\n execution,\n authorization: runtime.runtimeAuthorization,\n })\n assertAuthorized(runtime, { kind: \"workflow.run\", workflowId: workflow.id })\n // Only caller input: automatic runs carry stored data, which may predate the rule.\n assertValidFileRefs(input, `Workflow \"${workflow.id}\" input`)\n}\n",
68
+ "import { type PreparedActionRequest, prepareActionRequest } from \"../actions/request\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport { WorkflowValidationError } from \"../workflows/errors\"\nimport { type PreparedWorkflowRequest, prepareWorkflowRequest } from \"../workflows/request\"\nimport type { WorkflowDefinition } from \"../workflows/types\"\nimport type { ExecutionContext } from \"./types\"\n\nexport interface ActionRequestToPrepare {\n readonly actionId: string\n readonly subject?: PreparedActionRequest[\"subject\"]\n readonly params?: Record<string, unknown>\n}\n\nexport interface WorkflowRequestToPrepare {\n readonly workflowId: string\n readonly input?: Readonly<Record<string, unknown>>\n}\n\n/** Admit a request with a bound SDK's authority, as it would run, without running it. */\ninterface RequestPreparation {\n action(input: ActionRequestToPrepare): Promise<PreparedActionRequest>\n workflow(input: WorkflowRequestToPrepare): PreparedWorkflowRequest\n}\n\nconst preparationKey = Symbol(\"sixb.requestPreparation\")\n\ninterface PreparationOwner {\n readonly [preparationKey]?: RequestPreparation\n}\n\n/** Let infrastructure prepare requests with a bound SDK's authority. */\nexport function registerRequestPreparation(\n owner: object,\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n workflows: { getById(workflowId: string): WorkflowDefinition | null }\n): void {\n const preparation: RequestPreparation = {\n action: (input) => prepareActionRequest(runtime, execution, input),\n workflow: (input) => {\n const workflow = workflows.getById(input.workflowId)\n if (!workflow) {\n throw new WorkflowValidationError(`[Sixb] Unknown workflow '${input.workflowId}'`)\n }\n return prepareWorkflowRequest(runtime, execution, workflow, input.input)\n },\n }\n Object.defineProperty(owner, preparationKey, {\n configurable: false,\n enumerable: false,\n value: preparation,\n writable: false,\n })\n}\n\n/** Admit an Action request as `sixb.actions.request` would, and return it normalized. */\nexport function prepareBoundActionRequest(\n sixb: object,\n input: ActionRequestToPrepare\n): Promise<PreparedActionRequest> {\n return requirePreparation(sixb).action(input)\n}\n\n/** Admit a workflow start as `sixb.workflows.requestById` would, and return its input snapshot. */\nexport function prepareBoundWorkflowRequest(\n sixb: object,\n input: WorkflowRequestToPrepare\n): PreparedWorkflowRequest {\n return requirePreparation(sixb).workflow(input)\n}\n\nfunction requirePreparation(sixb: object): RequestPreparation {\n const preparation = (sixb as PreparationOwner)[preparationKey]\n if (!preparation) {\n throw new Error(\"[Sixb] Request preparation is not registered for this execution.\")\n }\n return preparation\n}\n",
69
+ "import { assertAuthorized } from \"../authorization\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type { LoggingService, LogsPage, LogsReadInput, LogsTailInput } from \"./service\"\n\nexport interface LogsRuntime {\n assertObservable(): void\n read(input?: LogsReadInput): Promise<LogsPage>\n tail(input?: LogsTailInput): Promise<LogsPage>\n}\n\nexport function createLogsRuntime(\n runtime: SixbRuntimeContext,\n source: LoggingService\n): LogsRuntime {\n const assertObservable = () => assertAuthorized(runtime, { kind: \"logs.observe\" })\n\n return {\n assertObservable,\n read: (input) => {\n assertObservable()\n return source.read(input)\n },\n tail: (input) => {\n assertObservable()\n return source.tail(input)\n },\n }\n}\n",
70
+ "import { randomUUID } from \"node:crypto\"\nimport { assertAuthorized, assertModelAccess } from \"../../authorization\"\nimport type { ExecutionContext } from \"../../execution\"\nimport { cloneJsonValue } from \"../../json\"\nimport type { SixbRuntimeContext } from \"../../runtime/types\"\nimport type { ModelCatalog } from \"../catalog\"\nimport { AI_MODEL_CALL_OUTPUT_TOKEN_ALLOWANCE } from \"../execution/model-call-admission\"\nimport type { AiModelCallRecorder } from \"../execution/model-call-recorder\"\nimport type { ModelExecutionSession } from \"../execution/session\"\nimport { estimateModelCall } from \"../pricing\"\nimport { DecisionModelResponseError } from \"./errors\"\nimport type {\n DecisionAnswers,\n DecisionModel,\n DecisionModelRequest,\n DecisionModelResponseMetadata,\n DecisionModelResult,\n DecisionModelsRuntime,\n} from \"./types\"\nimport {\n assertDecisionContent,\n assertDecisionModel,\n assertDecisionQuestions,\n assertDecisionSupport,\n validateDecisionAnswers,\n} from \"./validation\"\n\n/**\n * Who may ask: code and the API need `can.run(project.models)`; the Agent asks on a turn's behalf,\n * which running the Agent authorizes.\n */\nexport type DecisionAccess = \"models\" | \"agent.run\"\n\nexport function createDecisionRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n catalog: ModelCatalog | undefined,\n session: ModelExecutionSession,\n access: DecisionAccess\n): DecisionModelsRuntime {\n function assertAccess(): void {\n if (access === \"agent.run\") assertAuthorized(runtime, { kind: \"agent.run\" })\n else assertModelAccess(runtime, execution, \"models.decision.evaluate\")\n }\n\n return {\n async evaluate(input) {\n assertAccess()\n assertDecisionContent(input.input, \"input\")\n assertDecisionQuestions(input.questions)\n\n // Snapshot before the first await; caller edits cannot change an admitted request.\n const state = cloneJsonValue(input.input)\n assertDecisionContent(state, \"input\")\n const questions = structuredClone(input.questions)\n const signal = session.signal(input.signal)\n signal.throwIfAborted()\n\n const binding = resolveDecisionModel(catalog, input.model)\n assertDecisionModel(binding)\n assertDecisionSupport(binding, questions)\n\n const accounting = await session.accounting()\n accounting.assertHealthy()\n signal.throwIfAborted()\n const model = binding.resolve ? await binding.resolve() : binding\n assertDecisionModel(model)\n if (model.providerId !== binding.providerId || model.modelId !== binding.modelId) {\n throw new TypeError(\n \"[SixbModels] Resolved decision model identity does not match the selected model.\"\n )\n }\n assertDecisionSupport(model, questions)\n signal.throwIfAborted()\n const request = { input: state, questions, signal }\n const callId = await admitDecisionCall(accounting, model, request)\n\n let result: DecisionModelResult\n try {\n signal.throwIfAborted()\n result = await model.evaluate(request)\n } catch (error) {\n const metadata = error instanceof DecisionModelResponseError ? error.metadata : {}\n await recordDecision(accounting, model, callId, metadata)\n throw error\n }\n\n // Account before validation or cancellation can reject a billable response.\n const event = await recordDecision(accounting, model, callId, result ?? {})\n signal.throwIfAborted()\n\n let output: DecisionAnswers<typeof input.questions>\n try {\n output = validateDecisionAnswers(\n questions,\n result?.output,\n model.definition.capabilities.answerDecimalPlaces\n )\n } catch (cause) {\n throw new DecisionModelResponseError(\n \"[SixbModels] Invalid decision response.\",\n model.providerId,\n model.modelId,\n result ?? {},\n { cause }\n )\n }\n\n return {\n output,\n callId,\n ...(event.responseModelId === undefined ? {} : { responseModelId: event.responseModelId }),\n usage: event.usage,\n cost: event.cost,\n }\n },\n }\n}\n\nfunction resolveDecisionModel(\n catalog: ModelCatalog | undefined,\n requested: DecisionModel | undefined\n): DecisionModel {\n // A model the caller passes runs as given, listed or not; the catalog supplies the default.\n const selected = requested ?? catalog?.decision?.default.model\n if (!selected) {\n throw new Error(\"[SixbModels] Configure models.decision or supply a model to evaluate().\")\n }\n\n return selected\n}\n\nasync function admitDecisionCall(\n accounting: AiModelCallRecorder,\n model: DecisionModel,\n request: DecisionModelRequest\n): Promise<string> {\n const callId = `call_${randomUUID()}`\n const serialized = JSON.stringify({ input: request.input, questions: request.questions })\n const tokens = Math.ceil(new TextEncoder().encode(serialized).byteLength / 4)\n\n // Reservation estimate only; neither an exact context check nor an enforced output cap.\n const outputTokenAllowance = AI_MODEL_CALL_OUTPUT_TOKEN_ALLOWANCE\n await accounting.admitCall({\n callId,\n providerId: model.providerId,\n modelId: model.modelId,\n costEstimator: model.costEstimator,\n inputTokens: { status: \"estimated\", tokens, method: \"utf8BytesDividedByFour\" },\n outputTokenAllowance,\n estimatedTotalTokens: tokens + outputTokenAllowance,\n })\n\n return callId\n}\n\nasync function recordDecision(\n accounting: AiModelCallRecorder,\n model: DecisionModel,\n callId: string,\n metadata: DecisionModelResponseMetadata\n) {\n const usage = metadata.usage ?? {}\n const estimate = estimateModelCall(model, {\n usage,\n route: metadata.route,\n responseModelId: metadata.responseModelId,\n })\n const event = {\n callId,\n modelKind: \"decision\" as const,\n providerId: model.providerId,\n modelId: model.modelId,\n responseId: metadata.providerIds?.responseId ?? callId,\n responseModelId: metadata.responseModelId,\n providerIds: metadata.providerIds,\n usage,\n cost: metadata.reportedCost\n ? { status: \"reported\" as const, ...metadata.reportedCost }\n : estimate,\n ...(metadata.reportedCost ? { estimate } : {}),\n route: metadata.route,\n }\n\n await accounting.onModelCallEnd(event)\n return event\n}\n",
71
+ "import { randomUUID } from \"node:crypto\"\nimport {\n assertJsonObject,\n assertJsonValue,\n isJsonValue,\n isPlainRecord,\n type JsonValue,\n} from \"../json\"\nimport { ModelProviderError, ModelStreamError, StructuredOutputError } from \"../models/errors\"\nimport type {\n LanguageModelStreamEvent,\n ModelCallEndEvent,\n ModelFinishReason,\n ModelStep,\n ModelUiChunk,\n ModelUsage,\n} from \"../models/events\"\nimport type {\n LanguageModel,\n ModelReasoning,\n ModelToolSpecification,\n} from \"../models/language-model\"\nimport type {\n ModelAssistantPart,\n ModelMessage,\n ModelProviderStatePart,\n ModelTextPart,\n ModelToolCallPart,\n ModelToolOutput,\n ModelToolResultPart,\n ProviderData,\n} from \"../models/messages\"\nimport {\n estimateModelCall,\n type ModelCallCost,\n type ModelReportedCost,\n rateModelCall,\n} from \"../models/pricing\"\nimport type { ModelOutput, ModelTool } from \"../models/tools\"\n\nconst MAX_PROVIDER_DATA_BYTES = 256 * 1024\n\ninterface ModelLoopOptions {\n readonly model: LanguageModel\n readonly messages: readonly ModelMessage[]\n readonly tools?: readonly ModelTool[]\n readonly reasoning?: ModelReasoning\n readonly maxOutputTokens?: number\n readonly caching?: \"auto\" | \"off\"\n readonly maxSteps: number\n /** Direct generation cannot execute or synthesize local tool results. */\n readonly rejectLocalToolCalls?: boolean\n readonly signal: AbortSignal\n /** Reserve the final provider call for a tool-free synthesis response. */\n readonly finalStepInstruction?: string\n readonly prepareStep?: (\n input: PrepareModelStepInput\n ) => PrepareModelStepResult | undefined | Promise<PrepareModelStepResult | undefined>\n readonly onEvent?: (event: ModelUiChunk) => void | Promise<void>\n readonly onModelCallEnd?: (event: ModelCallEndEvent) => void | Promise<void>\n readonly onStepEnd?: (step: ModelStep) => void | Promise<void>\n /**\n * Asked after each step that ran local tools, once `onStepEnd` settled: `true` ends the loop\n * there, before the next provider call. Its tool results are the last thing the loop produced.\n */\n readonly pauseAfterStep?: (step: ModelStep) => boolean | Promise<boolean>\n /**\n * Asked when the model answers without local tools and a step is left, once `onStepEnd` settled,\n * with that step's index. Messages it returns follow that answer in one more step, instead of the\n * loop ending on it.\n */\n readonly beforeComplete?: (\n step: ModelStep,\n stepIndex: number\n ) => readonly ModelMessage[] | undefined | Promise<readonly ModelMessage[] | undefined>\n readonly generateCallId?: () => string\n}\n\n/** Non-text output requires a validator; unvalidated text can only inhabit types accepting string. */\nexport type RunModelLoopInput<TOutput = string> = ModelLoopOptions &\n (\n | { readonly output: ModelOutput<TOutput> }\n | (string extends TOutput ? { readonly output?: undefined } : never)\n )\n\nexport interface PrepareModelStepInput {\n readonly stepIndex: number\n readonly messages: readonly ModelMessage[]\n readonly model: LanguageModel\n readonly signal: AbortSignal\n}\n\nexport interface PrepareModelStepResult {\n /** Replacement history retained for this request and subsequent steps. */\n readonly messages?: readonly ModelMessage[]\n}\n\nexport type ModelLoopResult<TOutput = string> =\n | {\n readonly status: \"completed\"\n readonly output: TOutput\n readonly steps: readonly ModelStep[]\n readonly finishReason: ModelFinishReason\n }\n | {\n readonly status: \"aborted\"\n readonly steps: readonly ModelStep[]\n readonly partialContent: readonly ModelAssistantPart[]\n }\n\n/** What a loop given `pauseAfterStep` returns: it may also stop after a step that ran tools. */\nexport type PausableModelLoopResult<TOutput = string> =\n | ModelLoopResult<TOutput>\n /** `pauseAfterStep` stopped the loop after the last of these steps. */\n | {\n readonly status: \"paused\"\n readonly steps: readonly ModelStep[]\n }\n\ninterface CompletedResponse {\n readonly providerIds?: import(\"../models/events\").ModelProviderIds\n readonly content: readonly ModelAssistantPart[]\n readonly toolCalls: readonly ParsedToolCall[]\n readonly finishReason: ModelFinishReason\n readonly rawFinishReason?: string\n readonly usage: ModelUsage\n readonly responseId?: string\n readonly responseModelId?: string\n readonly projectionError?: Error\n readonly reportedCost?: ModelReportedCost\n readonly route?: import(\"../models/events\").ModelRoute\n}\n\ninterface ParsedToolCall {\n readonly part: ModelToolCallPart\n readonly inputError?: Error\n}\n\n/**\n * Run a provider-neutral, streaming model/tool loop.\n *\n * One step is exactly one provider call. Lifecycle and stream callbacks are awaited so the caller\n * controls backpressure and can fail closed before another billable call starts.\n * Completed steps and partial content contain validated JSON payloads and normalized provider\n * metadata. Trace adapters may project these results directly; storage owns write validation.\n */\nexport function runModelLoop<TOutput = string>(\n input: RunModelLoopInput<TOutput> & Required<Pick<ModelLoopOptions, \"pauseAfterStep\">>\n): Promise<PausableModelLoopResult<TOutput>>\nexport function runModelLoop<TOutput = string>(\n input: RunModelLoopInput<TOutput>\n): Promise<ModelLoopResult<TOutput>>\nexport async function runModelLoop(\n input: RunModelLoopInput<unknown>\n): Promise<PausableModelLoopResult<unknown>> {\n assertLoopInput(input)\n const tools = indexTools(input.tools ?? [])\n const toolSpecifications = [...tools.values()].map<ModelToolSpecification>((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n }))\n let messages: readonly ModelMessage[] = [...input.messages]\n const steps: ModelStep[] = []\n const generateCallId = input.generateCallId ?? (() => `model_call_${randomUUID()}`)\n const callIds = new Set<string>()\n\n for (let stepIndex = 0; stepIndex < input.maxSteps; stepIndex += 1) {\n if (input.signal.aborted) {\n return { status: \"aborted\", steps, partialContent: [] }\n }\n await input.onEvent?.({ type: \"start-step\" })\n\n let requestMessages: readonly ModelMessage[]\n try {\n const prepared = await input.prepareStep?.({\n stepIndex,\n messages,\n model: input.model,\n signal: input.signal,\n })\n requestMessages = prepared?.messages ?? messages\n } catch (error) {\n if (!input.signal.aborted && !isAbortError(error)) throw error\n return { status: \"aborted\", steps, partialContent: [] }\n }\n if (input.signal.aborted) {\n return { status: \"aborted\", steps, partialContent: [] }\n }\n let requestTools: readonly ModelToolSpecification[] = toolSpecifications\n if (input.finalStepInstruction !== undefined && stepIndex === input.maxSteps - 1) {\n requestMessages = [\n ...requestMessages,\n { role: \"user\", content: [{ type: \"text\", text: input.finalStepInstruction }] },\n ]\n requestTools = []\n }\n\n const callId = generateCallId()\n if (!callId || callIds.has(callId)) {\n throw new ModelStreamError(`[SixbModels] Model call IDs must be nonempty and unique.`)\n }\n callIds.add(callId)\n const accumulator = new StreamAccumulator(input.onEvent)\n let accepted = false\n let cost: ModelCallCost = { status: \"unpriceable\", reason: \"missing-usage\" }\n let terminalStreamError: { readonly error: unknown } | undefined\n try {\n const stream = await input.model.stream({\n callId,\n messages: requestMessages,\n tools: requestTools,\n ...(input.reasoning === undefined ? {} : { reasoning: input.reasoning }),\n ...(input.maxOutputTokens === undefined ? {} : { maxOutputTokens: input.maxOutputTokens }),\n ...(input.caching === undefined ? {} : { caching: input.caching }),\n ...(input.output === undefined\n ? {}\n : {\n responseFormat: {\n type: \"json\" as const,\n name: input.output.name,\n ...(input.output.description === undefined\n ? {}\n : { description: input.output.description }),\n schema: input.output.schema,\n },\n }),\n signal: input.signal,\n })\n accepted = true\n for await (const event of stream.events) {\n await accumulator.accept(event)\n }\n } catch (error) {\n const aborted = input.signal.aborted || isAbortError(error)\n if (accumulator.isFinished()) {\n if (!aborted) terminalStreamError = { error }\n } else if (!aborted) {\n throw error\n } else {\n return {\n status: \"aborted\",\n steps,\n partialContent: accumulator.partialContent(),\n }\n }\n } finally {\n // Once a stream is accepted, cancellation or protocol failure cannot erase the call.\n // Only a finish event establishes final meters; interrupted calls remain explicitly unknown.\n if (accepted) {\n const facts = accumulator.accounting()\n const estimate = accumulator.isFinished() ? estimateModelCall(input.model, facts) : cost\n cost = facts.reportedCost\n ? rateModelCall({ usage: facts.usage, reported: facts.reportedCost })\n : estimate\n await input.onModelCallEnd?.({\n callId,\n modelKind: \"language\",\n providerId: input.model.providerId,\n modelId: input.model.modelId,\n responseId: facts.responseId ?? `${callId}:response`,\n providerIds: facts.providerIds,\n responseModelId: facts.responseModelId,\n usage: facts.usage,\n cost,\n ...(facts.reportedCost === undefined ? {} : { estimate }),\n ...(input.reasoning === undefined ? {} : { requestedReasoning: input.reasoning }),\n ...(facts.route === undefined ? {} : { route: facts.route }),\n })\n }\n }\n\n if (input.signal.aborted && !accumulator.isFinished()) {\n return { status: \"aborted\", steps, partialContent: accumulator.partialContent() }\n }\n const completed = accumulator.complete()\n const responseId = completed.responseId ?? `${callId}:response`\n if (terminalStreamError) throw terminalStreamError.error\n if (completed.projectionError) throw completed.projectionError\n if (input.signal.aborted) {\n return { status: \"aborted\", steps, partialContent: completed.content }\n }\n\n // Closed tool arguments are not proof of a successful response. In particular,\n // providers can close valid JSON before reporting truncation or content filtering.\n // A response cut short by the output limit still ends the loop with what it produced:\n // its local tool calls are dropped, never executed. Other unsuccessful finishes fail.\n const response =\n completed.finishReason === \"length\" ? withoutLocalToolCalls(completed) : completed\n const localCalls = response.toolCalls.filter((call) => call.part.providerExecuted !== true)\n if (localCalls.length > 0 && ![\"stop\", \"tool-calls\", \"pause\"].includes(response.finishReason)) {\n throw new ModelStreamError(\n `[SixbModels] Cannot execute local tools after '${response.finishReason}'.`\n )\n }\n if (\n input.rejectLocalToolCalls &&\n (localCalls.length > 0 || response.finishReason === \"tool-calls\")\n ) {\n throw new ModelStreamError(\"[SixbModels] Direct generation cannot continue local tool calls.\")\n }\n if (response.finishReason === \"pause\" && localCalls.length === 0) {\n const step = modelStep(response, responseId, response.content, cost)\n steps.push(step)\n await input.onStepEnd?.(step)\n messages = [...requestMessages, { role: \"assistant\", content: response.content }]\n if (stepIndex + 1 === input.maxSteps) {\n throw new ModelStreamError(\n \"[SixbModels] Model reached the step limit while a provider continuation was pending.\"\n )\n }\n continue\n }\n if (localCalls.length === 0) {\n const step = modelStep(response, responseId, response.content, cost)\n steps.push(step)\n await input.onStepEnd?.(step)\n\n // An answer cut short by the output limit ends the loop as it is.\n const canContinue = response.finishReason !== \"length\" && stepIndex + 1 < input.maxSteps\n let followUp: readonly ModelMessage[] | undefined\n try {\n followUp = canContinue ? await input.beforeComplete?.(step, stepIndex) : undefined\n } catch (error) {\n if (!input.signal.aborted && !isAbortError(error)) throw error\n return { status: \"aborted\", steps, partialContent: [] }\n }\n if (followUp?.length) {\n messages = [\n ...requestMessages,\n { role: \"assistant\", content: response.content },\n ...followUp,\n ]\n continue\n }\n\n if (input.output) {\n const text = responseText(response)\n if (response.finishReason !== \"stop\") {\n throw new StructuredOutputError(\n `[SixbModels] Structured output did not complete successfully (${response.finishReason}).`,\n structuredOutputErrorContext(input, response, responseId, cost, text)\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw new StructuredOutputError(\"[SixbModels] Model did not produce valid JSON output.\", {\n cause: error,\n ...structuredOutputErrorContext(input, response, responseId, cost, text),\n })\n }\n try {\n return {\n status: \"completed\",\n output: input.output.validate(raw),\n steps,\n finishReason: response.finishReason,\n }\n } catch (error) {\n throw new StructuredOutputError(\"[SixbModels] Structured output validation failed.\", {\n cause: error,\n ...structuredOutputErrorContext(input, response, responseId, cost, text),\n })\n }\n }\n const output = responseText(response)\n return { status: \"completed\", output, steps, finishReason: response.finishReason }\n }\n\n const toolResults = await Promise.all(\n localCalls.map((call) => executeToolCall(call, tools, callId, input.signal, input.onEvent))\n )\n const step = modelStep(response, responseId, [...response.content, ...toolResults], cost)\n steps.push(step)\n await input.onStepEnd?.(step)\n\n if (input.signal.aborted) {\n return {\n status: \"aborted\",\n steps,\n partialContent: [],\n }\n }\n if (await input.pauseAfterStep?.(step)) {\n return { status: \"paused\", steps }\n }\n\n const assistantContent = response.content.filter(\n (part) => part.type !== \"tool-result\" || part.providerExecuted === true\n )\n messages = [\n ...requestMessages,\n { role: \"assistant\", content: assistantContent },\n { role: \"tool\", content: toolResults },\n ]\n\n if (stepIndex + 1 === input.maxSteps) {\n if (input.output) {\n throw new StructuredOutputError(\n \"[SixbModels] Model reached the step limit without structured output.\",\n structuredOutputErrorContext(input, response, responseId, cost, responseText(response))\n )\n }\n const output = responseText(response)\n return { status: \"completed\", output, steps, finishReason: response.finishReason }\n }\n }\n\n throw new ModelStreamError(\"[SixbModels] Model loop exited without a terminal result.\")\n}\n\nfunction assertLoopInput(input: RunModelLoopInput<unknown>): void {\n if (\n input.maxOutputTokens !== undefined &&\n (!Number.isSafeInteger(input.maxOutputTokens) || input.maxOutputTokens <= 0)\n ) {\n throw new TypeError(\"[SixbModels] maxOutputTokens must be a positive safe integer.\")\n }\n if (!Number.isInteger(input.maxSteps) || input.maxSteps <= 0) {\n throw new TypeError(\"[SixbModels] maxSteps must be a positive integer.\")\n }\n if (!input.model.providerId.trim() || !input.model.modelId.trim()) {\n throw new TypeError(\"[SixbModels] Model providerId and modelId must not be empty.\")\n }\n if (\n input.model.definition.providerId !== input.model.providerId ||\n input.model.definition.modelId !== input.model.modelId\n ) {\n throw new TypeError(\n `[SixbModels] Model definition for '${input.model.providerId}/${input.model.modelId}' has a different identity.`\n )\n }\n if (input.output) {\n if (!input.output.name.trim()) {\n throw new TypeError(\"[SixbModels] Structured output names must not be empty.\")\n }\n assertJsonObject(input.output.schema, \"structured output schema\")\n }\n}\n\nfunction indexTools(tools: readonly ModelTool[]): ReadonlyMap<string, ModelTool> {\n const result = new Map<string, ModelTool>()\n for (const tool of tools) {\n if (!tool.name.trim()) throw new TypeError(\"[SixbModels] Tool names must not be empty.\")\n if (result.has(tool.name)) {\n throw new TypeError(`[SixbModels] Duplicate tool name '${tool.name}'.`)\n }\n assertJsonObject(tool.inputSchema, `tool '${tool.name}' input schema`)\n result.set(tool.name, tool)\n }\n return result\n}\n\nfunction withoutLocalToolCalls(response: CompletedResponse): CompletedResponse {\n const dropped = new Set(\n response.toolCalls\n .filter((call) => call.part.providerExecuted !== true)\n .map((call) => call.part.toolCallId)\n )\n if (dropped.size === 0) return response\n return {\n ...response,\n content: response.content.filter(\n (part) => part.type !== \"tool-call\" || !dropped.has(part.toolCallId)\n ),\n toolCalls: response.toolCalls.filter((call) => !dropped.has(call.part.toolCallId)),\n }\n}\n\nfunction responseText(response: CompletedResponse): string {\n return response.content\n .filter((part): part is ModelTextPart => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\")\n}\n\nfunction structuredOutputErrorContext(\n input: RunModelLoopInput<unknown>,\n response: CompletedResponse,\n responseId: string,\n cost: ModelCallCost,\n text: string\n) {\n return {\n text,\n providerId: input.model.providerId,\n modelId: input.model.modelId,\n responseId,\n ...(response.responseModelId === undefined\n ? {}\n : { responseModelId: response.responseModelId }),\n finishReason: response.finishReason,\n usage: response.usage,\n cost,\n }\n}\n\nfunction modelStep(\n response: CompletedResponse,\n responseId: string,\n content: readonly ModelAssistantPart[],\n cost: import(\"../models/pricing\").ModelCallCost\n): ModelStep {\n return {\n content,\n finishReason: response.finishReason,\n ...(response.rawFinishReason === undefined\n ? {}\n : { rawFinishReason: response.rawFinishReason }),\n usage: response.usage,\n responseId,\n ...(response.responseModelId === undefined\n ? {}\n : { responseModelId: response.responseModelId }),\n cost,\n ...(response.route === undefined ? {} : { route: response.route }),\n }\n}\n\nasync function executeToolCall(\n call: ParsedToolCall,\n tools: ReadonlyMap<string, ModelTool>,\n callId: string,\n signal: AbortSignal,\n onEvent: RunModelLoopInput[\"onEvent\"]\n): Promise<ModelToolResultPart> {\n const { part } = call\n if (call.inputError) {\n const errorText = `Tool input is not valid JSON: ${call.inputError.message}`\n await onEvent?.({\n type: \"tool-input-error\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n errorText,\n })\n return toolErrorResult(part, errorText)\n }\n\n const tool = tools.get(part.toolName)\n if (!tool) {\n const errorText = `Tool '${part.toolName}' is not available.`\n await onEvent?.({\n type: \"tool-output-error\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n errorText,\n })\n return toolErrorResult(part, errorText)\n }\n\n let parsed: unknown\n try {\n parsed = tool.parseInput(part.input)\n } catch (error) {\n const errorText = error instanceof Error ? error.message : \"Tool input validation failed.\"\n await onEvent?.({\n type: \"tool-input-error\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n errorText,\n })\n return toolErrorResult(part, errorText)\n }\n\n await onEvent?.({\n type: \"tool-input-available\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n })\n let output: JsonValue\n let modelOutput: ModelToolOutput\n try {\n const context = { signal, callId, toolCallId: part.toolCallId }\n output = await tool.execute(parsed, context)\n assertJsonValue(output, `tool '${part.toolName}' output`)\n modelOutput = tool.toModelOutput\n ? await tool.toModelOutput(output, context)\n : modelToolOutput(output)\n validateModelToolOutput(modelOutput, part.toolName)\n } catch (error) {\n const errorText = tool.errorText(error)\n await onEvent?.({\n type: \"tool-output-error\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n errorText,\n })\n return toolErrorResult(part, errorText)\n }\n // Publication failures belong to the caller, not the tool's recoverable error channel.\n await onEvent?.({\n type: \"tool-output-available\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output,\n })\n return {\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output: modelOutput,\n ...(modelOutputMatchesOriginal(modelOutput, output) ? {} : { originalOutput: output }),\n }\n}\n\nfunction validateModelToolOutput(output: ModelToolOutput, toolName: string): void {\n if (output.type === \"text\" || output.type === \"error-text\") {\n if (typeof output.value !== \"string\") {\n throw new TypeError(`[SixbModels] Tool '${toolName}' model output must contain text.`)\n }\n return\n }\n if (output.type !== \"json\" && output.type !== \"error-json\") {\n throw new TypeError(\n `[SixbModels] Tool '${toolName}' returned an unsupported model output type.`\n )\n }\n assertJsonValue(output.value, `tool '${toolName}' model output`)\n}\n\nfunction modelOutputMatchesOriginal(output: ModelToolOutput, original: JsonValue): boolean {\n if (output.type === \"text\") return typeof original === \"string\" && output.value === original\n if (output.type === \"json\") return output.value === original\n return false\n}\n\nfunction modelToolOutput(value: JsonValue): ModelToolOutput {\n return typeof value === \"string\" ? { type: \"text\", value } : { type: \"json\", value }\n}\n\nfunction toolErrorResult(part: ModelToolCallPart, errorText: string): ModelToolResultPart {\n if (typeof errorText !== \"string\") {\n throw new TypeError(`[SixbModels] Tool '${part.toolName}' error text must be a string.`)\n }\n return {\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output: { type: \"error-text\", value: errorText },\n }\n}\n\ntype MutableTextPart = {\n type: \"text\"\n text: string\n providerData?: ProviderData\n complete: boolean\n}\ntype MutableReasoningPart = {\n type: \"reasoning\"\n text: string\n providerData?: ProviderData\n complete: boolean\n}\ntype MutableToolCall = {\n type: \"tool-call\"\n toolCallId: string\n toolName: string\n inputText: string\n providerData?: ProviderData\n providerExecuted?: boolean\n dynamic?: boolean\n complete: boolean\n}\ntype MutablePart =\n | MutableTextPart\n | MutableReasoningPart\n | MutableToolCall\n | ModelToolResultPart\n | ModelProviderStatePart\n\nclass StreamAccumulator {\n private readonly parts: MutablePart[] = []\n private readonly spans = new Map<string, MutableTextPart | MutableReasoningPart>()\n private readonly toolCalls = new Map<string, MutableToolCall>()\n private started = false\n private finished = false\n private finishReason: ModelFinishReason | undefined\n private rawFinishReason: string | undefined\n private usage: ModelUsage = {}\n private responseId: string | undefined\n private providerIds: import(\"../models/events\").ModelProviderIds | undefined\n private responseModelId: string | undefined\n private projectionError: Error | undefined\n private reportedCost: ModelReportedCost | undefined\n private route: import(\"../models/events\").ModelRoute | undefined\n\n constructor(private readonly onEvent: RunModelLoopInput[\"onEvent\"]) {}\n\n isFinished(): boolean {\n return this.finished\n }\n\n async accept(event: LanguageModelStreamEvent): Promise<void> {\n if (this.finished) {\n throw new ModelStreamError(`[SixbModels] Received '${event.type}' after stream finish.`)\n }\n switch (event.type) {\n case \"stream-start\":\n if (this.started) throw new ModelStreamError(\"[SixbModels] Duplicate stream-start event.\")\n this.started = true\n return\n case \"response-metadata\":\n this.requireStarted(event.type)\n this.responseId = event.id ?? this.responseId\n if (event.providerIds) this.providerIds = { ...this.providerIds, ...event.providerIds }\n this.responseModelId = event.modelId ?? this.responseModelId\n return\n case \"text-start\":\n await this.startText(event)\n return\n case \"text-delta\":\n await this.appendText(event, \"text\")\n return\n case \"text-end\":\n await this.endText(event, \"text\")\n return\n case \"reasoning-start\":\n await this.startReasoning(event)\n return\n case \"reasoning-delta\":\n await this.appendText(event, \"reasoning\")\n return\n case \"reasoning-end\":\n await this.endText(event, \"reasoning\")\n return\n case \"tool-input-start\":\n await this.startTool(event)\n return\n case \"tool-input-delta\":\n await this.appendTool(event)\n return\n case \"tool-input-end\":\n this.endTool(event)\n return\n case \"tool-call\":\n await this.completeTool(event)\n return\n case \"tool-result\":\n this.addProviderToolResult(event)\n return\n case \"provider-state\":\n if (typeof event.providerId !== \"string\" || event.providerId.length === 0) {\n this.captureProjectionError(\n new ModelStreamError(\"[SixbModels] Provider state requires a nonempty provider ID.\")\n )\n return\n }\n if (this.captureProviderState(event.data)) {\n this.parts.push({\n type: \"provider-state\",\n providerId: event.providerId,\n data: event.data,\n })\n }\n return\n case \"finish\":\n this.requireStarted(event.type)\n validateUsage(event.usage)\n this.captureProviderData(event.providerData)\n this.finished = true\n this.finishReason = event.finishReason\n this.rawFinishReason = event.rawFinishReason\n this.usage = event.usage\n this.reportedCost = event.reportedCost\n this.route = event.route\n return\n case \"error\":\n throw event.error instanceof Error\n ? event.error\n : new ModelProviderError(\"[SixbModels] Provider stream failed.\", \"unknown\", \"unknown\", {\n cause: event.error,\n })\n }\n }\n\n complete(): CompletedResponse {\n if (!this.started) throw new ModelStreamError(\"[SixbModels] Stream did not start.\")\n if (!this.finished || !this.finishReason) {\n throw new ModelStreamError(\"[SixbModels] Stream ended without a finish event.\")\n }\n if (this.finishReason === \"length\") this.settleTruncatedParts()\n for (const part of this.parts) {\n if (\"complete\" in part && !part.complete) {\n throw new ModelStreamError(\n `[SixbModels] Stream finished with incomplete ${part.type} content.`\n )\n }\n }\n const parsed = this.parseParts(false)\n return {\n content: parsed.content,\n toolCalls: parsed.toolCalls,\n finishReason: this.finishReason,\n ...(this.rawFinishReason === undefined ? {} : { rawFinishReason: this.rawFinishReason }),\n ...this.accounting(),\n ...(this.projectionError === undefined ? {} : { projectionError: this.projectionError }),\n }\n }\n\n accounting() {\n return {\n usage: this.usage,\n ...(this.responseId === undefined ? {} : { responseId: this.responseId }),\n ...(this.providerIds === undefined ? {} : { providerIds: this.providerIds }),\n ...(this.responseModelId === undefined ? {} : { responseModelId: this.responseModelId }),\n ...(this.reportedCost === undefined ? {} : { reportedCost: this.reportedCost }),\n ...(this.route === undefined ? {} : { route: this.route }),\n }\n }\n\n /**\n * The output limit explains spans a provider left open: streamed text and reasoning are kept as\n * written, and an unfinished tool call is dropped, never executed.\n */\n private settleTruncatedParts(): void {\n for (let index = this.parts.length - 1; index >= 0; index -= 1) {\n const part = this.parts[index]\n if (part === undefined || !(\"complete\" in part) || part.complete) continue\n if (part.type === \"tool-call\") {\n this.parts.splice(index, 1)\n this.toolCalls.delete(part.toolCallId)\n } else {\n part.complete = true\n }\n }\n }\n\n partialContent(): readonly ModelAssistantPart[] {\n return this.parseParts(true).content\n }\n\n private parseParts(partial: boolean): {\n readonly content: ModelAssistantPart[]\n readonly toolCalls: ParsedToolCall[]\n } {\n const content: ModelAssistantPart[] = []\n const toolCalls: ParsedToolCall[] = []\n for (const part of this.parts) {\n if (part.type === \"text\") {\n if ((!partial || part.text.length > 0) && (part.complete || partial)) {\n content.push({\n type: \"text\",\n text: part.text,\n ...(part.providerData === undefined ? {} : { providerData: part.providerData }),\n })\n }\n } else if (part.type === \"reasoning\") {\n if (part.complete) {\n content.push({\n type: \"reasoning\",\n text: part.text,\n ...(part.providerData === undefined ? {} : { providerData: part.providerData }),\n })\n }\n } else if (part.type === \"tool-call\") {\n if (!part.complete) continue\n let value: JsonValue = null\n let inputError: Error | undefined\n try {\n const parsed: unknown = JSON.parse(part.inputText)\n if (!isJsonValue(parsed)) throw new TypeError(\"input is not a JSON value\")\n value = parsed\n } catch (error) {\n inputError = error instanceof Error ? error : new Error(String(error))\n }\n const call: ModelToolCallPart = {\n type: \"tool-call\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: value,\n ...(part.providerData === undefined ? {} : { providerData: part.providerData }),\n ...(part.providerExecuted === undefined\n ? {}\n : { providerExecuted: part.providerExecuted }),\n ...(part.dynamic === undefined ? {} : { dynamic: part.dynamic }),\n }\n content.push(call)\n toolCalls.push({ part: call, ...(inputError === undefined ? {} : { inputError }) })\n } else {\n content.push(part)\n }\n }\n return { content, toolCalls }\n }\n\n private async startText(\n event: Extract<LanguageModelStreamEvent, { type: \"text-start\" }>\n ): Promise<void> {\n this.requireStarted(event.type)\n this.assertNewSpan(event.id)\n const providerData = this.captureProviderData(event.providerData)\n const part: MutableTextPart = {\n type: \"text\",\n text: \"\",\n complete: false,\n ...(providerData === undefined ? {} : { providerData }),\n }\n this.spans.set(event.id, part)\n this.parts.push(part)\n await this.onEvent?.({ type: \"text-start\", id: event.id })\n }\n\n private async startReasoning(\n event: Extract<LanguageModelStreamEvent, { type: \"reasoning-start\" }>\n ): Promise<void> {\n this.requireStarted(event.type)\n this.assertNewSpan(event.id)\n const providerData = this.captureProviderData(event.providerData)\n const part: MutableReasoningPart = {\n type: \"reasoning\",\n text: \"\",\n complete: false,\n ...(providerData === undefined ? {} : { providerData }),\n }\n this.spans.set(event.id, part)\n this.parts.push(part)\n await this.onEvent?.({ type: \"reasoning-start\", id: event.id })\n }\n\n private async appendText(\n event: Extract<LanguageModelStreamEvent, { type: \"text-delta\" | \"reasoning-delta\" }>,\n expected: \"text\" | \"reasoning\"\n ): Promise<void> {\n const part = this.spans.get(event.id)\n if (!part || part.type !== expected || part.complete) {\n throw new ModelStreamError(\n `[SixbModels] ${event.type} references unopened ${expected} span '${event.id}'.`\n )\n }\n part.text += event.delta\n await this.onEvent?.({ type: event.type, id: event.id, delta: event.delta })\n }\n\n private async endText(\n event: Extract<LanguageModelStreamEvent, { type: \"text-end\" | \"reasoning-end\" }>,\n expected: \"text\" | \"reasoning\"\n ): Promise<void> {\n const part = this.spans.get(event.id)\n if (!part || part.type !== expected || part.complete) {\n throw new ModelStreamError(\n `[SixbModels] ${event.type} references unopened ${expected} span '${event.id}'.`\n )\n }\n part.providerData = mergeProviderData(\n part.providerData,\n this.captureProviderData(event.providerData)\n )\n part.complete = true\n this.spans.delete(event.id)\n await this.onEvent?.({ type: event.type, id: event.id })\n }\n\n private async startTool(\n event: Extract<LanguageModelStreamEvent, { type: \"tool-input-start\" }>\n ): Promise<void> {\n this.requireStarted(event.type)\n if (\n typeof event.id !== \"string\" ||\n !event.id ||\n typeof event.toolName !== \"string\" ||\n !event.toolName\n ) {\n throw new ModelStreamError(\"[SixbModels] Tool calls require nonempty IDs and names.\")\n }\n if (this.toolCalls.has(event.id)) {\n throw new ModelStreamError(`[SixbModels] Duplicate tool call ID '${event.id}'.`)\n }\n const providerData = this.captureProviderData(event.providerData)\n const part: MutableToolCall = {\n type: \"tool-call\",\n toolCallId: event.id,\n toolName: event.toolName,\n inputText: \"\",\n complete: false,\n ...(providerData === undefined ? {} : { providerData }),\n ...(event.providerExecuted === undefined ? {} : { providerExecuted: event.providerExecuted }),\n ...(event.dynamic === undefined ? {} : { dynamic: event.dynamic }),\n }\n this.toolCalls.set(event.id, part)\n this.parts.push(part)\n await this.onEvent?.({\n type: \"tool-input-start\",\n toolCallId: event.id,\n toolName: event.toolName,\n })\n }\n\n private async appendTool(\n event: Extract<LanguageModelStreamEvent, { type: \"tool-input-delta\" }>\n ): Promise<void> {\n const part = this.toolCalls.get(event.id)\n if (!part || part.complete) {\n throw new ModelStreamError(\n `[SixbModels] tool-input-delta references unopened tool call '${event.id}'.`\n )\n }\n part.inputText += event.delta\n await this.onEvent?.({\n type: \"tool-input-delta\",\n toolCallId: event.id,\n toolName: part.toolName,\n inputTextDelta: event.delta,\n })\n }\n\n private endTool(event: Extract<LanguageModelStreamEvent, { type: \"tool-input-end\" }>): void {\n const part = this.toolCalls.get(event.id)\n if (!part || part.complete) {\n throw new ModelStreamError(\n `[SixbModels] tool-input-end references unopened tool call '${event.id}'.`\n )\n }\n part.providerData = mergeProviderData(\n part.providerData,\n this.captureProviderData(event.providerData)\n )\n part.complete = true\n }\n\n private async completeTool(\n event: Extract<LanguageModelStreamEvent, { type: \"tool-call\" }>\n ): Promise<void> {\n await this.startTool({\n type: \"tool-input-start\",\n id: event.toolCallId,\n toolName: event.toolName,\n ...(event.providerData === undefined ? {} : { providerData: event.providerData }),\n ...(event.providerExecuted === undefined ? {} : { providerExecuted: event.providerExecuted }),\n ...(event.dynamic === undefined ? {} : { dynamic: event.dynamic }),\n })\n const part = this.toolCalls.get(event.toolCallId)\n if (!part) throw new ModelStreamError(\"[SixbModels] Failed to index completed tool call.\")\n part.inputText = event.input\n part.complete = true\n }\n\n private addProviderToolResult(\n event: Extract<LanguageModelStreamEvent, { type: \"tool-result\" }>\n ): void {\n if (!this.captureJsonValue(event.output, \"provider tool result\")) return\n const providerData = this.captureProviderData(event.providerData)\n this.parts.push({\n type: \"tool-result\",\n toolCallId: event.toolCallId,\n toolName: event.toolName,\n output: event.isError\n ? { type: \"error-json\", value: event.output }\n : modelToolOutput(event.output),\n providerExecuted: event.providerExecuted ?? true,\n ...(event.dynamic === undefined ? {} : { dynamic: event.dynamic }),\n ...(providerData === undefined ? {} : { providerData }),\n })\n }\n\n private captureProviderData(data: ProviderData | undefined): ProviderData | undefined {\n if (data === undefined) return undefined\n try {\n return normalizeProviderData(data)\n } catch (error) {\n this.captureProjectionError(error)\n return undefined\n }\n }\n\n private captureProviderState(value: unknown): value is JsonValue {\n if (!this.captureJsonValue(value, \"provider state\")) return false\n if (JSON.stringify(value).length > MAX_PROVIDER_DATA_BYTES) {\n this.captureProjectionError(\n new ModelStreamError(\n `[SixbModels] Provider state exceeds the ${MAX_PROVIDER_DATA_BYTES}-byte response limit.`\n )\n )\n return false\n }\n return true\n }\n\n private captureJsonValue(value: unknown, label: string): value is JsonValue {\n try {\n assertJsonValue(value, label)\n return true\n } catch (error) {\n this.captureProjectionError(error)\n return false\n }\n }\n\n private captureProjectionError(error: unknown): void {\n this.projectionError ??= error instanceof Error ? error : new Error(String(error))\n }\n\n private requireStarted(type: string): void {\n if (!this.started) {\n throw new ModelStreamError(`[SixbModels] Received '${type}' before stream-start.`)\n }\n }\n\n private assertNewSpan(id: string): void {\n if (!id) throw new ModelStreamError(\"[SixbModels] Content span IDs must not be empty.\")\n if (this.spans.has(id)) {\n throw new ModelStreamError(`[SixbModels] Duplicate open content span '${id}'.`)\n }\n }\n}\n\nfunction validateUsage(usage: ModelUsage): void {\n for (const [key, value] of Object.entries(usage)) {\n if (key === \"raw\") {\n if (value !== undefined) assertJsonValue(value, \"raw model usage\")\n continue\n }\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 0)) {\n throw new ModelStreamError(`[SixbModels] Usage field '${key}' must be a nonnegative integer.`)\n }\n }\n}\n\nfunction normalizeProviderData(value: ProviderData): ProviderData {\n const data = omitUndefinedObjectProperties(value)\n assertJsonValue(data, \"provider data\")\n if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n throw new TypeError(\"[SixbModels] provider data must be a JSON object.\")\n }\n if (JSON.stringify(data).length > MAX_PROVIDER_DATA_BYTES) {\n throw new ModelStreamError(\n `[SixbModels] Provider data exceeds the ${MAX_PROVIDER_DATA_BYTES}-byte response limit.`\n )\n }\n return data\n}\n\n/** Normalize absent metadata fields at ingestion, leaving non-JSON values for validation. */\nfunction omitUndefinedObjectProperties(value: unknown, seen = new Set<object>()): unknown {\n if (typeof value !== \"object\" || value === null || seen.has(value)) return value\n seen.add(value)\n try {\n if (Array.isArray(value)) {\n return value.map((entry) => omitUndefinedObjectProperties(entry, seen))\n }\n if (!isPlainRecord(value)) return value\n return Object.fromEntries(\n Reflect.ownKeys(value)\n .filter((key) => Object.prototype.propertyIsEnumerable.call(value, key))\n .map((key) => [key, Reflect.get(value, key)] as const)\n .filter(([, entry]) => entry !== undefined)\n .map(([key, entry]) => [key, omitUndefinedObjectProperties(entry, seen)])\n )\n } finally {\n seen.delete(value)\n }\n}\n\nfunction mergeProviderData(\n first: ProviderData | undefined,\n second: ProviderData | undefined\n): ProviderData | undefined {\n if (first === undefined) return second\n if (second === undefined) return first\n return { ...first, ...second }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return (\n (error instanceof DOMException && error.name === \"AbortError\") ||\n (error instanceof Error && error.name === \"AbortError\")\n )\n}\n",
72
+ "import { randomUUID } from \"node:crypto\"\nimport { assertModelAccess } from \"../../authorization\"\nimport type { BlobStorage } from \"../../blob-storage/types\"\nimport type { ExecutionContext } from \"../../execution\"\nimport type { SixbRuntimeContext } from \"../../runtime/types\"\nimport type { ModelCatalog } from \"../catalog\"\nimport type { ModelCallEndEvent } from \"../events\"\nimport type { AiModelCallRecorder } from \"../execution/model-call-recorder\"\nimport type { ModelExecutionSession } from \"../execution/session\"\nimport { prepareModelInputFile, readModelInputFile } from \"../input-file\"\nimport { estimateModelCall, type ModelMoney } from \"../pricing\"\nimport { assertTranscriptionModel } from \"./catalog\"\nimport { TranscriptionModelResponseError } from \"./errors\"\nimport { createSpeak } from \"./speech\"\nimport type {\n AudioModelsRuntime,\n TranscriptionModel,\n TranscriptionModelResponseMetadata,\n TranscriptionModelResult,\n} from \"./types\"\n\nexport function createAudioRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n catalog: ModelCatalog | undefined,\n session: ModelExecutionSession,\n blobs: BlobStorage | undefined\n): AudioModelsRuntime {\n return {\n speak: createSpeak(runtime, execution, catalog, session, blobs),\n async transcribe(input) {\n assertModelAccess(runtime, execution, \"models.audio.transcribe\")\n\n const { file: audio, mediaType } = prepareModelInputFile(input.audio, \"audio\")\n if (!blobs) {\n throw new Error(\"[SixbModels] Transcription requires blob storage.\")\n }\n\n const signal = session.signal(input.signal)\n signal.throwIfAborted()\n\n const binding = selectModel(catalog, input.model)\n assertTranscriptionModel(binding)\n assertFileSupport(binding, audio.sizeBytes, mediaType)\n\n const accounting = await session.accounting()\n accounting.assertHealthy()\n\n const model = binding.resolve ? await binding.resolve() : binding\n assertTranscriptionModel(model)\n if (model.providerId !== binding.providerId || model.modelId !== binding.modelId) {\n throw new TypeError(\n \"[SixbModels] Resolved transcription model identity does not match the selected model.\"\n )\n }\n assertFileSupport(model, audio.sizeBytes, mediaType)\n\n signal.throwIfAborted()\n const bytes = await readModelInputFile(blobs, audio, signal)\n accounting.assertHealthy()\n\n const reservationCost = estimateReservationCost(model, bytes.byteLength, mediaType)\n const callId = `call_${randomUUID()}`\n await accounting.admitCall({\n callId,\n providerId: model.providerId,\n modelId: model.modelId,\n modelKind: \"transcription\",\n inputTokens: { status: \"unavailable\", reason: \"nonTextInput\" },\n outputTokenAllowance: 0,\n reservationCost,\n })\n\n let result: TranscriptionModelResult\n try {\n signal.throwIfAborted()\n result = await model.transcribe({ audio: bytes, mediaType, signal })\n } catch (error) {\n await recordTranscription(\n accounting,\n model,\n callId,\n error instanceof TranscriptionModelResponseError ? error.metadata : {}\n )\n throw error\n }\n\n // A completed, billable reply must survive cancellation and transcript validation failures.\n const event = await recordTranscription(accounting, model, callId, result ?? {})\n signal.throwIfAborted()\n if (typeof result?.output?.text !== \"string\") {\n throw new TranscriptionModelResponseError(\n \"[SixbModels] Invalid transcription response.\",\n model.providerId,\n model.modelId,\n result ?? {}\n )\n }\n\n return {\n output: { text: result.output.text },\n usage: event.usage,\n cost: event.cost,\n callId,\n }\n },\n }\n}\n\nfunction selectModel(\n catalog: ModelCatalog | undefined,\n requested: TranscriptionModel | undefined\n): TranscriptionModel {\n // A model the caller passes runs as given, listed or not; the catalog supplies the default.\n const selected = requested ?? catalog?.audio?.transcription?.default.model\n if (!selected) {\n throw new Error(\n \"[SixbModels] Configure models.audio.transcription in createSixb() or supply a model to transcribe().\"\n )\n }\n\n return selected\n}\n\nfunction assertFileSupport(model: TranscriptionModel, sizeBytes: number, mediaType: string): void {\n if (sizeBytes > model.definition.maxInputBytes) {\n throw new RangeError(\n `[SixbModels] Audio exceeds the model's ${model.definition.maxInputBytes}-byte input limit.`\n )\n }\n if (model.definition.mediaTypes && !model.definition.mediaTypes.includes(mediaType)) {\n throw new TypeError(\n `[SixbModels] Audio media type '${mediaType}' is not supported by the selected model.`\n )\n }\n}\n\nfunction estimateReservationCost(\n model: TranscriptionModel,\n sizeBytes: number,\n mediaType: string\n): ModelMoney | undefined {\n try {\n return model.costEstimator?.estimateReservation?.({ sizeBytes, mediaType })\n } catch {\n // Optional pricing cannot bypass an enforced budget: admission fails closed without it.\n return undefined\n }\n}\n\nasync function recordTranscription(\n accounting: AiModelCallRecorder,\n model: TranscriptionModel,\n callId: string,\n metadata: TranscriptionModelResponseMetadata\n): Promise<ModelCallEndEvent> {\n const usage = metadata.usage ?? {}\n const estimate = estimateModelCall(model, {\n usage,\n route: metadata.route,\n responseModelId: metadata.responseModelId,\n })\n const event: ModelCallEndEvent = {\n callId,\n modelKind: \"transcription\",\n providerId: model.providerId,\n modelId: model.modelId,\n responseId: metadata.providerIds?.responseId ?? callId,\n providerIds: metadata.providerIds,\n responseModelId: metadata.responseModelId,\n usage,\n cost: metadata.reportedCost ? { status: \"reported\", ...metadata.reportedCost } : estimate,\n ...(metadata.reportedCost ? { estimate } : {}),\n route: metadata.route,\n }\n\n await accounting.onModelCallEnd(event)\n return event\n}\n",
73
+ "import { createHash } from \"node:crypto\"\nimport type { BlobStorage, FileRef } from \"../blob-storage/types\"\nimport { isFileRef } from \"../blob-storage/validation\"\n\n/** Snapshot caller-owned metadata before model resolution or storage introduces an await. */\nexport function prepareModelInputFile(\n input: FileRef,\n type: \"audio\" | \"image\"\n): { file: FileRef; mediaType: string } {\n if (!isFileRef(input) || !Number.isSafeInteger(input.sizeBytes) || input.sizeBytes <= 0) {\n throw new TypeError(`[SixbModels] ${capitalize(type)} input must be a nonempty FileRef.`)\n }\n\n const file = { ...input }\n const mediaType = file.mediaType?.split(\";\", 1)[0]?.trim().toLowerCase()\n if (!mediaType || !new RegExp(`^${type}/[a-z0-9.+-]+$`).test(mediaType)) {\n throw new TypeError(\n `[SixbModels] ${capitalize(type)} FileRef must declare an ${type} mediaType.`\n )\n }\n\n return { file, mediaType }\n}\n\nfunction capitalize(type: \"audio\" | \"image\"): string {\n return type === \"audio\" ? \"Audio\" : \"Image\"\n}\n\n/** Read an already validated reference, bounded by its verified size and the model's limit. */\nexport async function readModelInputFile(\n storage: BlobStorage,\n file: FileRef,\n signal: AbortSignal\n): Promise<Uint8Array> {\n const info = await storage.stat(file.blobId)\n signal.throwIfAborted()\n if (\n !info ||\n info.blobId !== file.blobId ||\n info.digest !== file.digest ||\n info.sizeBytes !== file.sizeBytes\n ) {\n throw new Error(\"[SixbModels] File reference does not match the stored file.\")\n }\n\n const stream = await storage.open(file.blobId)\n const reader = stream.getReader()\n const cancel = () => {\n void reader.cancel(signal.reason).catch(() => undefined)\n }\n signal.addEventListener(\"abort\", cancel, { once: true })\n\n let complete = false\n try {\n signal.throwIfAborted()\n\n const bytes = new Uint8Array(file.sizeBytes)\n const hash = createHash(\"sha256\")\n let offset = 0\n\n while (true) {\n const { value, done } = await reader.read()\n signal.throwIfAborted()\n if (done) break\n if (!(value instanceof Uint8Array) || value.byteLength > bytes.byteLength - offset) {\n throw new Error(\"[SixbModels] File stream exceeds its declared size.\")\n }\n\n bytes.set(value, offset)\n hash.update(value)\n offset += value.byteLength\n }\n\n if (offset !== file.sizeBytes || `sha256:${hash.digest(\"hex\")}` !== file.digest) {\n throw new Error(\"[SixbModels] File stream does not match its content-addressed reference.\")\n }\n\n complete = true\n return bytes\n } finally {\n signal.removeEventListener(\"abort\", cancel)\n if (!complete) {\n void reader.cancel().catch(() => undefined)\n }\n reader.releaseLock()\n }\n}\n",
74
+ "import { randomUUID } from \"node:crypto\"\nimport { assertModelAccess } from \"../../authorization\"\nimport type { BlobStorage } from \"../../blob-storage/types\"\nimport type { ExecutionContext } from \"../../execution\"\nimport type { SixbRuntimeContext } from \"../../runtime/types\"\nimport type { ModelCatalog } from \"../catalog\"\nimport type { ModelCallEndEvent } from \"../events\"\nimport type { AiModelCallRecorder } from \"../execution/model-call-recorder\"\nimport type { ModelExecutionSession } from \"../execution/session\"\nimport { estimateModelCall, type ModelMoney } from \"../pricing\"\nimport { assertSpeechModel } from \"./catalog\"\nimport { SpeechModelResponseError } from \"./errors\"\nimport type {\n AudioModelsRuntime,\n AudioSpeakInput,\n SpeechModel,\n SpeechModelRequest,\n SpeechModelResponseMetadata,\n SpeechModelResult,\n SpeechReservationInput,\n} from \"./types\"\n\ntype PreparedRequest = Omit<SpeechModelRequest, \"signal\">\n\nexport function createSpeak(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n catalog: ModelCatalog | undefined,\n session: ModelExecutionSession,\n blobs: BlobStorage | undefined\n): AudioModelsRuntime[\"speak\"] {\n return async (input) => {\n assertModelAccess(runtime, execution, \"models.audio.speak\")\n\n const prepared = prepareRequest(input)\n if (!blobs) {\n throw new Error(\"[SixbModels] Speech generation requires blob storage.\")\n }\n\n const signal = session.signal(input.signal)\n signal.throwIfAborted()\n\n const binding = selectModel(catalog, input.model)\n assertSpeechModel(binding)\n assertRequestSupport(binding, withVoice(binding, prepared))\n\n const accounting = await session.accounting()\n accounting.assertHealthy()\n\n const model = binding.resolve ? await binding.resolve() : binding\n assertSpeechModel(model)\n if (model.providerId !== binding.providerId || model.modelId !== binding.modelId) {\n throw new TypeError(\n \"[SixbModels] Resolved speech model identity does not match the selected model.\"\n )\n }\n const request = withVoice(model, prepared)\n assertRequestSupport(model, request)\n signal.throwIfAborted()\n\n const callId = `call_${randomUUID()}`\n await accounting.admitCall({\n callId,\n providerId: model.providerId,\n modelId: model.modelId,\n modelKind: \"speech\",\n inputTokens: {\n status: \"estimated\",\n tokens: Math.ceil(new TextEncoder().encode(request.text).byteLength / 4),\n method: \"utf8BytesDividedByFour\",\n },\n outputTokenAllowance: 0,\n reservationCost: estimateReservationCost(model, {\n text: request.text,\n ...(request.voice === undefined ? {} : { voice: request.voice }),\n ...(request.instructions === undefined ? {} : { instructions: request.instructions }),\n }),\n })\n\n let result: SpeechModelResult\n try {\n signal.throwIfAborted()\n result = await model.speak({ ...request, signal })\n } catch (error) {\n await recordSpeech(\n accounting,\n model,\n callId,\n error instanceof SpeechModelResponseError ? error.metadata : {}\n )\n throw error\n }\n\n // A completed, billable reply must survive cancellation and audio validation failures.\n const event = await recordSpeech(accounting, model, callId, result ?? {})\n signal.throwIfAborted()\n const audio = result?.output?.audio\n if (\n !(audio?.data instanceof Uint8Array) ||\n audio.data.byteLength === 0 ||\n typeof audio.mediaType !== \"string\" ||\n !/^audio\\/[a-z0-9.+-]+$/.test(audio.mediaType) ||\n (request.mediaType !== undefined && audio.mediaType !== request.mediaType) ||\n !isWarnings(result.warnings)\n ) {\n throw new SpeechModelResponseError(\n \"[SixbModels] Invalid speech response.\",\n model.providerId,\n model.modelId,\n result ?? {}\n )\n }\n\n const file = await blobs.put({\n body: audio.data,\n expectedSizeBytes: audio.data.byteLength,\n mediaType: audio.mediaType,\n signal,\n })\n await accounting.recordFiles(callId, [file])\n return {\n file,\n warnings: [...(result.warnings ?? [])],\n usage: event.usage,\n cost: event.cost,\n callId,\n }\n }\n}\n\n/** Validate and snapshot the caller's request before the first await. */\nfunction prepareRequest(input: AudioSpeakInput): PreparedRequest {\n if (typeof input?.text !== \"string\" || !input.text.trim()) {\n throw new TypeError(\"[SixbModels] Speech generation requires nonblank text.\")\n }\n for (const field of [\"voice\", \"instructions\", \"language\"] as const) {\n const value = input[field]\n if (value !== undefined && (typeof value !== \"string\" || !value.trim())) {\n throw new TypeError(`[SixbModels] Speech ${field} must be a nonblank string.`)\n }\n }\n const mediaType = input.mediaType?.split(\";\", 1)[0]?.trim().toLowerCase()\n if (input.mediaType !== undefined && !/^audio\\/[a-z0-9.+-]+$/.test(mediaType ?? \"\")) {\n throw new TypeError(\"[SixbModels] Speech mediaType must be an audio media type.\")\n }\n if (\n input.speed !== undefined &&\n (typeof input.speed !== \"number\" || !Number.isFinite(input.speed) || input.speed <= 0)\n ) {\n throw new TypeError(\"[SixbModels] Speech speed must be a positive number.\")\n }\n\n return {\n text: input.text,\n ...(input.voice === undefined ? {} : { voice: input.voice }),\n ...(input.instructions === undefined ? {} : { instructions: input.instructions }),\n ...(mediaType === undefined ? {} : { mediaType }),\n ...(input.speed === undefined ? {} : { speed: input.speed }),\n ...(input.language === undefined ? {} : { language: input.language }),\n }\n}\n\nfunction withVoice(model: SpeechModel, request: PreparedRequest): PreparedRequest {\n const voice = request.voice ?? model.defaultVoice\n return voice === undefined ? request : { ...request, voice }\n}\n\nfunction selectModel(\n catalog: ModelCatalog | undefined,\n requested: SpeechModel | undefined\n): SpeechModel {\n // A model the caller passes runs as given, listed or not; the catalog supplies the default.\n const selected = requested ?? catalog?.audio?.speech?.default.model\n if (!selected) {\n throw new Error(\n \"[SixbModels] Configure models.audio.speech in createSixb() or supply a model to speak().\"\n )\n }\n\n return selected\n}\n\nfunction assertRequestSupport(model: SpeechModel, request: PreparedRequest): void {\n const definition = model.definition\n if (\n definition.maxInputCharacters !== undefined &&\n request.text.length > definition.maxInputCharacters\n ) {\n throw new RangeError(\n `[SixbModels] Text exceeds the model's ${definition.maxInputCharacters}-character input limit.`\n )\n }\n if (\n request.voice !== undefined &&\n definition.voices &&\n !definition.voices.includes(request.voice)\n ) {\n throw new TypeError(\n `[SixbModels] Voice '${request.voice}' is not supported by the selected model. Use one of: ${definition.voices.join(\", \")}.`\n )\n }\n if (\n request.mediaType !== undefined &&\n definition.outputMediaTypes &&\n !definition.outputMediaTypes.includes(request.mediaType)\n ) {\n throw new TypeError(\n `[SixbModels] Speech media type '${request.mediaType}' is not supported by the selected model. Use one of: ${definition.outputMediaTypes.join(\", \")}.`\n )\n }\n if (request.instructions !== undefined && definition.instructions === false) {\n throw new TypeError(\"[SixbModels] The selected model does not take speech instructions.\")\n }\n}\n\nfunction estimateReservationCost(\n model: SpeechModel,\n input: SpeechReservationInput\n): ModelMoney | undefined {\n try {\n return model.costEstimator?.estimateReservation?.(input)\n } catch {\n // Optional pricing cannot bypass an enforced budget: admission fails closed without it.\n return undefined\n }\n}\n\nasync function recordSpeech(\n accounting: AiModelCallRecorder,\n model: SpeechModel,\n callId: string,\n metadata: SpeechModelResponseMetadata\n): Promise<ModelCallEndEvent> {\n const usage = metadata.usage ?? {}\n const estimate = estimateModelCall(model, {\n usage,\n route: metadata.route,\n responseModelId: metadata.responseModelId,\n ...(metadata.pricingDimensions === undefined ? {} : { dimensions: metadata.pricingDimensions }),\n })\n const event: ModelCallEndEvent = {\n callId,\n modelKind: \"speech\",\n providerId: model.providerId,\n modelId: model.modelId,\n responseId: metadata.providerIds?.responseId ?? callId,\n providerIds: metadata.providerIds,\n responseModelId: metadata.responseModelId,\n usage,\n cost: metadata.reportedCost ? { status: \"reported\", ...metadata.reportedCost } : estimate,\n ...(metadata.reportedCost ? { estimate } : {}),\n route: metadata.route,\n }\n\n await accounting.onModelCallEnd(event)\n return event\n}\n\nfunction isWarnings(value: unknown): value is readonly string[] | undefined {\n return value === undefined || (Array.isArray(value) && value.every((w) => typeof w === \"string\"))\n}\n",
75
+ "import { principalsEqual } from \"../auth/types\"\nimport type { FileRef } from \"../blob-storage/types\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type { ExecutionRecord } from \"../storage/executions\"\n\n/** The files one model call produced. */\nexport interface ModelCallFiles {\n readonly callId: string\n readonly files: readonly FileRef[]\n readonly recordedAt: Date\n}\n\nexport interface ModelCallsRuntime {\n /**\n * The files a call produced, when the caller can see the run that made it: the request's own\n * principal, the agent thread's readers, or the action or workflow run's viewers. Null when the\n * call produced none or is hidden; usage observers see a call's cost, not its content.\n */\n files(callId: string): Promise<ModelCallFiles | null>\n}\n\n/** Whether the caller sees a run, as the runtime's own run lookups decide it. */\nexport interface ModelCallRunVisibility {\n canViewActionRun(runId: string): Promise<boolean>\n canViewWorkflowRun(runId: string): Promise<boolean>\n /** A conversation run: visible to whoever can read its thread. */\n canViewAgentRun(runId: string): Promise<boolean>\n}\n\n// Subagents nest; a chain longer than this is a storage fault, not a deeper delegation.\nconst MAX_SUBAGENT_DEPTH = 32\n\nexport function createModelCallsRuntime(\n runtime: Pick<SixbRuntimeContext, \"projectId\" | \"runtimeAuthorization\" | \"storage\">,\n runs: ModelCallRunVisibility,\n /** The execution reading; it reads what it produced, whoever can see its run. */\n executionId?: string\n): ModelCallsRuntime {\n const projectId = runtime.projectId\n\n async function canRead(execution: ExecutionRecord): Promise<boolean> {\n const authority = resolveRuntimeAuthorizationForProject(runtime)\n if (authority.type === \"unrestricted\") return true\n if (authority.type !== \"principal\") return false\n\n const executor = execution.executor\n if (executor.type === \"request\") {\n return (\n execution.requestedBy !== undefined &&\n principalsEqual(authority.context.principal, execution.requestedBy)\n )\n }\n if (executor.type === \"primitive\") {\n if (executor.kind === \"action\") return runs.canViewActionRun(executor.runId)\n if (executor.kind === \"workflow\") return runs.canViewWorkflowRun(executor.runId)\n return false\n }\n if (executor.type === \"agent\") return canReadAgentRun(executor.runId)\n return false\n }\n\n async function canReadAgentRun(runId: string): Promise<boolean> {\n const agents = runtime.storage.agents\n let id = runId\n for (let depth = 0; depth < MAX_SUBAGENT_DEPTH; depth += 1) {\n const run = agents ? await agents.runs.getById({ projectId, id }) : null\n if (run?.kind === \"conversation\") return runs.canViewAgentRun(run.id)\n if (run?.kind === \"subagent\") {\n id = run.parentRunId\n continue\n }\n // A workflow's agent step runs as a node of that workflow's run.\n const node = await runtime.storage.workflowRuns?.nodes.getById({ projectId, id })\n return node ? runs.canViewWorkflowRun(node.workflowRunId) : false\n }\n return false\n }\n\n return {\n async files(callId) {\n if (typeof callId !== \"string\" || !callId.trim()) {\n throw new TypeError(\"[SixbModels] A model call ID must be a nonblank string.\")\n }\n const record = await runtime.storage.aiUsage?.getModelCallFiles({ projectId, callId })\n if (!record) return null\n\n // A workflow's agent step runs as a service account that cannot view its own workflow run,\n // yet must read back the image it just made.\n const visible = { callId: record.callId, files: record.files, recordedAt: record.recordedAt }\n if (record.executionId === executionId) return visible\n\n const execution = await runtime.storage.executions.getById({\n projectId,\n id: record.executionId,\n })\n return execution && (await canRead(execution)) ? visible : null\n },\n }\n}\n",
76
+ "import { randomUUID } from \"node:crypto\"\nimport { assertModelAccess } from \"../../authorization\"\nimport type { BlobStorage, FileRef } from \"../../blob-storage/types\"\nimport type { ExecutionContext } from \"../../execution\"\nimport type { SixbRuntimeContext } from \"../../runtime/types\"\nimport type { ModelCatalog } from \"../catalog\"\nimport type { ModelCallEndEvent } from \"../events\"\nimport type { AiModelCallRecorder } from \"../execution/model-call-recorder\"\nimport type { ModelExecutionSession } from \"../execution/session\"\nimport { prepareModelInputFile, readModelInputFile } from \"../input-file\"\nimport { estimateModelCall, type ModelMoney } from \"../pricing\"\nimport type { ModelPricingDimensions } from \"../rate-card\"\nimport { assertImageModel } from \"./catalog\"\nimport { ImageModelResponseError } from \"./errors\"\nimport type {\n ImageData,\n ImageGenerateInput,\n ImageModel,\n ImageModelResponseMetadata,\n ImageModelResult,\n ImageModelsRuntime,\n ImageReservationInput,\n} from \"./types\"\n\ninterface PreparedRequest {\n readonly prompt: string\n readonly n: number\n readonly size?: string\n readonly aspectRatio?: string\n readonly quality?: string\n readonly style?: string\n readonly seed?: number\n readonly images: readonly { readonly file: FileRef; readonly mediaType: string }[]\n}\n\nexport function createImageRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n catalog: ModelCatalog | undefined,\n session: ModelExecutionSession,\n blobs: BlobStorage | undefined\n): ImageModelsRuntime {\n return {\n async generate(input) {\n assertModelAccess(runtime, execution, \"models.image.generate\")\n\n const request = prepareRequest(input)\n if (!blobs) {\n throw new Error(\"[SixbModels] Image generation requires blob storage.\")\n }\n\n const signal = session.signal(input.signal)\n signal.throwIfAborted()\n\n const binding = selectModel(catalog, input.model)\n assertImageModel(binding)\n assertRequestSupport(binding, request)\n\n const accounting = await session.accounting()\n accounting.assertHealthy()\n\n const model = binding.resolve ? await binding.resolve() : binding\n assertImageModel(model)\n if (model.providerId !== binding.providerId || model.modelId !== binding.modelId) {\n throw new TypeError(\n \"[SixbModels] Resolved image model identity does not match the selected model.\"\n )\n }\n assertRequestSupport(model, request)\n\n const images: ImageData[] = []\n for (const image of request.images) {\n signal.throwIfAborted()\n images.push({\n data: await readModelInputFile(blobs, image.file, signal),\n mediaType: image.mediaType,\n })\n }\n accounting.assertHealthy()\n\n const dimensions = pricingDimensions(request)\n const promptTokens = Math.ceil(new TextEncoder().encode(request.prompt).byteLength / 4)\n const callId = `call_${randomUUID()}`\n await accounting.admitCall({\n callId,\n providerId: model.providerId,\n modelId: model.modelId,\n modelKind: \"image\",\n inputTokens:\n images.length > 0\n ? { status: \"unavailable\", reason: \"nonTextInput\" }\n : { status: \"estimated\", tokens: promptTokens, method: \"utf8BytesDividedByFour\" },\n outputTokenAllowance: 0,\n reservationCost: estimateReservationCost(model, {\n n: request.n,\n promptTokens,\n inputImages: images.length,\n dimensions,\n }),\n })\n\n let result: ImageModelResult\n try {\n signal.throwIfAborted()\n result = await model.generate({\n prompt: request.prompt,\n n: request.n,\n ...(request.size === undefined ? {} : { size: request.size }),\n ...(request.aspectRatio === undefined ? {} : { aspectRatio: request.aspectRatio }),\n ...(request.quality === undefined ? {} : { quality: request.quality }),\n ...(request.style === undefined ? {} : { style: request.style }),\n ...(request.seed === undefined ? {} : { seed: request.seed }),\n images,\n signal,\n })\n } catch (error) {\n await recordImages(\n accounting,\n model,\n callId,\n error instanceof ImageModelResponseError ? error.metadata : {},\n undefined,\n dimensions\n )\n throw error\n }\n\n // A completed, billable reply must survive cancellation and image validation failures.\n const returned = Array.isArray(result?.output?.images) ? result.output.images : undefined\n const event = await recordImages(\n accounting,\n model,\n callId,\n result ?? {},\n returned?.length,\n dimensions\n )\n signal.throwIfAborted()\n if (!returned?.length || !returned.every(isImageData) || !isWarnings(result.warnings)) {\n throw new ImageModelResponseError(\n \"[SixbModels] Invalid image response.\",\n model.providerId,\n model.modelId,\n result ?? {}\n )\n }\n\n const files: FileRef[] = []\n for (const image of returned) {\n files.push(\n await blobs.put({\n body: image.data,\n expectedSizeBytes: image.data.byteLength,\n mediaType: image.mediaType,\n signal,\n })\n )\n }\n await accounting.recordFiles(callId, files)\n\n return {\n files,\n warnings: [...(result.warnings ?? [])],\n usage: event.usage,\n cost: event.cost,\n callId,\n }\n },\n }\n}\n\n/** Validate and snapshot the caller's request before the first await. */\nfunction prepareRequest(input: ImageGenerateInput): PreparedRequest {\n if (typeof input?.prompt !== \"string\" || !input.prompt.trim()) {\n throw new TypeError(\"[SixbModels] Image generation requires a nonblank prompt.\")\n }\n const n = input.n ?? 1\n if (!Number.isSafeInteger(n) || n <= 0) {\n throw new TypeError(\"[SixbModels] Image count 'n' must be a positive safe integer.\")\n }\n for (const field of [\"size\", \"aspectRatio\", \"quality\", \"style\"] as const) {\n const value = input[field]\n if (value !== undefined && (typeof value !== \"string\" || !value.trim())) {\n throw new TypeError(`[SixbModels] Image ${field} must be a nonblank string.`)\n }\n }\n if (input.seed !== undefined && !Number.isSafeInteger(input.seed)) {\n throw new TypeError(\"[SixbModels] Image seed must be a safe integer.\")\n }\n if (input.images !== undefined && !Array.isArray(input.images)) {\n throw new TypeError(\"[SixbModels] Reference images must be an array of FileRefs.\")\n }\n\n return {\n prompt: input.prompt,\n n,\n ...(input.size === undefined ? {} : { size: input.size }),\n ...(input.aspectRatio === undefined ? {} : { aspectRatio: input.aspectRatio }),\n ...(input.quality === undefined ? {} : { quality: input.quality }),\n ...(input.style === undefined ? {} : { style: input.style }),\n ...(input.seed === undefined ? {} : { seed: input.seed }),\n images: (input.images ?? []).map((image) => prepareModelInputFile(image, \"image\")),\n }\n}\n\nfunction selectModel(\n catalog: ModelCatalog | undefined,\n requested: ImageModel | undefined\n): ImageModel {\n // A model the caller passes runs as given, listed or not; the catalog supplies the default.\n const selected = requested ?? catalog?.image?.default.model\n if (!selected) {\n throw new Error(\n \"[SixbModels] Configure models.image in createSixb() or supply a model to generate().\"\n )\n }\n\n return selected\n}\n\nfunction assertRequestSupport(model: ImageModel, request: PreparedRequest): void {\n const definition = model.definition\n if (definition.maxImagesPerCall !== undefined && request.n > definition.maxImagesPerCall) {\n throw new RangeError(\n `[SixbModels] The selected model returns at most ${definition.maxImagesPerCall} images per call.`\n )\n }\n for (const [field, list] of [\n [\"size\", definition.sizes],\n [\"aspectRatio\", definition.aspectRatios],\n [\"quality\", definition.qualities],\n [\"style\", definition.styles],\n ] as const) {\n const value = request[field]\n if (value !== undefined && list && !list.includes(value)) {\n throw new TypeError(\n `[SixbModels] Image ${field} '${value}' is not supported by the selected model. Use one of: ${list.join(\", \")}.`\n )\n }\n }\n\n if (request.images.length === 0) return\n const accepted = definition.inputImages\n if (!accepted) {\n throw new TypeError(\"[SixbModels] The selected model does not accept reference images.\")\n }\n if (request.images.length > accepted.maxCount) {\n throw new RangeError(\n `[SixbModels] The selected model accepts at most ${accepted.maxCount} reference images.`\n )\n }\n for (const image of request.images) {\n if (image.file.sizeBytes > accepted.maxBytes) {\n throw new RangeError(\n `[SixbModels] Reference image exceeds the model's ${accepted.maxBytes}-byte input limit.`\n )\n }\n if (accepted.mediaTypes && !accepted.mediaTypes.includes(image.mediaType)) {\n throw new TypeError(\n `[SixbModels] Image media type '${image.mediaType}' is not supported by the selected model.`\n )\n }\n }\n}\n\nfunction pricingDimensions(request: PreparedRequest): ModelPricingDimensions {\n return {\n ...(request.size === undefined ? {} : { size: request.size }),\n ...(request.quality === undefined ? {} : { quality: request.quality }),\n ...(request.style === undefined ? {} : { style: request.style }),\n }\n}\n\nfunction estimateReservationCost(\n model: ImageModel,\n input: ImageReservationInput\n): ModelMoney | undefined {\n try {\n return model.costEstimator?.estimateReservation?.(input)\n } catch {\n // Optional pricing cannot bypass an enforced budget: admission fails closed without it.\n return undefined\n }\n}\n\nasync function recordImages(\n accounting: AiModelCallRecorder,\n model: ImageModel,\n callId: string,\n metadata: ImageModelResponseMetadata,\n returnedImages: number | undefined,\n dimensions: ModelPricingDimensions\n): Promise<ModelCallEndEvent> {\n // The images actually returned are the count that was billed, whatever the provider reports.\n const usage = {\n ...metadata.usage,\n ...(returnedImages === undefined ? {} : { outputImages: returnedImages }),\n }\n const estimate = estimateModelCall(model, {\n usage,\n route: metadata.route,\n responseModelId: metadata.responseModelId,\n dimensions,\n })\n const event: ModelCallEndEvent = {\n callId,\n modelKind: \"image\",\n providerId: model.providerId,\n modelId: model.modelId,\n responseId: metadata.providerIds?.responseId ?? callId,\n providerIds: metadata.providerIds,\n responseModelId: metadata.responseModelId,\n usage,\n cost: metadata.reportedCost ? { status: \"reported\", ...metadata.reportedCost } : estimate,\n ...(metadata.reportedCost ? { estimate } : {}),\n route: metadata.route,\n }\n\n await accounting.onModelCallEnd(event)\n return event\n}\n\nfunction isImageData(value: unknown): value is ImageData {\n const image = value as Partial<ImageData> | null\n return (\n image?.data instanceof Uint8Array &&\n image.data.byteLength > 0 &&\n typeof image.mediaType === \"string\" &&\n /^image\\/[a-z0-9.+-]+$/.test(image.mediaType)\n )\n}\n\nfunction isWarnings(value: unknown): value is readonly string[] | undefined {\n return value === undefined || (Array.isArray(value) && value.every((w) => typeof w === \"string\"))\n}\n",
77
+ "import { assertJsonObject } from \"../json\"\nimport { schemaRecordToJsonSchema } from \"../ontology/json-schema\"\nimport { isObjectRefSchema, validateSchemaOrRefValue } from \"../ontology/refs\"\nimport type { ValueType } from \"../ontology/types\"\nimport { isRecord } from \"../ontology/validation\"\nimport { coerceSchemaValueToTyped, normalizeSchemaValue } from \"../ontology/validation/normalize\"\nimport type { LanguageModelOutputShape } from \"./generation-types\"\nimport type { ModelOutput } from \"./tools\"\n\nexport function languageModelOutput(\n shape: LanguageModelOutputShape,\n valueTypesById: ReadonlyMap<string, ValueType>\n): ModelOutput<Record<string, unknown>> {\n if (!isRecord(shape)) throw new TypeError(\"[SixbModels] output must be a Sixb schema record.\")\n const schema = schemaRecordToJsonSchema({ shape, valueTypesById })\n assertJsonObject(schema, \"model output schema\")\n return {\n name: \"sixb_output\",\n schema,\n validate(value) {\n if (!isRecord(value)) throw new TypeError(\"[SixbModels] Output must be an object.\")\n for (const key of Object.keys(value)) {\n if (!Object.hasOwn(shape, key)) {\n throw new TypeError(`[SixbModels] Unknown output field '${key}'.`)\n }\n }\n return Object.fromEntries(\n Object.entries(shape).map(([key, field]) => {\n if (!Object.hasOwn(value, key)) {\n throw new TypeError(`[SixbModels] Missing output field '${key}'.`)\n }\n validateSchemaOrRefValue(field, value[key], `output.${key}`, valueTypesById)\n const output = isObjectRefSchema(field)\n ? value[key]\n : coerceSchemaValueToTyped(\n field,\n normalizeSchemaValue(field, value[key], `output.${key}`, valueTypesById),\n valueTypesById\n )\n return [key, output]\n })\n )\n },\n }\n}\n",
78
+ "import { runModelLoop } from \"../agents/model-loop\"\nimport { assertModelAccess } from \"../authorization\"\nimport type { BlobStorage } from \"../blob-storage/types\"\nimport type { ExecutionContext } from \"../execution\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport { createAudioRuntime } from \"./audio/runtime\"\nimport { createModelCallsRuntime, type ModelCallRunVisibility } from \"./calls\"\nimport { type ModelCatalog, selectLanguageModel } from \"./catalog\"\nimport { createDecisionRuntime } from \"./decision/runtime\"\nimport { ModelProviderError, ModelStreamError, UnsupportedModelFeatureError } from \"./errors\"\nimport type { ModelCallEndEvent } from \"./events\"\nimport { registerModelExecutionBinding } from \"./execution/binding\"\nimport { aiModelCallOutputTokenAllowance } from \"./execution/model-call-admission\"\nimport type { ModelExecutionSession } from \"./execution/session\"\nimport type {\n InferLanguageModelOutput,\n LanguageModelGenerateInput,\n LanguageModelGenerateResult,\n LanguageModelOutputShape,\n ModelsRuntime,\n} from \"./generation-types\"\nimport { createImageRuntime } from \"./image/runtime\"\nimport { modelReasoningSupportIssue } from \"./language-model\"\nimport type { ModelMessage } from \"./messages\"\nimport { languageModelOutput } from \"./output\"\nimport { resolveLanguageModel } from \"./resolve\"\n\nexport function createModelsRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n catalog: ModelCatalog | undefined,\n session: ModelExecutionSession,\n runs: ModelCallRunVisibility,\n blobs?: BlobStorage\n): ModelsRuntime {\n function generate<const TShape extends LanguageModelOutputShape | undefined = undefined>(\n input: LanguageModelGenerateInput<TShape>\n ): Promise<\n LanguageModelGenerateResult<\n TShape extends LanguageModelOutputShape ? InferLanguageModelOutput<TShape> : string\n >\n >\n async function generate(\n input: LanguageModelGenerateInput<LanguageModelOutputShape | undefined>\n ): Promise<LanguageModelGenerateResult<unknown>> {\n assertModelAccess(runtime, execution, \"models.language.generate\")\n const messages = generationMessages(input)\n const signal = session.signal(input.signal)\n signal.throwIfAborted()\n // An explicit model runs as given, listed or not; the catalog supplies a tier's or the default.\n const selected = selectLanguageModel(catalog?.language, input.model)\n if (!selected) {\n throw new Error(\n \"[SixbModels] Configure models.language in createSixb() or supply a model to generate().\"\n )\n }\n const output =\n input.output === undefined\n ? undefined\n : languageModelOutput(input.output, runtime.ontology.getValueTypesById())\n const model = await resolveLanguageModel(selected)\n const reasoningIssue = modelReasoningSupportIssue(\n model.definition.capabilities.reasoning,\n input.reasoning\n )\n if (reasoningIssue) throw new UnsupportedModelFeatureError(`[SixbModels] ${reasoningIssue}.`)\n // A catalog model's default was checked against the capabilities known at startup; like any\n // request, a level the resolved model turns out not to support falls back to the provider default.\n const reasoning = input.reasoning ?? selected.defaultReasoning\n if (output && model.definition.capabilities.nativeStructuredOutput === false) {\n throw new UnsupportedModelFeatureError(\n \"[SixbModels] Model does not support native structured output.\"\n )\n }\n // Like its reasoning, the binding's output limit applies unless the call sets its own.\n const maxOutputTokens = Math.min(\n aiModelCallOutputTokenAllowance(\n input.maxOutputTokens ?? selected.maxOutputTokens ?? model.definition.maxOutputTokens\n ),\n model.definition.maxOutputTokens ?? Infinity\n )\n if (typeof reasoning === \"object\" && reasoning.budgetTokens >= maxOutputTokens) {\n throw new TypeError(\"[SixbModels] Output allowance must exceed the reasoning token budget.\")\n }\n const accounting = await session.accounting()\n accounting.assertHealthy()\n signal.throwIfAborted()\n let event: ModelCallEndEvent | undefined\n const options = {\n model: accounting.wrapModel(model),\n messages,\n maxSteps: 1,\n rejectLocalToolCalls: true,\n maxOutputTokens,\n reasoning,\n caching: input.caching,\n signal,\n onModelCallEnd: async (completed: ModelCallEndEvent) => {\n await accounting.onModelCallEnd(completed)\n event = completed\n },\n }\n const result = output ? await runModelLoop({ ...options, output }) : await runModelLoop(options)\n if (result.status === \"aborted\") {\n signal.throwIfAborted()\n throw new DOMException(\"Model generation aborted\", \"AbortError\")\n }\n if (result.finishReason === \"error\" || result.finishReason === \"content-filter\") {\n throw new ModelProviderError(\n `[SixbModels] Generation ended with '${result.finishReason}'.`,\n model.providerId,\n model.modelId\n )\n }\n if (!event)\n throw new ModelStreamError(\"[SixbModels] Generation completed without accounting metadata.\")\n return {\n output: result.output,\n usage: event.usage,\n cost: event.cost,\n callId: event.callId,\n finishReason: result.finishReason,\n }\n }\n\n const models: ModelsRuntime = {\n language: { generate },\n decision: createDecisionRuntime(runtime, execution, catalog, session, \"models\"),\n audio: createAudioRuntime(runtime, execution, catalog, session, blobs),\n image: createImageRuntime(runtime, execution, catalog, session, blobs),\n calls: createModelCallsRuntime(runtime, runs, execution.id),\n }\n registerModelExecutionBinding(models, (input) => {\n session.bind(input)\n })\n return models\n}\n\nfunction generationMessages(\n input: LanguageModelGenerateInput<LanguageModelOutputShape | undefined>\n): readonly ModelMessage[] {\n if ((input.prompt === undefined) === (input.messages === undefined)) {\n throw new TypeError(\"[SixbModels] Supply exactly one of prompt or messages.\")\n }\n if (input.prompt !== undefined && typeof input.prompt !== \"string\") {\n throw new TypeError(\"[SixbModels] prompt must be a string.\")\n }\n if (input.messages !== undefined && !Array.isArray(input.messages)) {\n throw new TypeError(\"[SixbModels] messages must be an array.\")\n }\n if (input.instructions !== undefined && typeof input.instructions !== \"string\") {\n throw new TypeError(\"[SixbModels] instructions must be a string.\")\n }\n if (\n input.maxOutputTokens !== undefined &&\n (!Number.isSafeInteger(input.maxOutputTokens) || input.maxOutputTokens <= 0)\n ) {\n throw new TypeError(\"[SixbModels] maxOutputTokens must be a positive safe integer.\")\n }\n if (input.caching !== undefined && input.caching !== \"auto\" && input.caching !== \"off\") {\n throw new TypeError(\"[SixbModels] caching must be 'auto' or 'off'.\")\n }\n return [\n ...(input.instructions === undefined\n ? []\n : [{ role: \"system\" as const, content: input.instructions }]),\n ...(input.prompt !== undefined\n ? [{ role: \"user\" as const, content: [{ type: \"text\" as const, text: input.prompt }] }]\n : (input.messages ?? [])),\n ]\n}\n",
79
+ "/**\n * Compatibility leaf operation: request an action on an object.\n *\n * The canonical action request path lives in `actions/request.ts`; object-bound\n * helpers delegate here by supplying an object subject.\n */\nimport {\n type RequestActionOptions,\n requestAction as requestRuntimeAction,\n} from \"../../actions/request\"\nimport type { ActionRunRecord } from \"../../storage\"\nimport type { ExecutionObjectContext } from \"../context\"\n\nexport type { RequestActionOptions }\n\nexport async function requestAction(\n ctx: ExecutionObjectContext,\n params: {\n primaryId: string\n actionId: string\n params?: Record<string, unknown>\n options?: RequestActionOptions\n }\n): Promise<ActionRunRecord> {\n return requestRuntimeAction(ctx, ctx.execution, {\n actionId: params.actionId,\n subject: {\n kind: \"object\",\n objectTypeId: ctx.objectType.id,\n primaryId: params.primaryId,\n },\n params: params.params,\n runId: params.options?.runId,\n signal: params.options?.signal,\n })\n}\n",
80
+ "/**\n * Runtime translation onto the ontology Materializer.\n *\n * Every typed and dynamic object/link mutation lowers to canonical Materializer operations here and\n * every Materializer result is mapped back to the public runtime shapes. The adapter owns no\n * ontology semantics: authority classification, effective resolution, validation, and event\n * construction all happen inside the Materializer's single commit.\n */\n\nimport { randomUUID } from \"node:crypto\"\nimport type { JsonValue } from \"../json\"\nimport type {\n EditCommitResult,\n EffectiveObjectSnapshot,\n ExpectedObjectRevision,\n MaterializationItemError,\n OntologyEditOperation,\n OntologyLinkRef,\n OntologyObjectRef,\n OntologyOperationOutcome,\n} from \"../materialization/model\"\nimport { normalizeJsonProperties } from \"../materializer\"\nimport type { ObjectLink, ValueType } from \"../ontology\"\nimport { OntologyValidationError } from \"../ontology/errors\"\nimport type { ObjectTypeWithPropertyTokens } from \"../ontology/tokens\"\nimport {\n assertKnownProperties,\n assertLinkTargetType,\n assertValidFileRefs,\n normalizeLinkProperties,\n normalizeObjectProperties,\n validateLinkProperties,\n validateObjectProperties,\n} from \"../ontology/validation\"\nimport { getOntologyMutationRuntime } from \"../runtime/ontology-mutations\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type { ObjectRow } from \"../storage\"\nimport { ObjectError } from \"./errors\"\nimport { uniqueViolationError, uniqueViolationItemError } from \"./unique-violation\"\n\n/** The runtime pieces one commit needs. */\nexport type RuntimeMaterializerContext = Pick<SixbRuntimeContext, \"projectId\" | \"storage\">\n\n/** One caller-supplied batch item, lowered to the operations it contributes. */\nexport interface RuntimeBatchGroup {\n /** Position in the caller's input array; item errors are reported against it. */\n readonly index: number\n readonly operations: readonly OntologyEditOperation[]\n}\n\nexport interface RuntimeBatchCommit {\n readonly commit: EditCommitResult | null\n /** Outcomes per input position, in the order the item's operations were submitted. */\n readonly outcomes: ReadonlyMap<number, readonly OntologyOperationOutcome[]>\n}\n\n/**\n * Commits ordered operations as one atomic runtime commit.\n *\n * A fresh request id per call keeps each runtime mutation its own commit; the Materializer's\n * idempotency replay then only collapses a retry of the very same request. The commit fails with an\n * `expectation` conflict when an object it expects changed since it was read.\n */\nexport async function commitRuntimeOperations(\n ctx: RuntimeMaterializerContext,\n operations: readonly OntologyEditOperation[],\n expectedObjects: readonly ExpectedObjectRevision[] = []\n): Promise<EditCommitResult> {\n const mutations = getOntologyMutationRuntime(ctx)\n try {\n return await mutations.commitEdits({\n mode: \"atomic\",\n source: { kind: \"runtime\", requestId: randomUUID() },\n operations,\n expectedObjects,\n expectedLinks: [],\n expectedLinkScopes: [],\n })\n } catch (error) {\n throw uniqueViolationError(error) ?? error\n }\n}\n\n/**\n * Commits grouped batch operations as one ordered continue-mode transaction.\n *\n * Successful items apply against one evolving authority state while semantic failures are recorded\n * per item. Provider, serialization, and CAS failures still roll the whole transaction back.\n *\n * An item that lowers to several operations is declared as one operation group so the Materializer\n * rolls the whole item back rather than committing the operations that ran before the failure.\n */\nexport async function commitRuntimeBatch(\n ctx: RuntimeMaterializerContext,\n groups: readonly RuntimeBatchGroup[],\n expectedObjects: readonly ExpectedObjectRevision[] = []\n): Promise<RuntimeBatchCommit> {\n const operations = groups.flatMap((group) => group.operations)\n if (operations.length === 0) {\n return { commit: null, outcomes: new Map() }\n }\n\n const operationGroups = groups\n .filter((group) => group.operations.length > 1)\n .map((group) => group.operations.map((operation) => operation.id))\n\n // Items that collide fail alone; a duplicate storage still finds, claimed by a commit that\n // landed meanwhile, fails the whole batch.\n const mutations = getOntologyMutationRuntime(ctx)\n let commit: EditCommitResult\n try {\n commit = await mutations.commitEdits({\n mode: \"continue\",\n source: { kind: \"runtime\", requestId: randomUUID() },\n operations,\n ...(operationGroups.length > 0 ? { operationGroups } : {}),\n ...(expectedObjects.length > 0 ? { expectedObjects } : {}),\n })\n } catch (error) {\n throw uniqueViolationError(error) ?? error\n }\n\n const byId = new Map(commit.outcomes.map((outcome) => [outcome.id, outcome]))\n const outcomes = new Map<number, readonly OntologyOperationOutcome[]>()\n for (const group of groups) {\n outcomes.set(\n group.index,\n group.operations.map((operation) => requireOutcome(byId, operation.id))\n )\n }\n return { commit, outcomes }\n}\n\n/**\n * Assigns the canonical operation id for one batch item.\n *\n * Ids derive from the caller's original ordinal so outcomes map back to input positions even when\n * earlier items failed local validation and never reached the Materializer.\n */\nexport function runtimeOperationId(index: number, subOrdinal = 0): string {\n return subOrdinal === 0 ? `op:${index}` : `op:${index}.${subOrdinal}`\n}\n\nexport interface NormalizedRuntimeObject {\n readonly primaryId: string\n /** Managed authority values; identity lives in the object ref, never in the properties. */\n readonly properties: Readonly<Record<string, JsonValue>>\n}\n\n/**\n * Validates and normalizes one runtime object input at the SDK/service boundary.\n *\n * Shape and value-type errors surface here so a batch can report them against the caller's original\n * position. Authority classification, required-property enforcement, and cardinality stay in the\n * Materializer, which validates the resolved effective object instead of the request.\n */\nexport function normalizeRuntimeObject(input: {\n readonly objectType: ObjectTypeWithPropertyTokens\n readonly primaryPropertyId: string\n readonly properties: Record<string, unknown>\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n}): NormalizedRuntimeObject {\n const { objectType, primaryPropertyId, properties, valueTypesById } = input\n assertKnownProperties(objectType, properties)\n validateObjectProperties(objectType, properties, valueTypesById)\n assertValidFileRefs(properties, objectType.id)\n\n const primaryValue = properties[primaryPropertyId]\n if (primaryValue === undefined || primaryValue === null) {\n throw new OntologyValidationError(\n `[Sixb] Missing primary property '${primaryPropertyId}' in upsert for '${objectType.id}'`\n )\n }\n\n const normalized = normalizeObjectProperties(\n objectType.properties,\n properties,\n valueTypesById,\n objectType.id\n )\n const { [primaryPropertyId]: _identity, ...managed } = normalized\n return {\n primaryId: String(primaryValue),\n properties: normalizeJsonProperties(managed, `${objectType.id} properties`),\n }\n}\n\n/**\n * Validates and normalizes one runtime link input.\n *\n * Managed link authority carries the complete property set, so required link properties must be\n * present in the request rather than inherited from the stored edge.\n */\nexport function normalizeRuntimeLink(input: {\n readonly objectType: ObjectTypeWithPropertyTokens\n readonly linkDefinition: ObjectLink\n readonly linkId: string\n readonly targetTypeId: string\n readonly properties?: Record<string, unknown>\n readonly valueTypesById: ReadonlyMap<string, ValueType>\n readonly isValidLinkTarget: (expected: string | string[], actual: string) => boolean\n}): Readonly<Record<string, JsonValue>> | undefined {\n const { objectType, linkDefinition, linkId, targetTypeId, properties, valueTypesById } = input\n assertLinkTargetType(objectType.id, linkId, linkDefinition, targetTypeId, input.isValidLinkTarget)\n validateLinkProperties(objectType, linkDefinition, properties, undefined, valueTypesById)\n assertValidFileRefs(properties, `${objectType.id}.${linkId}`)\n const normalized = normalizeLinkProperties(objectType, linkDefinition, properties, valueTypesById)\n if (normalized === undefined) return undefined\n return normalizeJsonProperties(normalized, `${objectType.id}.${linkId} properties`)\n}\n\nexport function objectUpsertOperation(input: {\n readonly id: string\n readonly ref: OntologyObjectRef\n readonly properties: Readonly<Record<string, JsonValue>>\n}): OntologyEditOperation {\n return { id: input.id, kind: \"object.upsert\", ref: input.ref, properties: input.properties }\n}\n\n/** Creates an object, and fails if any authority holds its id: a hidden one, or a deleted one. */\nexport function objectCreateOperation(input: {\n readonly id: string\n readonly ref: OntologyObjectRef\n readonly properties: Readonly<Record<string, JsonValue>>\n}): OntologyEditOperation {\n return { id: input.id, kind: \"object.create\", ref: input.ref, properties: input.properties }\n}\n\nexport function objectDeleteOperation(input: {\n readonly id: string\n readonly ref: OntologyObjectRef\n}): OntologyEditOperation {\n return { id: input.id, kind: \"object.delete\", ref: input.ref }\n}\n\nexport function objectRestoreOperation(input: {\n readonly id: string\n readonly ref: OntologyObjectRef\n}): OntologyEditOperation {\n return { id: input.id, kind: \"object.restore\", ref: input.ref }\n}\n\nexport function linkUpsertOperation(input: {\n readonly id: string\n readonly ref: OntologyLinkRef\n readonly properties?: Readonly<Record<string, JsonValue>>\n}): OntologyEditOperation {\n return {\n id: input.id,\n kind: \"link.upsert\",\n ref: input.ref,\n ...(input.properties !== undefined ? { properties: input.properties } : {}),\n }\n}\n\nexport function linkDeleteOperation(input: {\n readonly id: string\n readonly ref: OntologyLinkRef\n}): OntologyEditOperation {\n return { id: input.id, kind: \"link.delete\", ref: input.ref }\n}\n\n/** Reads the outcomes one batch item produced; the commit returns one per submitted operation. */\nexport function requireItemOutcomes(\n commit: RuntimeBatchCommit,\n index: number\n): readonly OntologyOperationOutcome[] {\n const outcomes = commit.outcomes.get(index)\n if (!outcomes || outcomes.length === 0) {\n throw new ObjectError(`[Sixb] Materializer returned no outcome for batch item ${index}.`)\n }\n return outcomes\n}\n\n/** Reads the effective object an ok outcome produced; runtime object writes always resolve one. */\nexport function requireEffectiveObject(outcome: OntologyOperationOutcome): EffectiveObjectSnapshot {\n if (!outcome.ok || !outcome.object) {\n throw new ObjectError(`[Sixb] Materializer returned no effective object for '${outcome.id}'.`)\n }\n return outcome.object\n}\n\nexport function toObjectRow(projectId: string, snapshot: EffectiveObjectSnapshot): ObjectRow {\n return {\n projectId,\n objectTypeId: snapshot.ref.objectTypeId,\n primaryId: snapshot.ref.primaryId,\n properties: structuredClone(snapshot.properties) as Record<string, unknown>,\n createdAt: new Date(snapshot.createdAt),\n updatedAt: new Date(snapshot.updatedAt),\n version: snapshot.version,\n lastCommitId: snapshot.lastCommitId,\n }\n}\n\n/** The revision a commit expects of an object, as it was read. */\nexport function expectedRevision(row: ObjectRow): ExpectedObjectRevision {\n return {\n ref: { objectTypeId: row.objectTypeId, primaryId: row.primaryId },\n exists: true,\n version: row.version,\n lastCommitId: row.lastCommitId,\n }\n}\n\n/** Rehydrates a persisted item error into the public runtime error type. */\nexport function toItemError(error: MaterializationItemError): Error {\n switch (error.code) {\n case \"validation\":\n return new OntologyValidationError(error.message)\n case \"unique_violation\":\n return uniqueViolationItemError(error)\n }\n}\n\nfunction requireOutcome(\n outcomes: ReadonlyMap<string, OntologyOperationOutcome>,\n id: string\n): OntologyOperationOutcome {\n const outcome = outcomes.get(id)\n if (!outcome) {\n throw new ObjectError(`[Sixb] Materializer returned no outcome for '${id}'.`)\n }\n return outcome\n}\n",
81
+ "/**\n * Error for runtime invariants and failures specific to the objects module\n * (e.g., unexpected event results after appending an object/link event).\n */\nexport class ObjectError extends Error {\n readonly name = \"ObjectError\"\n}\n",
82
+ "/**\n * Writes by a principal that views a type only through a condition.\n *\n * Such a writer acts on the objects its reader shows it, and on nothing else. Each existing object\n * a write names is read through that reader first: one it cannot find is hidden or missing, and\n * the write treats both as missing. Its commit then expects each object as the reader saw it, so\n * one hidden meanwhile is never written.\n *\n * Nothing is checked after the write: a writer may create an object it then cannot see.\n */\nimport { assertAuthorized, assertCanEdit } from \"../authorization\"\nimport type { JsonValue } from \"../json\"\nimport type {\n ExpectedObjectRevision,\n OntologyEditOperation,\n OntologyObjectRef,\n} from \"../materialization/model\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type { ObjectRow } from \"../storage\"\nimport {\n expectedRevision,\n objectCreateOperation,\n objectUpsertOperation,\n} from \"./materializer-adapter\"\nimport { primaryIdTakenError } from \"./unique-violation\"\n\ntype AuthorizeContext = Pick<\n SixbRuntimeContext,\n \"projectId\" | \"runtimeAuthorization\" | \"authorization\" | \"objectReader\"\n>\ntype WriteContext = AuthorizeContext & Pick<SixbRuntimeContext, \"storage\">\n\n/** What the writer finds at an id: the object it sees, or one it cannot see. Nothing when free. */\nexport type FoundObject = ObjectRow | \"hidden\"\n\n/**\n * `can.edit` on a type, and a view of it: whole, or through a condition. The reader then applies\n * that condition to each object the write names.\n */\nexport async function assertCanEditType(\n ctx: AuthorizeContext,\n objectTypeId: string\n): Promise<void> {\n if (!ctx.objectReader.viewsThroughCondition(objectTypeId)) {\n assertCanEdit(ctx, objectTypeId)\n return\n }\n\n assertAuthorized(ctx, { kind: \"object.edit\", objectTypeId })\n await ctx.objectReader.assertViewable([objectTypeId])\n}\n\n/**\n * What a writer that views `objectTypeId` through a condition finds at each primary id it writes.\n *\n * The ids its reader does not show are looked up in the object storage, to tell a free id from one\n * a hidden object holds. That tells the writer no more than that the id is taken.\n */\nexport async function findWrittenObjects(\n ctx: WriteContext,\n objectTypeId: string,\n primaryIds: readonly string[]\n): Promise<ReadonlyMap<string, FoundObject>> {\n const ids = [...new Set(primaryIds)]\n const found = new Map<string, FoundObject>()\n if (ids.length === 0) return found\n\n const visible = await ctx.objectReader.getByPrimaryIdBatch({\n items: ids.map((primaryId) => ({ objectTypeId, primaryId })),\n })\n for (const row of visible.values()) found.set(row.primaryId, row)\n\n const unseen = ids.filter((primaryId) => !found.has(primaryId))\n if (unseen.length === 0) return found\n\n const stored = await ctx.storage.objects.getByPrimaryIdBatch({\n projectId: ctx.projectId,\n items: unseen.map((primaryId) => ({ objectTypeId, primaryId })),\n })\n for (const row of stored.values()) found.set(row.primaryId, \"hidden\")\n\n return found\n}\n\n/**\n * Write one object as the writer found it: update the object it sees, and create one where the id\n * is free. A create fails in its commit if any object, a deleted one included, holds the id by\n * then, so it never merges into an object the writer did not see. An id a hidden object holds is\n * taken.\n */\nexport function writeFoundObject(input: {\n readonly id: string\n readonly ref: OntologyObjectRef\n readonly properties: Readonly<Record<string, JsonValue>>\n readonly primaryPropertyId: string\n readonly found: FoundObject | undefined\n}): OntologyEditOperation {\n const { found, primaryPropertyId, ...write } = input\n\n if (found === \"hidden\") throw primaryIdTakenError(write.ref.objectTypeId, primaryPropertyId)\n if (found === undefined) return objectCreateOperation(write)\n\n return objectUpsertOperation(write)\n}\n\n/** The revisions a commit expects of the objects its writer saw. */\nexport function expectSeen(found: Iterable<FoundObject>): ExpectedObjectRevision[] {\n return [...found].flatMap((object) => (object === \"hidden\" ? [] : [expectedRevision(object)]))\n}\n",
83
+ "/**\n * The authorization rule for writing a link, in one place because all three link leaves need it.\n */\nimport { assertAuthorized } from \"../../authorization\"\nimport type { SixbRuntimeContext } from \"../../runtime/types\"\nimport { assertCanEditType } from \"../conditional-writes\"\n\ninterface LinkWrite {\n readonly sourceTypeId: string\n readonly linkId: string\n readonly targetTypeId: string\n}\n\n/**\n * Assert a principal may create or remove these links.\n *\n * `edit` on the **source** type, `view` on the **target**: a link is declared on the source type\n * (`objectType.links`), and writing one changes the source's edges, not the target's properties.\n * Requiring `edit` on the target too would mean a clerk needs write access to every customer before\n * attaching an invoice to one.\n *\n * `view` on the target is still required, and for two reasons: it matches how links are *read* —\n * `canViewLink` already demands `view` on both endpoints — and without it the endpoint-existence\n * check that follows would answer whether a target the principal cannot see exists.\n *\n * Call this *before* any endpoint lookup, for that second reason.\n *\n * A view through a condition counts for either end: the endpoint lookup then reads each object of\n * such a type through the writer's reader, and one it cannot see is not found.\n */\nexport async function assertCanWriteLinks(\n ctx: Pick<\n SixbRuntimeContext,\n \"projectId\" | \"runtimeAuthorization\" | \"authorization\" | \"objectReader\"\n >,\n writes: readonly LinkWrite[]\n): Promise<void> {\n for (const write of writes) {\n await assertCanEditType(ctx, write.sourceTypeId)\n\n if (ctx.objectReader.viewsThroughCondition(write.targetTypeId)) {\n await ctx.objectReader.assertViewable([write.targetTypeId])\n } else {\n assertAuthorized(ctx, { kind: \"object.view\", objectTypeId: write.targetTypeId })\n }\n }\n\n // An endpoint type or a link the reader cannot read under the markings of the versions\n // projections applied is refused like one it has no view grant for, for the same reason.\n await ctx.objectReader.assertReadable({\n objectTypeIds: [\n ...new Set(writes.flatMap((write) => [write.sourceTypeId, write.targetTypeId])),\n ],\n links: writes.map((write) => ({ objectTypeId: write.sourceTypeId, linkId: write.linkId })),\n })\n}\n",
84
+ "/**\n * Shared endpoint existence reads for runtime link batches.\n *\n * The Materializer independently refuses a link whose endpoints are not effective. These reads exist\n * only so batch callers keep receiving the public {@link ObjectNotFoundError} for a missing endpoint\n * instead of a generic per-item validation error.\n *\n * An endpoint whose type the writer views through a condition exists for it only when its reader\n * shows it: a hidden one is not found, as a missing one is.\n */\n\nimport type { SixbRuntimeContext } from \"../../runtime/types\"\nimport { type ObjectRow, objectBatchKey } from \"../../storage\"\nimport { ObjectNotFoundError } from \"../../storage/errors\"\n\nexport interface LinkEndpointItem {\n readonly objectType: { readonly id: string }\n readonly sourceId: string\n readonly targetTypeId: string\n readonly targetId: string\n}\n\nexport interface EndpointExistence {\n readonly keys: ReadonlySet<string>\n /** The endpoints read through a condition, as the writer saw them: its commit expects them. */\n readonly seen: readonly ObjectRow[]\n}\n\ntype EndpointContext = Pick<SixbRuntimeContext, \"projectId\" | \"storage\" | \"objectReader\">\n\nexport function collectEndpointLookups(\n items: readonly LinkEndpointItem[]\n): { objectTypeId: string; primaryId: string }[] {\n const lookups: { objectTypeId: string; primaryId: string }[] = []\n const seen = new Set<string>()\n\n for (const item of items) {\n for (const endpoint of [\n { objectTypeId: item.objectType.id, primaryId: item.sourceId },\n { objectTypeId: item.targetTypeId, primaryId: item.targetId },\n ]) {\n const key = endpointKey(endpoint.objectTypeId, endpoint.primaryId)\n if (seen.has(key)) continue\n seen.add(key)\n lookups.push(endpoint)\n }\n }\n\n return lookups\n}\n\nexport async function loadEndpointExistence(\n ctx: EndpointContext,\n lookups: readonly { objectTypeId: string; primaryId: string }[]\n): Promise<EndpointExistence> {\n const conditioned = conditionedEndpoints(ctx, lookups)\n const stored = lookups.filter((lookup) => !conditioned.includes(lookup))\n\n const [rows, seen] = await Promise.all([\n stored.length === 0\n ? new Map<string, ObjectRow>()\n : ctx.storage.objects.getByPrimaryIdBatch({ projectId: ctx.projectId, items: stored }),\n readSeenEndpoints(ctx, conditioned),\n ])\n\n return { keys: new Set([...rows.keys(), ...seen.keys()]), seen: [...seen.values()] }\n}\n\n/** The endpoints whose type the writer views through a condition. */\nexport function conditionedEndpoints<T extends { readonly objectTypeId: string }>(\n ctx: Pick<SixbRuntimeContext, \"objectReader\">,\n lookups: readonly T[]\n): T[] {\n return lookups.filter((lookup) => ctx.objectReader.viewsThroughCondition(lookup.objectTypeId))\n}\n\n/** The endpoints among `conditioned` the writer's reader shows, keyed like the lookups. */\nexport async function readSeenEndpoints(\n ctx: Pick<SixbRuntimeContext, \"objectReader\">,\n conditioned: readonly { objectTypeId: string; primaryId: string }[]\n): Promise<ReadonlyMap<string, ObjectRow>> {\n if (conditioned.length === 0) return new Map()\n return ctx.objectReader.getByPrimaryIdBatch({ items: conditioned })\n}\n\n/** Throws {@link ObjectNotFoundError} for the first endpoint the read did not find. */\nexport function requireEndpoints(item: LinkEndpointItem, existing: EndpointExistence): void {\n if (!existing.keys.has(endpointKey(item.objectType.id, item.sourceId))) {\n throw new ObjectNotFoundError(item.objectType.id, item.sourceId, \"Source object not found\")\n }\n if (!existing.keys.has(endpointKey(item.targetTypeId, item.targetId))) {\n throw new ObjectNotFoundError(item.targetTypeId, item.targetId, \"Target object not found\")\n }\n}\n\nfunction endpointKey(objectTypeId: string, primaryId: string): string {\n return objectBatchKey(objectTypeId, primaryId)\n}\n",
85
+ "/**\n * Leaf operation: remove a single link through the ontology Materializer.\n */\nimport { assertLinkTargetType } from \"../../ontology/validation\"\nimport type { ResolvedLinkContext } from \"../context\"\nimport {\n commitRuntimeOperations,\n expectedRevision,\n linkDeleteOperation,\n runtimeOperationId,\n} from \"../materializer-adapter\"\nimport { assertCanWriteLinks } from \"./authorization\"\nimport { collectEndpointLookups, conditionedEndpoints, readSeenEndpoints } from \"./endpoints\"\n\nexport async function removeLink(\n ctx: ResolvedLinkContext,\n params: {\n sourceId: string\n linkId: string\n targetTypeId: string\n targetId: string\n }\n): Promise<void> {\n const { objectType, linkDefinition, ontology } = ctx\n const { sourceId, linkId, targetTypeId, targetId } = params\n await assertCanWriteLinks(ctx, [{ sourceTypeId: objectType.id, linkId, targetTypeId }])\n\n assertLinkTargetType(objectType.id, linkId, linkDefinition, targetTypeId, (expected, actual) =>\n ontology.isValidLinkTarget(expected, actual)\n )\n\n // A writer removes a link only between objects it sees: one to an object hidden from it is\n // removed as a missing one is, not at all.\n const conditioned = conditionedEndpoints(\n ctx,\n collectEndpointLookups([{ objectType, sourceId, targetTypeId, targetId }])\n )\n const seen = await readSeenEndpoints(ctx, conditioned)\n if (seen.size < conditioned.length) return\n\n // A missing link is a no-op: the delete records managed authority only when an effective edge\n // exists, so the commit reports `unchanged` instead of failing.\n await commitRuntimeOperations(\n ctx,\n [\n linkDeleteOperation({\n id: runtimeOperationId(0),\n ref: {\n source: { objectTypeId: objectType.id, primaryId: sourceId },\n linkId,\n target: { objectTypeId: targetTypeId, primaryId: targetId },\n },\n }),\n ],\n [...seen.values()].map(expectedRevision)\n )\n}\n",
86
+ "/**\n * Leaf operation: upsert a single link through the ontology Materializer.\n */\nimport type { ResolvedLinkContext } from \"../context\"\nimport {\n commitRuntimeOperations,\n expectedRevision,\n linkUpsertOperation,\n normalizeRuntimeLink,\n runtimeOperationId,\n} from \"../materializer-adapter\"\nimport { assertCanWriteLinks } from \"./authorization\"\nimport { collectEndpointLookups, loadEndpointExistence, requireEndpoints } from \"./endpoints\"\n\nexport async function upsertLink(\n ctx: ResolvedLinkContext,\n params: {\n sourceId: string\n linkId: string\n targetTypeId: string\n targetId: string\n properties?: Record<string, unknown>\n }\n): Promise<void> {\n const { objectType, linkDefinition, ontology } = ctx\n const { sourceId, linkId, targetTypeId, targetId, properties } = params\n await assertCanWriteLinks(ctx, [{ sourceTypeId: objectType.id, linkId, targetTypeId }])\n const endpoints = { objectType, sourceId, targetTypeId, targetId }\n\n // Endpoint reads keep the public `ObjectNotFoundError` contract; the Materializer independently\n // refuses a link whose endpoints are not effective when it commits. This runs before property\n // normalization so the same input reports the same error class here and through the batch APIs,\n // which check endpoints first inside `plan`.\n const existing = await loadEndpointExistence(ctx, collectEndpointLookups([endpoints]))\n requireEndpoints(endpoints, existing)\n\n const normalizedProperties = normalizeRuntimeLink({\n objectType,\n linkDefinition,\n linkId,\n targetTypeId,\n properties,\n valueTypesById: ontology.getValueTypesById(),\n isValidLinkTarget: (expected, actual) => ontology.isValidLinkTarget(expected, actual),\n })\n\n await commitRuntimeOperations(\n ctx,\n [\n linkUpsertOperation({\n id: runtimeOperationId(0),\n ref: {\n source: { objectTypeId: objectType.id, primaryId: sourceId },\n linkId,\n target: { objectTypeId: targetTypeId, primaryId: targetId },\n },\n ...(normalizedProperties !== undefined ? { properties: normalizedProperties } : {}),\n }),\n ],\n existing.seen.map(expectedRevision)\n )\n}\n",
87
+ "/**\n * Per-item mechanics shared by every runtime batch.\n *\n * One place owns the rules the public batch APIs promise: a local failure stays at its own input\n * position, an identical repeat collapses onto the first item and shares its result, a conflicting\n * repeat is rejected, and each item's Materializer outcomes map back to the position they came from.\n */\n\nimport type {\n ExpectedObjectRevision,\n OntologyEditOperation,\n OntologyOperationOutcome,\n} from \"../materialization/model\"\nimport { OntologyValidationError } from \"../ontology/errors\"\nimport type { BatchItemResult } from \"../runtime/types\"\nimport {\n commitRuntimeBatch,\n type RuntimeMaterializerContext,\n requireItemOutcomes,\n toItemError,\n} from \"./materializer-adapter\"\n\nexport interface RuntimeBatchItemPlan {\n /** Identity this item claims. A later item claiming it must be identical. */\n readonly key: string\n /** How that identity reads in an error message, e.g. `object 'room:r1'`. */\n readonly label: string\n /** Canonical content, so an identical repeat is recognized as one. */\n readonly fingerprint: string\n readonly operations: readonly OntologyEditOperation[]\n}\n\nexport interface RuntimeItemBatch<TItem, TValue> {\n readonly ctx: RuntimeMaterializerContext\n readonly items: readonly TItem[]\n /** Lowers one item, throwing to record a local failure at that item's position. */\n plan(item: TItem, index: number): RuntimeBatchItemPlan\n /** Maps the outcomes of a fully successful item to its public value. */\n value(outcomes: readonly OntologyOperationOutcome[]): TValue\n /** Objects as the batch's author read them: one that changed fails the whole batch. */\n readonly expectedObjects?: readonly ExpectedObjectRevision[]\n}\n\ninterface PlannedItem {\n readonly index: number\n readonly operations: readonly OntologyEditOperation[]\n}\n\ninterface ClaimedIdentity {\n readonly index: number\n readonly fingerprint: string\n}\n\nexport async function runRuntimeItemBatch<TItem, TValue>(\n batch: RuntimeItemBatch<TItem, TValue>\n): Promise<readonly BatchItemResult<TValue>[]> {\n const { items } = batch\n if (items.length === 0) return []\n\n const results: BatchItemResult<TValue>[] = new Array(items.length)\n const planned: PlannedItem[] = []\n const claims = new Map<string, ClaimedIdentity>()\n /** Positions that repeat an earlier identical item and share its result. */\n const aliases = new Map<number, number>()\n\n for (const [index, item] of items.entries()) {\n let plan: RuntimeBatchItemPlan\n try {\n plan = batch.plan(item, index)\n } catch (error) {\n results[index] = {\n ok: false,\n error: error instanceof Error ? error : new Error(String(error)),\n }\n continue\n }\n\n const claimed = claims.get(plan.key)\n if (claimed) {\n if (claimed.fingerprint !== plan.fingerprint) {\n results[index] = {\n ok: false,\n error: new OntologyValidationError(\n `[Sixb] Conflicting duplicate ${plan.label} at batch positions ${claimed.index} and ${index}`\n ),\n }\n continue\n }\n aliases.set(index, claimed.index)\n continue\n }\n\n claims.set(plan.key, { index, fingerprint: plan.fingerprint })\n planned.push({ index, operations: plan.operations })\n }\n\n const commit = await commitRuntimeBatch(batch.ctx, planned, batch.expectedObjects)\n\n for (const { index } of planned) {\n const outcomes = requireItemOutcomes(commit, index)\n const failed = outcomes.find((outcome) => !outcome.ok)\n results[index] =\n failed?.ok === false\n ? { ok: false, error: toItemError(failed.error) }\n : { ok: true, value: batch.value(outcomes) }\n }\n for (const [index, source] of aliases) {\n results[index] = results[source]\n }\n return results\n}\n",
88
+ "/**\n * Leaf operation: batch upsert links through the ontology Materializer.\n *\n * Takes SixbRuntimeContext (shared infra) + per-item pre-resolved data, because each item can target\n * a different objectType + linkDefinition. Everything valid is submitted as one ordered\n * continue-mode commit.\n */\n\nimport { stableJsonStringify } from \"../../json\"\nimport { linkRefKey } from \"../../materialization/refs\"\nimport type { BatchItemResult, SixbRuntimeContext } from \"../../runtime/types\"\nimport type { ResolvedLinkBatchItem } from \"../context\"\nimport {\n expectedRevision,\n linkUpsertOperation,\n normalizeRuntimeLink,\n runtimeOperationId,\n} from \"../materializer-adapter\"\nimport { runRuntimeItemBatch } from \"../runtime-batch\"\nimport { assertCanWriteLinks } from \"./authorization\"\nimport { collectEndpointLookups, loadEndpointExistence, requireEndpoints } from \"./endpoints\"\n\nexport async function upsertLinkBatch(\n ctx: SixbRuntimeContext,\n items: readonly ResolvedLinkBatchItem[]\n): Promise<readonly BatchItemResult<void>[]> {\n const { ontology } = ctx\n if (items.length === 0) return []\n\n // Every item, up front, and before the endpoint lookup below. Authorization is a precondition, not\n // a per-item validation: a refused item must not become one failed `BatchItemResult` while the\n // rest of the batch commits. Asserting inside `plan` would do exactly that, and would also let the\n // existence lookup answer for targets the principal cannot see.\n await assertCanWriteLinks(\n ctx,\n items.map((item) => ({\n sourceTypeId: item.objectType.id,\n linkId: item.linkId,\n targetTypeId: item.targetTypeId,\n }))\n )\n\n const existing = await loadEndpointExistence(ctx, collectEndpointLookups(items))\n const valueTypesById = ontology.getValueTypesById()\n\n return runRuntimeItemBatch({\n ctx,\n items,\n expectedObjects: existing.seen.map(expectedRevision),\n plan(item, index) {\n requireEndpoints(item, existing)\n const properties = normalizeRuntimeLink({\n objectType: item.objectType,\n linkDefinition: item.linkDefinition,\n linkId: item.linkId,\n targetTypeId: item.targetTypeId,\n properties: item.properties,\n valueTypesById,\n isValidLinkTarget: (expected, actual) => ontology.isValidLinkTarget(expected, actual),\n })\n const ref = {\n source: { objectTypeId: item.objectType.id, primaryId: item.sourceId },\n linkId: item.linkId,\n target: { objectTypeId: item.targetTypeId, primaryId: item.targetId },\n }\n const edge = linkRefKey(ref)\n return {\n key: edge,\n // The key is a JSON array, which is unreadable in the error an operator sees on a failed\n // link projection. Name the edge the way the object path names an object.\n label: `link '${item.objectType.id}:${item.sourceId}.${item.linkId} -> ${item.targetTypeId}:${item.targetId}'`,\n fingerprint: stableJsonStringify(properties ?? null),\n operations: [\n linkUpsertOperation({\n id: runtimeOperationId(index),\n ref,\n ...(properties !== undefined ? { properties } : {}),\n }),\n ],\n }\n },\n value: () => undefined,\n })\n}\n",
89
+ "/**\n * Leaf operations: delete and restore a single object through the ontology Materializer.\n *\n * Both are thin wrappers over one materializer operation, exactly like `removeLink` — the cascade\n * over links and the effective-state bookkeeping happen inside the commit.\n */\nimport { assertCanEdit } from \"../../authorization\"\nimport type { ExpectedObjectRevision } from \"../../materialization/model\"\nimport { assertCanEditType } from \"../conditional-writes\"\nimport type { ResolvedObjectContext } from \"../context\"\nimport {\n commitRuntimeOperations,\n expectedRevision,\n objectDeleteOperation,\n objectRestoreOperation,\n runtimeOperationId,\n} from \"../materializer-adapter\"\n\n/**\n * Delete the object with this primary id.\n *\n * A missing object is a no-op: the delete records managed authority only where effective state\n * exists, so the commit reports `unchanged` rather than failing. An object a projection also writes\n * stays hidden even while the projection keeps asserting it — `restore()` is what reveals it again.\n */\nexport async function deleteObject(ctx: ResolvedObjectContext, primaryId: string): Promise<void> {\n await assertCanEditType(ctx, ctx.objectType.id)\n await ctx.objectReader.assertReadable({ objectTypeIds: [ctx.objectType.id] })\n const ref = { objectTypeId: ctx.objectType.id, primaryId }\n\n // A writer that views the type through a condition deletes only an object it sees, as it is: a\n // hidden one is deleted as a missing one is, not at all.\n let expected: ExpectedObjectRevision[] = []\n if (ctx.objectReader.viewsThroughCondition(ref.objectTypeId)) {\n const seen = await ctx.objectReader.getByPrimaryId(ref)\n if (!seen) return\n\n expected = [expectedRevision(seen)]\n }\n\n await commitRuntimeOperations(\n ctx,\n [objectDeleteOperation({ id: runtimeOperationId(0), ref })],\n expected\n )\n}\n\n/**\n * Withdraw a previous delete.\n *\n * For an object written only from code this is a no-op — there is nothing left to reveal, so write it\n * again instead. For an object a projection also writes, it makes the projected state visible again.\n *\n * It requires a view of every object of the type: no reader sees a deleted object, so none can\n * show that a condition matches the one it would reveal.\n */\nexport async function restoreObject(ctx: ResolvedObjectContext, primaryId: string): Promise<void> {\n assertCanEdit(ctx, ctx.objectType.id)\n await ctx.objectReader.assertReadable({ objectTypeIds: [ctx.objectType.id] })\n await commitRuntimeOperations(ctx, [\n objectRestoreOperation({\n id: runtimeOperationId(0),\n ref: { objectTypeId: ctx.objectType.id, primaryId },\n }),\n ])\n}\n",
90
+ "/**\n * Leaf operation: upsert a single object through the ontology Materializer.\n */\n\nimport type { ObjectRow } from \"../../storage\"\nimport {\n assertCanEditType,\n expectSeen,\n findWrittenObjects,\n writeFoundObject,\n} from \"../conditional-writes\"\nimport type { ResolvedObjectContext } from \"../context\"\nimport {\n commitRuntimeOperations,\n normalizeRuntimeObject,\n objectUpsertOperation,\n requireEffectiveObject,\n runtimeOperationId,\n toObjectRow,\n} from \"../materializer-adapter\"\n\nexport async function upsertObject(\n ctx: ResolvedObjectContext,\n properties: Record<string, unknown>\n): Promise<ObjectRow> {\n await assertCanEditType(ctx, ctx.objectType.id)\n const { objectType, primaryPropertyId, ontology } = ctx\n const redact = await ctx.objectReader.writtenRowRedactor(objectType.id)\n const checkUniqueValues = await ctx.objectReader.uniqueValueWriteCheck(objectType.id)\n\n const normalized = normalizeRuntimeObject({\n objectType,\n primaryPropertyId,\n properties,\n valueTypesById: ontology.getValueTypesById(),\n })\n checkUniqueValues(normalized.properties)\n const ref = { objectTypeId: objectType.id, primaryId: normalized.primaryId }\n const write = { id: runtimeOperationId(0), ref, properties: normalized.properties }\n\n if (ctx.objectReader.viewsThroughCondition(objectType.id)) {\n // Only an object the writer sees is updated. Anything else is a create, which returns the row\n // as sent: no value of an object the writer did not see is merged into it.\n const found = await findWrittenObjects(ctx, objectType.id, [ref.primaryId])\n const commit = await commitRuntimeOperations(\n ctx,\n [writeFoundObject({ ...write, primaryPropertyId, found: found.get(ref.primaryId) })],\n expectSeen(found.values())\n )\n return redact(toObjectRow(ctx.projectId, requireEffectiveObject(commit.outcomes[0])))\n }\n\n // The Materializer classifies this as an independent create, a patch over source authority, or a\n // restore plus patch inside its own transaction.\n const commit = await commitRuntimeOperations(ctx, [objectUpsertOperation(write)])\n return redact(toObjectRow(ctx.projectId, requireEffectiveObject(commit.outcomes[0])))\n}\n",
91
+ "/**\n * Leaf operation: batch upsert objects of a single type through the ontology Materializer.\n *\n * Everything that survives local normalization is submitted as one ordered continue-mode commit, so\n * later items observe earlier ones and a provider failure rolls the whole batch back.\n */\nimport { stableJsonStringify } from \"../../json\"\nimport type { BatchItemResult } from \"../../runtime/types\"\nimport type { ObjectRow } from \"../../storage\"\nimport {\n assertCanEditType,\n expectSeen,\n findWrittenObjects,\n writeFoundObject,\n} from \"../conditional-writes\"\nimport type { ResolvedObjectContext } from \"../context\"\nimport {\n type NormalizedRuntimeObject,\n normalizeRuntimeObject,\n objectUpsertOperation,\n requireEffectiveObject,\n runtimeOperationId,\n toObjectRow,\n} from \"../materializer-adapter\"\nimport { runRuntimeItemBatch } from \"../runtime-batch\"\n\nexport async function upsertObjectBatch(\n ctx: ResolvedObjectContext,\n items: readonly { properties: Record<string, unknown> }[]\n): Promise<readonly BatchItemResult<ObjectRow>[]> {\n await assertCanEditType(ctx, ctx.objectType.id)\n const { objectType, primaryPropertyId, ontology } = ctx\n const valueTypesById = ontology.getValueTypesById()\n const redact = await ctx.objectReader.writtenRowRedactor(objectType.id)\n const checkUniqueValues = await ctx.objectReader.uniqueValueWriteCheck(objectType.id)\n\n // Normalized up front, so that a writer viewing the type through a condition looks up every id\n // in one read. An item that fails here still fails at its own position.\n const normalized = items.map((item): NormalizedRuntimeObject | { readonly error: unknown } => {\n try {\n const object = normalizeRuntimeObject({\n objectType,\n primaryPropertyId,\n properties: item.properties,\n valueTypesById,\n })\n // Fails this item alone, whatever objects hold: a refusal as taken would answer per value.\n checkUniqueValues(object.properties)\n return object\n } catch (error) {\n return { error }\n }\n })\n\n const found = ctx.objectReader.viewsThroughCondition(objectType.id)\n ? await findWrittenObjects(\n ctx,\n objectType.id,\n normalized.flatMap((object) => (\"error\" in object ? [] : [object.primaryId]))\n )\n : undefined\n\n return runRuntimeItemBatch({\n ctx,\n items,\n ...(found === undefined ? {} : { expectedObjects: expectSeen(found.values()) }),\n plan(_item, index) {\n const object = normalized[index]!\n if (\"error\" in object) throw object.error\n\n const ref = { objectTypeId: objectType.id, primaryId: object.primaryId }\n const write = { id: runtimeOperationId(index), ref, properties: object.properties }\n return {\n // One commit resolves one authority state per object, so two items for the same identity are\n // unambiguous only when they ask for the same thing.\n key: `${ref.objectTypeId}:${ref.primaryId}`,\n label: `object '${ref.objectTypeId}:${ref.primaryId}'`,\n fingerprint: stableJsonStringify(object.properties),\n operations: [\n found === undefined\n ? objectUpsertOperation(write)\n : writeFoundObject({ ...write, primaryPropertyId, found: found.get(ref.primaryId) }),\n ],\n }\n },\n value: ([outcome]) => redact(toObjectRow(ctx.projectId, requireEffectiveObject(outcome))),\n })\n}\n",
92
+ "import { randomUUID } from \"node:crypto\"\nimport { AuthorizationError } from \"../../authorization/errors\"\nimport { MaterializationValidationError } from \"../../materialization/errors\"\nimport type { PreparedObjectVector } from \"../../materialization/vectors\"\nimport { sameEmbeddingModel } from \"../../models/embedding-model\"\nimport { getOntologyMutationRuntime } from \"../../runtime/ontology-mutations\"\nimport { assertCanEditType } from \"../conditional-writes\"\nimport type { ExecutionObjectContext } from \"../context\"\nimport {\n INDEXING_EMBEDDING_TIMEOUT_MS,\n normalizeVector,\n vectorConfiguration,\n vectorSources,\n} from \"./profile\"\nimport type { ObjectVectorHandle } from \"./types\"\n\nexport function createObjectVectorHandle(\n ctx: ExecutionObjectContext,\n primaryId: string,\n profileName: string\n): ObjectVectorHandle {\n const ref = Object.freeze({ objectTypeId: ctx.objectType.id, primaryId })\n const profileDefinition = ctx.ontology.resolveObjectType(ref.objectTypeId).search?.vectors?.[\n profileName\n ]\n if (!profileDefinition)\n throw new MaterializationValidationError(`Unknown vector profile: ${profileName}`)\n const vectors = ctx.storage.ontology.vectors\n if (!vectors)\n throw new MaterializationValidationError(\"Storage does not support vector profiles.\")\n\n const assertReadable = async () => {\n const allowed = await ctx.objectReader.canReadObjectPropertiesBatch({\n items: profileDefinition.source.map((propertyId) => ({ ...ref, propertyId })),\n })\n if (allowed.some((value) => !value))\n throw new AuthorizationError(\n `view:object:${ref.objectTypeId}`,\n \"[Sixb] Vector profile requires access to all its source properties.\"\n )\n }\n\n return Object.freeze({\n async index(): Promise<void> {\n await assertCanEditType(ctx, ref.objectTypeId)\n await assertReadable()\n const mutations = getOntologyMutationRuntime(ctx)\n const model = ctx.embeddingModels?.getByRef({\n provider: profileDefinition.model.providerId,\n modelId: profileDefinition.model.modelId,\n })?.model\n if (!model || !sameEmbeddingModel(model, profileDefinition.model)) {\n throw new MaterializationValidationError(\n `Vector profile '${profileName}' requires its configured embedding model.`\n )\n }\n const row = await ctx.objectReader.getByPrimaryId(ref)\n if (!row) throw new MaterializationValidationError(\"Cannot index a missing object.\")\n const current = (await vectors.list({ projectId: ctx.projectId, ref })).find(\n (entry) => entry.profile === profileName\n )\n const input: PreparedObjectVector = {\n projectId: ctx.projectId,\n ref,\n profile: profileName,\n configuration: vectorConfiguration(profileDefinition),\n ...vectorSources(profileDefinition.source, row.properties),\n expectedObject: { ref, exists: true, version: row.version, lastCommitId: row.lastCommitId },\n expectedVectorCommitId: current?.lastCommitId ?? null,\n }\n\n // Network work never holds a storage transaction or retries an obsolete computation.\n const result = await model.embed({\n texts: [input.text],\n purpose: \"document\",\n signal: AbortSignal.timeout(INDEXING_EMBEDDING_TIMEOUT_MS),\n })\n if (!Array.isArray(result?.vectors) || result.vectors.length !== 1) {\n throw new MaterializationValidationError(\n \"Embedding model must return exactly one vector for one input text.\"\n )\n }\n const values = normalizeVector(\n result.vectors[0]!,\n profileDefinition.model.definition.dimensions\n )\n await assertCanEditType(ctx, ref.objectTypeId)\n await assertReadable()\n await mutations.commitEdits({\n mode: \"atomic\",\n source: { kind: \"runtime\", requestId: randomUUID() },\n operations: [],\n vectorWrites: [{ input, values }],\n expectedObjects: [input.expectedObject],\n expectedLinks: [],\n expectedLinkScopes: [],\n })\n },\n })\n}\n",
93
+ "/**\n * File handle factory for ObjectReadByIdHandle.\n *\n * Opens a `fileRef` property through the object that holds it, the way the object file content\n * route does: the object is read again with the caller's permissions, the FileRef is resolved in\n * that authorized row, then checked against the stored blob before it is opened.\n */\nimport { AuthorizationError } from \"../../authorization/errors\"\nimport { jsonPointerSegment, openFileRef, resolveFileRefAtPath } from \"../../blob-storage/internal\"\nimport type { Property } from \"../../ontology\"\nimport { OntologyValidationError } from \"../../ontology/errors\"\nimport type { PropertyToken } from \"../../ontology/tokens\"\nimport { assertPropertyTokenBelongsToObjectType } from \"../../ontology/validation\"\nimport type { ObjectFileHandle } from \"../../runtime/types\"\nimport type { ObjectSetContext } from \"../context\"\n\nexport function createObjectFileHandle(\n ctx: ObjectSetContext,\n primaryId: string,\n property: PropertyToken<string, string, Property>,\n index?: number\n): ObjectFileHandle {\n const { objectType } = ctx\n assertPropertyTokenBelongsToObjectType(objectType, property)\n const registered = ctx.ontology\n .resolveObjectType(objectType.id)\n .properties.find((candidate) => candidate.id === property.id)\n if (!registered) {\n throw new OntologyValidationError(\n `[Sixb] Unknown property '${property.id}' for object type '${objectType.id}'`\n )\n }\n const path = filePropertyPath(objectType.id, registered, index)\n\n return {\n async open() {\n const row = await ctx.objectReader.getByPrimaryId({ objectTypeId: objectType.id, primaryId })\n if (!row) return null\n if (row.redactions?.[property.id]) {\n // Redacted, so the registered property has a marking the caller is not cleared for.\n const markings = registered.markings ?? []\n const marking =\n markings.find((markingId) => !ctx.authorization?.clearances?.has(markingId)) ??\n markings[0]\n throw new AuthorizationError(\n `clearance:marking:${marking}`,\n `[Sixb] Cannot open file '${objectType.id}.${property.id}': it requires clearance for marking '${marking}'.`\n )\n }\n const fileRef = resolveFileRefAtPath(row, path)\n return fileRef ? openFileRef(ctx.blobStorage, fileRef) : null\n },\n }\n}\n\n/** JSON Pointer to the file in an object row, validated against the property's schema. */\nfunction filePropertyPath(objectTypeId: string, property: Property, index: number | undefined) {\n const { schema } = property\n const name = `${objectTypeId}.${property.id}`\n if (schema === \"fileRef\") {\n if (index !== undefined) {\n throw new OntologyValidationError(`[Sixb] Property ${name} holds one file; omit the index.`)\n }\n return `/properties/${jsonPointerSegment(property.id)}`\n }\n if (typeof schema === \"object\" && schema.type === \"array\" && schema.items === \"fileRef\") {\n if (index === undefined || !Number.isSafeInteger(index) || index < 0) {\n throw new OntologyValidationError(\n `[Sixb] Property ${name} holds a list of files; pass the index of the file to open.`\n )\n }\n return `/properties/${jsonPointerSegment(property.id)}/${index}`\n }\n throw new OntologyValidationError(\n `[Sixb] Property ${name} is not a file: file() takes a \"fileRef\" property or a list of them.`\n )\n}\n",
94
+ "/**\n * Low-level write: append normalized telemetry points through the ontology Materializer.\n *\n * Shared by the batch operation and the per-property appenders in ObjectByIdHandle. The Materializer\n * persists immutable point history, derives latest telemetry state, and writes the commit's outbox\n * facts in one transaction, so this leaf never appends events or writes providers itself.\n */\nimport { randomUUID } from \"node:crypto\"\nimport type { AuthorizationContext } from \"../../authorization\"\nimport { assertCanAppendTelemetry } from \"../../authorization\"\nimport { MaterializationObjectNotFoundError } from \"../../materialization/errors\"\nimport type { TelemetryCommitResult, TelemetryPointWrite } from \"../../materialization/model\"\nimport { getOntologyMutationRuntime } from \"../../runtime/ontology-mutations\"\nimport { ObjectNotFoundError } from \"../../storage/errors\"\nimport type { RuntimeMaterializerContext } from \"../materializer-adapter\"\n\nexport type TelemetryWriteContext = RuntimeMaterializerContext & {\n readonly authorization?: AuthorizationContext\n}\n\nexport async function writeTelemetryBatch(\n ctx: TelemetryWriteContext,\n points: readonly TelemetryPointWrite[]\n): Promise<TelemetryCommitResult | null> {\n // Asserted from the points rather than a resolved context: this leaf is the low-level choke point\n // for both `appendTelemetryBatch` and the per-property `TelemetryChannel`, and only the points know\n // which object types the call actually touches.\n for (const objectTypeId of new Set(points.map((point) => point.series.object.objectTypeId))) {\n assertCanAppendTelemetry(ctx, objectTypeId)\n }\n if (points.length === 0) return null\n\n let commit: TelemetryCommitResult\n try {\n commit = await getOntologyMutationRuntime(ctx).appendTelemetry({\n source: { kind: \"runtime\", requestId: randomUUID() },\n points,\n })\n } catch (error) {\n if (error instanceof MaterializationObjectNotFoundError) {\n throw new ObjectNotFoundError(\n error.objectTypeId,\n error.primaryId,\n \"Object not found for telemetry append\"\n )\n }\n throw error\n }\n return commit\n}\n",
95
+ "/**\n * Leaf operation: batch telemetry append for multiple objects of a single type.\n */\nimport { assertCanAppendTelemetry } from \"../../authorization\"\nimport type { TelemetryPointWrite } from \"../../materialization/model\"\nimport { telemetryPointKey } from \"../../materialization/refs\"\nimport { OntologyValidationError } from \"../../ontology/errors\"\nimport { assertTelemetryProperty } from \"../../ontology/validation\"\nimport type { ResolvedObjectContext } from \"../context\"\nimport { writeTelemetryBatch } from \"./write-batch\"\n\n/**\n * Type guard for telemetry values that carry an explicit unit.\n *\n * Matches only the exact `{ value, unit }` wrapper (a string `unit` and no other\n * keys) so a legitimate JSON/object telemetry value is not silently\n * reinterpreted as value+unit. A fully explicit batch contract (passing units\n * out-of-band like the single-property appender) is tracked as a follow-up;\n * this narrows the heuristic without changing the public batch API.\n */\nfunction isUnitBearingValue(raw: unknown): raw is { value: unknown; unit: string } {\n if (raw === null || typeof raw !== \"object\") {\n return false\n }\n const record = raw as Record<string, unknown>\n return \"value\" in record && typeof record.unit === \"string\" && Object.keys(record).length === 2\n}\n\nexport async function appendTelemetryBatch(\n ctx: ResolvedObjectContext,\n items: readonly {\n id: string\n properties: Record<string, unknown | { value: unknown; unit: string }>\n at?: Date\n }[]\n): Promise<void> {\n // `writeTelemetryBatch` asserts again from the points it receives. Asserting here as well is not\n // redundant: it reports the type by name before any property is resolved, and it still refuses an\n // empty batch, which produces no points to assert over.\n assertCanAppendTelemetry(ctx, ctx.objectType.id)\n const { objectType } = ctx\n // Telemetry identity is `(series, at)`, so a repeated instant inside one call is an upsert: the\n // last value wins rather than failing the whole batch.\n const points = new Map<string, TelemetryPointWrite>()\n\n for (const item of items) {\n const at = (item.at ?? new Date()).toISOString()\n\n for (const [propertyId, rawValue] of Object.entries(item.properties)) {\n const propertyToken = objectType.p[propertyId]\n if (!propertyToken) {\n throw new OntologyValidationError(`Unknown property '${objectType.id}.${propertyId}'`)\n }\n\n assertTelemetryProperty(propertyToken.property)\n\n // Value and unit validation, plus schema normalization, happen inside the Materializer.\n const series = {\n object: { objectTypeId: objectType.id, primaryId: item.id },\n propertyId: propertyToken.id,\n }\n points.set(telemetryPointKey(series, at), {\n series,\n value: isUnitBearingValue(rawValue)\n ? (rawValue.value as TelemetryPointWrite[\"value\"])\n : (rawValue as TelemetryPointWrite[\"value\"]),\n ...(isUnitBearingValue(rawValue) ? { unit: rawValue.unit } : {}),\n at,\n })\n }\n }\n\n await writeTelemetryBatch(ctx, [...points.values()])\n}\n",
96
+ "import { createSixbError } from \"../../errors/internal\"\nimport type { AuthorizedObjectReader } from \"../../execution/authorized-object-reader\"\nimport type {\n TimeseriesHistoryBatchInput,\n TimeseriesHistoryBatchResult,\n TimeseriesHistorySeriesInput,\n TimeseriesPoint,\n TimeseriesStorage,\n} from \"../../storage\"\n\nexport interface TelemetryHistoryOptions {\n readonly storage: TimeseriesStorage\n readonly objectReader: AuthorizedObjectReader\n}\n\nexport type TelemetryHistoryBatchInput = Omit<TimeseriesHistoryBatchInput, \"projectId\">\n\ninterface SnapshotTelemetryHistoryRequest extends TelemetryHistoryBatchInput {\n readonly maxPointOccurrences?: number\n}\n\n/** Read only series selected for the exact object occurrence carried by the nominal reader. */\nexport async function getTelemetryHistoryBatch(\n input: TelemetryHistoryBatchInput,\n options: TelemetryHistoryOptions\n): Promise<readonly TimeseriesHistoryBatchResult[]> {\n // Capture both provider capabilities before reading caller-owned request fields.\n const objectReader = options.objectReader\n const storage = options.storage\n const projectId = objectReader.projectId\n const request = snapshotTelemetryHistoryInput(input, objectReader)\n\n const uniqueSeries = deduplicateSeries(request.series)\n const readableSeries = await selectReadableSeries(uniqueSeries, objectReader)\n const resultsBySeries = await readAndValidateHistory({\n storage,\n projectId,\n request,\n series: readableSeries,\n })\n\n // Objects and telemetry do not share a portable read snapshot. Recheck live selection after\n // all provider-owned values have been detached, before deciding which points to return.\n const releasableSeries =\n readableSeries.length === 0 ? [] : await selectReadableSeries(readableSeries, objectReader)\n const result = assembleHistoryResults({ request, resultsBySeries, releasableSeries })\n objectReader.assertVisibleOutputWithinLimit(result)\n return result\n}\n\n/** Read the latest point only while its exact object property remains selected. */\nexport async function getLatestTelemetryPoint(\n input: TimeseriesHistorySeriesInput,\n options: TelemetryHistoryOptions\n): Promise<TimeseriesPoint | null> {\n const objectReader = options.objectReader\n const storage = options.storage\n const projectId = objectReader.projectId\n const series = snapshotTelemetrySeries(input)\n const readable = await objectReader.canReadObjectProperty(objectPropertySelection(series))\n if (!readable) return visibleLatestResult(null, objectReader)\n\n const rawResult = await storage.getLatest({ projectId, ...series })\n const result = rawResult === null ? null : snapshotProviderPoint(rawResult)\n if (result) assertTimeseriesPointMatchesSeries(projectId, series, result)\n\n // See the batch release check above. Revocation during the timeseries read hides the result.\n const releaseReadable = await objectReader.canReadObjectProperty(objectPropertySelection(series))\n if (!releaseReadable) return visibleLatestResult(null, objectReader)\n\n return visibleLatestResult(result, objectReader)\n}\n\nfunction deduplicateSeries(\n series: readonly TimeseriesHistorySeriesInput[]\n): TimeseriesHistorySeriesInput[] {\n const uniqueSeries = new Map<string, TimeseriesHistorySeriesInput>()\n for (const item of series) {\n const key = seriesKey(item)\n if (!uniqueSeries.has(key)) uniqueSeries.set(key, item)\n }\n return [...uniqueSeries.values()]\n}\n\nasync function selectReadableSeries(\n series: readonly TimeseriesHistorySeriesInput[],\n objectReader: AuthorizedObjectReader\n): Promise<readonly TimeseriesHistorySeriesInput[]> {\n const readable = await objectReader.canReadObjectPropertiesBatch({\n items: series.map(objectPropertySelection),\n })\n return series.filter((_, index) => readable[index] === true)\n}\n\nasync function readAndValidateHistory(input: {\n readonly storage: TimeseriesStorage\n readonly projectId: string\n readonly request: SnapshotTelemetryHistoryRequest\n readonly series: readonly TimeseriesHistorySeriesInput[]\n}): Promise<ReadonlyMap<string, TimeseriesHistoryBatchResult>> {\n const { storage, projectId, request, series } = input\n\n // The provider receives its own detached request. It must never retain or mutate the canonical\n // series snapshot that admission and the final release check rely on.\n const providerRequest = structuredClone({\n projectId,\n series,\n ...(request.from === undefined ? {} : { from: request.from }),\n ...(request.to === undefined ? {} : { to: request.to }),\n ...(request.limitPerSeries === undefined ? {} : { limitPerSeries: request.limitPerSeries }),\n ...(request.order === undefined ? {} : { order: request.order }),\n })\n const stored = series.length === 0 ? [] : await storage.getHistoryBatch(providerRequest)\n\n // Fully detach and validate provider-owned data before the final live check. A provider result\n // may contain accessors or a custom iterator; none of that code may run after release admission.\n if (!Array.isArray(stored)) throw invalidTimeseriesProviderResult()\n const storedCount = stored.length\n if (!Number.isSafeInteger(storedCount) || storedCount > series.length) {\n throw invalidTimeseriesProviderResult()\n }\n const seriesKeys = new Set(series.map(seriesKey))\n const providerResultBySeries = new Map<string, TimeseriesHistoryBatchResult>()\n for (let index = 0; index < storedCount; index += 1) {\n const providerResult = snapshotProviderResult(stored[index]!, request.limitPerSeries)\n const key = seriesKey(providerResult)\n if (providerResultBySeries.has(key) || !seriesKeys.has(key)) {\n throw invalidTimeseriesProviderResult()\n }\n for (const point of providerResult.points) {\n assertTimeseriesPointMatchesSeries(projectId, providerResult, point)\n }\n providerResultBySeries.set(key, providerResult)\n }\n\n return providerResultBySeries\n}\n\n/** Restore request order and duplicates, with independent point copies for every occurrence. */\nfunction assembleHistoryResults(input: {\n readonly request: SnapshotTelemetryHistoryRequest\n readonly resultsBySeries: ReadonlyMap<string, TimeseriesHistoryBatchResult>\n readonly releasableSeries: readonly TimeseriesHistorySeriesInput[]\n}): readonly TimeseriesHistoryBatchResult[] {\n const { request, resultsBySeries, releasableSeries } = input\n const releasableSeriesKeys = new Set(releasableSeries.map(seriesKey))\n const releasedPoints = request.series.map((series) =>\n releasableSeriesKeys.has(seriesKey(series))\n ? (resultsBySeries.get(seriesKey(series))?.points ?? [])\n : []\n )\n const pointOccurrences = releasedPoints.reduce((total, points) => total + points.length, 0)\n if (request.maxPointOccurrences !== undefined && pointOccurrences > request.maxPointOccurrences) {\n throw invalidTimeseriesProviderResult()\n }\n return request.series.map((series, index) => ({\n ...series,\n points: releasedPoints[index]!.map((point) => structuredClone(point)),\n }))\n}\n\nfunction snapshotTelemetrySeries(\n series: TimeseriesHistorySeriesInput\n): TimeseriesHistorySeriesInput {\n if (typeof series !== \"object\" || series === null || Array.isArray(series)) {\n throw new Error(\"[Sixb] Telemetry history series must be an object.\")\n }\n const objectTypeId = telemetryIdentifier(series.objectTypeId, \"objectTypeId\")\n const objectId = telemetryIdentifier(series.objectId, \"objectId\")\n const propertyId = telemetryIdentifier(series.propertyId, \"propertyId\")\n return structuredClone({ objectTypeId, objectId, propertyId })\n}\n\nfunction assertTimeseriesPointMatchesSeries(\n projectId: string,\n series: TimeseriesHistorySeriesInput,\n point: TimeseriesPoint\n): void {\n if (\n typeof point !== \"object\" ||\n point === null ||\n point.projectId !== projectId ||\n point.objectTypeId !== series.objectTypeId ||\n point.objectId !== series.objectId ||\n point.propertyId !== series.propertyId\n ) {\n throw invalidTimeseriesProviderResult()\n }\n}\n\nfunction snapshotTelemetryHistoryInput(\n input: TelemetryHistoryBatchInput,\n objectReader: AuthorizedObjectReader\n): SnapshotTelemetryHistoryRequest {\n const authoredSeries = input.series\n const from = input.from\n const to = input.to\n const limitPerSeries = input.limitPerSeries\n const order = input.order\n if (!Array.isArray(authoredSeries)) {\n throw new Error(\"[Sixb] Telemetry history series must be an array.\")\n }\n if (order !== undefined && order !== \"asc\" && order !== \"desc\") {\n throw new Error(\"[Sixb] Telemetry history order must be 'asc' or 'desc'.\")\n }\n\n // Capture length once and walk by index so proxies cannot change the iteration shape halfway.\n const seriesCount = authoredSeries.length\n const admission = objectReader.admitTelemetryHistoryRead({\n seriesCount,\n ...(limitPerSeries === undefined ? {} : { limitPerSeries }),\n })\n const series: TimeseriesHistorySeriesInput[] = []\n for (let index = 0; index < seriesCount; index += 1) {\n series.push(snapshotTelemetrySeries(authoredSeries[index]!))\n }\n return structuredClone({\n series,\n ...(from === undefined ? {} : { from }),\n ...(to === undefined ? {} : { to }),\n ...(admission.limitPerSeries === undefined ? {} : { limitPerSeries: admission.limitPerSeries }),\n ...(order === undefined ? {} : { order }),\n ...(admission.maxPointOccurrences === undefined\n ? {}\n : { maxPointOccurrences: admission.maxPointOccurrences }),\n })\n}\n\nfunction objectPropertySelection(series: TimeseriesHistorySeriesInput): {\n readonly objectTypeId: string\n readonly primaryId: string\n readonly propertyId: string\n} {\n return {\n objectTypeId: series.objectTypeId,\n primaryId: series.objectId,\n propertyId: series.propertyId,\n }\n}\n\nfunction visibleLatestResult<T extends TimeseriesPoint | null>(\n result: T,\n objectReader: AuthorizedObjectReader\n): T {\n objectReader.assertVisibleOutputWithinLimit(result)\n return result\n}\n\nfunction snapshotProviderResult(\n result: TimeseriesHistoryBatchResult,\n maxPointsPerSeries: number | undefined\n): TimeseriesHistoryBatchResult {\n try {\n if (typeof result !== \"object\" || result === null || Array.isArray(result)) {\n throw invalidTimeseriesProviderResult()\n }\n const series = snapshotTelemetrySeries(result)\n const authoredPoints = result.points\n if (!Array.isArray(authoredPoints)) throw invalidTimeseriesProviderResult()\n const pointCount = authoredPoints.length\n if (\n !Number.isSafeInteger(pointCount) ||\n (maxPointsPerSeries !== undefined && pointCount > maxPointsPerSeries)\n ) {\n throw invalidTimeseriesProviderResult()\n }\n const points: TimeseriesPoint[] = []\n for (let index = 0; index < pointCount; index += 1) {\n points.push(snapshotProviderPoint(authoredPoints[index]!))\n }\n return { ...series, points }\n } catch (error) {\n if (isInvalidTimeseriesProviderResult(error)) throw error\n throw invalidTimeseriesProviderResult(error)\n }\n}\n\nfunction snapshotProviderPoint(point: TimeseriesPoint): TimeseriesPoint {\n try {\n const snapshot = structuredClone(point)\n if (!snapshot || typeof snapshot !== \"object\") throw invalidTimeseriesProviderResult()\n return snapshot\n } catch (error) {\n if (isInvalidTimeseriesProviderResult(error)) throw error\n throw invalidTimeseriesProviderResult(error)\n }\n}\n\nfunction invalidTimeseriesProviderResult(cause?: unknown): Error {\n return createSixbError(\n \"internal.unexpected\",\n \"[Sixb] Timeseries storage returned data outside the requested series.\",\n cause === undefined ? {} : { cause }\n )\n}\n\nfunction isInvalidTimeseriesProviderResult(\n error: unknown\n): error is Error & { readonly code: \"internal.unexpected\" } {\n return (\n error instanceof Error &&\n \"code\" in error &&\n error.code === \"internal.unexpected\" &&\n error.message === \"[Sixb] Timeseries storage returned data outside the requested series.\"\n )\n}\n\nfunction telemetryIdentifier(value: unknown, field: string): string {\n if (typeof value !== \"string\" || !value.trim()) {\n throw new Error(`[Sixb] Telemetry history ${field} must be a non-empty string.`)\n }\n return value\n}\n\nfunction seriesKey(series: TimeseriesHistorySeriesInput): string {\n return JSON.stringify([series.objectTypeId, series.objectId, series.propertyId])\n}\n",
97
+ "/**\n * Telemetry channel factory for ObjectByIdHandle.\n *\n * Creates a per-property channel that writes through the low-level `writeTelemetryBatch` leaf and\n * reads the same series back through `getTelemetryHistoryBatch`, both keyed by the property token.\n */\nimport type { TelemetryPointWrite } from \"../../materialization/model\"\nimport type { ObjectTypeWithPropertyTokens } from \"../../ontology/tokens\"\nimport {\n assertPropertyTokenBelongsToObjectType,\n assertTelemetryProperty,\n} from \"../../ontology/validation\"\nimport { RuntimeError } from \"../../runtime/errors\"\nimport type {\n TelemetryChannel,\n TelemetryHistoryInput,\n TelemetryPropertyToken,\n} from \"../../runtime/types\"\nimport type { ResolvedObjectContext } from \"../context\"\nimport { getTelemetryHistoryBatch, writeTelemetryBatch } from \"../telemetry\"\n\nexport function createTelemetryChannel<TObjectType extends ObjectTypeWithPropertyTokens>(\n ctx: ResolvedObjectContext,\n primaryId: string\n) {\n return <TToken extends TelemetryPropertyToken<TObjectType>>(\n property: TToken\n ): TelemetryChannel<TToken> => {\n const { objectType } = ctx\n assertPropertyTokenBelongsToObjectType(objectType, property)\n assertTelemetryProperty(property.property)\n\n const series = { objectTypeId: objectType.id, objectId: primaryId, propertyId: property.id }\n\n const channel = {\n append: async (input: { value: unknown; unit?: string; at: Date }) => {\n // Value and unit validation, plus schema normalization, happen inside the Materializer.\n await writeTelemetryBatch(ctx, [\n {\n series: {\n object: { objectTypeId: objectType.id, primaryId },\n propertyId: property.id,\n },\n value: input.value as TelemetryPointWrite[\"value\"],\n ...(input.unit !== undefined ? { unit: input.unit } : {}),\n at: input.at.toISOString(),\n },\n ])\n },\n\n history: async (input: TelemetryHistoryInput = {}) => {\n const timeseries = ctx.storage.timeseries\n const objectReader = ctx.objectReader\n if (!timeseries) {\n throw new RuntimeError(\"[Sixb] Reading telemetry requires storage.timeseries support.\")\n }\n\n const from = input.from\n const to = input.to\n const limit = input.limit\n const order = input.order\n\n const [result] = await getTelemetryHistoryBatch(\n {\n series: [series],\n ...(from !== undefined ? { from } : {}),\n ...(to !== undefined ? { to } : {}),\n ...(limit !== undefined ? { limitPerSeries: limit } : {}),\n ...(order !== undefined ? { order } : {}),\n },\n {\n storage: timeseries,\n objectReader,\n }\n )\n\n return (result?.points ?? []).map((point) => ({\n value: point.value,\n at: point.at,\n ...(point.unit !== undefined ? { unit: point.unit } : {}),\n }))\n },\n }\n\n // Cast needed: generic token inference boundary — TToken is narrower than what `channel` sees\n return channel as unknown as TelemetryChannel<TToken>\n }\n}\n",
98
+ "/**\n * ObjectByIdHandle binds operations to a specific object id within an ObjectSet.\n * Created via `sixb.objects(MyType).byId(\"id-1\")`, it provides link/unlink and\n * per-property telemetry appenders with compile-time unit and value type safety.\n */\n\nimport type { ActionDefinition } from \"../../actions\"\nimport type { ObjectLink, ObjectRef, Property } from \"../../ontology\"\nimport { OntologyValidationError } from \"../../ontology/errors\"\nimport type { LinkToken, ObjectTypeWithPropertyTokens, PropertyToken } from \"../../ontology/tokens\"\nimport { assertLinkTokenBelongsToObjectType } from \"../../ontology/validation\"\nimport type { ObjectByIdHandle, TwinObject } from \"../../runtime/types\"\nimport { requestAction as requestActionLeaf } from \"../action\"\nimport type { ObjectSetContext, ResolvedLinkContext } from \"../context\"\nimport { removeLink as removeLinkLeaf, upsertLink as upsertLinkLeaf } from \"../link\"\nimport { deleteObject, restoreObject } from \"../object\"\nimport { createObjectVectorHandle } from \"../vectors/handle\"\nimport { createObjectFileHandle } from \"./file-handle\"\nimport { createTelemetryChannel } from \"./telemetry-channel\"\n\ntype ObjectRefInput = ObjectRef\ntype AnyLinkToken = LinkToken<string, string, string | readonly string[], ObjectLink>\n\nexport function createObjectByIdHandle<TObjectType extends ObjectTypeWithPropertyTokens>(\n ctx: ObjectSetContext,\n primaryId: string\n): ObjectByIdHandle<TObjectType> {\n const objectHandle = {\n vector: (profileName: string) => createObjectVectorHandle(ctx, primaryId, profileName),\n get: async () => {\n const row = await ctx.objectReader.getByPrimaryId({\n objectTypeId: ctx.objectType.id,\n primaryId,\n })\n return row ? (row as unknown as TwinObject<TObjectType>) : null\n },\n\n listLinks: async (linkToken?: AnyLinkToken) => {\n if (linkToken) {\n assertLinkTokenBelongsToObjectType(ctx.objectType, linkToken)\n }\n return ctx.objectReader.listLinks({\n objectTypeId: ctx.objectType.id,\n objectId: primaryId,\n linkId: linkToken?.id,\n })\n },\n\n link: async (\n linkToken: AnyLinkToken,\n target: ObjectRefInput,\n options?: { properties?: Record<string, unknown> }\n ) => {\n assertLinkTokenBelongsToObjectType(ctx.objectType, linkToken)\n\n const linkCtx: ResolvedLinkContext = { ...ctx, linkDefinition: linkToken.link }\n await upsertLinkLeaf(linkCtx, {\n sourceId: primaryId,\n linkId: linkToken.id,\n targetTypeId: target.objectTypeId,\n targetId: target.primaryId,\n properties: options?.properties,\n })\n },\n\n unlink: async (linkToken: AnyLinkToken, target: ObjectRefInput) => {\n assertLinkTokenBelongsToObjectType(ctx.objectType, linkToken)\n\n const linkCtx: ResolvedLinkContext = { ...ctx, linkDefinition: linkToken.link }\n await removeLinkLeaf(linkCtx, {\n sourceId: primaryId,\n linkId: linkToken.id,\n targetTypeId: target.objectTypeId,\n targetId: target.primaryId,\n })\n },\n\n delete: async () => {\n await deleteObject(ctx, primaryId)\n },\n\n restore: async () => {\n await restoreObject(ctx, primaryId)\n },\n\n requestAction: async (input: {\n action?: ActionDefinition\n actionId?: string\n params?: Record<string, unknown>\n runId?: string\n signal?: AbortSignal\n }) => {\n const actionId = input.action?.id ?? input.actionId\n if (!actionId) {\n throw new OntologyValidationError(\n \"[Sixb] requestAction requires either 'action' or 'actionId'\"\n )\n }\n return requestActionLeaf(ctx, {\n primaryId,\n actionId,\n params: input.params,\n options: { runId: input.runId, signal: input.signal },\n })\n },\n\n telemetry: createTelemetryChannel<TObjectType>(ctx, primaryId),\n\n file: (property: PropertyToken<string, string, Property>, index?: number) =>\n createObjectFileHandle(ctx, primaryId, property, index),\n }\n\n return objectHandle as unknown as ObjectByIdHandle<TObjectType>\n}\n",
99
+ "/**\n * Context resolution factories.\n *\n * Resolve ontology identifiers into concrete type data so leaf functions\n * receive all structural information pre-resolved.\n */\n\nimport type { ObjectLink } from \"../../ontology\"\nimport { OntologyNotFoundError } from \"../../ontology/errors\"\nimport type { ObjectTypeWithPropertyTokens } from \"../../ontology/tokens\"\nimport type { SixbRuntimeContext } from \"../../runtime/types\"\nimport type { ResolvedLinkContext, ResolvedObjectContext } from \"./types\"\n\n/** Look up a link definition on an object type, throwing if not found. */\nexport function requireLinkDefinition(\n objectType: ObjectTypeWithPropertyTokens,\n linkId: string\n): ObjectLink {\n const def = objectType.links.find((l) => l.id === linkId)\n if (!def) throw new OntologyNotFoundError(`Unknown link '${objectType.id}.${linkId}'`)\n return def\n}\n\n/**\n * Resolve an object type id to a full ResolvedObjectContext.\n *\n * Uses ontology.resolveObjectType() and getPrimaryPropertyId() — these\n * are structural resolution calls that belong in factories, not leaf functions.\n */\nexport function resolveObjectContext(\n runtime: SixbRuntimeContext,\n objectTypeId: string\n): ResolvedObjectContext {\n const objectType = runtime.ontology.resolveObjectType(objectTypeId)\n const primaryPropertyId = runtime.ontology.getPrimaryPropertyId(objectTypeId)\n return { ...runtime, objectType, primaryPropertyId }\n}\n\n/**\n * Resolve a link id to a full ResolvedLinkContext.\n *\n * Uses requireLinkDefinition to look up the link definition on the\n * already-resolved object type.\n */\nexport function resolveLinkContext(\n objCtx: ResolvedObjectContext,\n linkId: string\n): ResolvedLinkContext {\n const linkDefinition = requireLinkDefinition(objCtx.objectType, linkId)\n return { ...objCtx, linkDefinition }\n}\n",
100
+ "/**\n * Server-side ObjectQueryExecutor backed by the shared query executor and storage.\n * Validation, planning, fallback, and execution all run in-process here; the\n * HTTP executor in `@sixb/client` is the remote counterpart.\n */\n\nimport type { AuthorizedObjectReader } from \"../../execution/authorized-object-reader\"\nimport type { OntologyRegistry } from \"../../ontology\"\nimport { ObjectQueryPlanningError } from \"../query\"\nimport { explainObjectQuery } from \"../query/explain\"\nimport type { ObjectQuery } from \"../query/ir\"\nimport { validateObjectQuery } from \"../query/validate\"\nimport type { ObjectQueryExecutor, ObjectQueryExecutorFacetRequest } from \"./query-executor\"\n\nexport function createRuntimeQueryExecutor(params: {\n ontology: OntologyRegistry\n objectReader: AuthorizedObjectReader\n}): ObjectQueryExecutor {\n const { ontology, objectReader } = params\n\n return {\n async list(query: ObjectQuery, options?: { includeTotal?: boolean; signal?: AbortSignal }) {\n try {\n return await objectReader.executeQuery({\n query,\n includeTotal: options?.includeTotal,\n signal: options?.signal,\n })\n } catch (error) {\n if (error instanceof ObjectQueryPlanningError) {\n throw addSdkPlanningHints(error)\n }\n throw error\n }\n },\n\n async count(query: ObjectQuery) {\n const result = await objectReader.count({ query })\n return result.count\n },\n\n async exists(query: ObjectQuery) {\n const result = await objectReader.exists({ query })\n return result.exists\n },\n\n async facets(query: ObjectQuery, facets: readonly ObjectQueryExecutorFacetRequest[]) {\n const result = await objectReader.facet({ query, facets })\n return {\n total: result.total,\n facets: result.facets.map((facet) => ({\n propertyId: facet.propertyId,\n buckets: [...facet.buckets],\n })),\n }\n },\n\n validate(query: ObjectQuery) {\n return validateObjectQuery(query, { ontology, normalize: false })\n },\n\n explain(query: ObjectQuery) {\n return explainObjectQuery(query, { ontology, normalize: false })\n },\n }\n}\n\nfunction addSdkPlanningHints(error: ObjectQueryPlanningError): ObjectQueryPlanningError {\n if (!error.issues.some((issue) => issue.code === \"fallback_requires_bound\")) return error\n\n return new ObjectQueryPlanningError(\n error.issues.map((issue) =>\n issue.code === \"fallback_requires_bound\"\n ? {\n ...issue,\n message:\n \"Object query fallback requires an explicit result bound. Add .limit(n) or .page({ pageSize: n }) before .list().\",\n }\n : issue\n )\n )\n}\n",
101
+ "/**\n * ObjectSet provides a type-safe collection API for objects of a given type.\n * Created via `sixb.objects(MyType)`, it exposes upsert, query, and telemetry batch operations\n * while preserving compile-time property types inferred from the ontology definition.\n */\n\nimport type { ActionDefinition } from \"../../actions\"\nimport { shareActionRunExecutor } from \"../../actions/run/executor\"\nimport type { AuthorizationContext } from \"../../authorization\"\nimport type { BlobStorage } from \"../../blob-storage\"\nimport { shareSixbErrorReporter } from \"../../error-reporting/capability\"\nimport type { ExecutionContext } from \"../../execution\"\nimport { assertAuthorizedObjectReaderBinding } from \"../../execution/authorized-object-reader\"\nimport { OntologyValidationError } from \"../../ontology/errors\"\nimport type { ObjectTypeWithPropertyTokens, PropertyToken } from \"../../ontology/tokens\"\nimport { assertPropertyTokenBelongsToObjectType } from \"../../ontology/validation\"\nimport { shareOntologyMutationRuntime } from \"../../runtime/ontology-mutations\"\nimport type {\n ObjectSet,\n ObjectSetListInput,\n SixbRuntimeContext,\n TwinObject,\n} from \"../../runtime/types\"\nimport { requestAction as requestActionLeaf } from \"../action\"\nimport type { ObjectSetContext, ResolvedLinkContext } from \"../context\"\nimport { requireLinkDefinition } from \"../context\"\nimport { removeLink as removeLinkLeaf, upsertLink as upsertLinkLeaf } from \"../link\"\nimport { upsertObject as upsertObjectLeaf } from \"../object\"\nimport { appendTelemetryBatch as appendTelemetryBatchLeaf } from \"../telemetry\"\nimport { createObjectByIdHandle } from \"./object-handle\"\nimport { createObjectQueryBuilder } from \"./query-builder\"\nimport { createRuntimeQueryExecutor } from \"./runtime-query-executor\"\n\nexport function createObjectSet<TObjectType extends ObjectTypeWithPropertyTokens>(\n params: SixbRuntimeContext & {\n readonly execution: ExecutionContext\n readonly objectType: TObjectType\n readonly authorization?: AuthorizationContext\n readonly blobStorage: Pick<BlobStorage, \"stat\" | \"open\">\n }\n): ObjectSet<TObjectType> {\n assertAuthorizedObjectReaderBinding({\n reader: params.objectReader,\n scope: { execution: params.execution, authorization: params.runtimeAuthorization },\n })\n const { objectType } = params\n const primaryProp = objectType.properties.find((p) => p.primary)\n if (!primaryProp) {\n throw new OntologyValidationError(`Object type '${objectType.id}' has no primary property`)\n }\n const primaryPropertyId = primaryProp.id\n\n const {\n projectId,\n broker,\n ontology,\n actionRegistry,\n events,\n storage,\n queues,\n objectReader,\n runtimeAuthorization,\n authorization,\n execution,\n } = params\n const queryExecutor = createRuntimeQueryExecutor({\n ontology,\n objectReader,\n })\n\n const resolvedCtx: ObjectSetContext = {\n embeddingModels: params.embeddingModels,\n projectId,\n broker,\n ontology,\n actionRegistry,\n events,\n storage,\n queues,\n objectReader,\n runtimeAuthorization,\n authorization,\n execution,\n blobStorage: params.blobStorage,\n objectType,\n primaryPropertyId,\n }\n shareOntologyMutationRuntime(params, resolvedCtx)\n shareSixbErrorReporter(params, resolvedCtx)\n shareActionRunExecutor(params, resolvedCtx)\n\n const objectSet = {\n get: async (id: string) => {\n const row = await objectReader.getByPrimaryId({\n objectTypeId: objectType.id,\n primaryId: id,\n })\n return row ? (row as unknown as TwinObject<TObjectType>) : null\n },\n\n getBy: async (property: PropertyToken, value: unknown) => {\n assertPropertyTokenBelongsToObjectType(objectType, property)\n const row = await objectReader.getByUniqueValue({\n objectTypeId: objectType.id,\n propertyId: property.id,\n value,\n })\n return row ? (row as unknown as TwinObject<TObjectType>) : null\n },\n\n upsert: async (input: { properties: Record<string, unknown> }) => {\n const row = await upsertObjectLeaf(resolvedCtx, input.properties)\n return row as unknown as TwinObject<TObjectType>\n },\n\n query: () =>\n createObjectQueryBuilder<TObjectType>({\n query: { kind: \"start\", objectTypeId: objectType.id },\n executor: queryExecutor,\n }),\n\n byId: (id: string) => createObjectByIdHandle<TObjectType>(resolvedCtx, id),\n\n list: async (input?: ObjectSetListInput) => {\n const result = await objectReader.list({\n objectTypeId: objectType.id,\n primaryIdPrefix: input?.idPrefix,\n primaryIdSuffix: input?.idSuffix,\n updatedAfter: input?.updatedAfter,\n updatedBefore: input?.updatedBefore,\n createdAfter: input?.createdAfter,\n createdBefore: input?.createdBefore,\n limit: input?.limit,\n offset: input?.offset,\n orderBy: input?.orderBy,\n order: input?.order,\n })\n\n return {\n objects: result.objects.map((row) => row as unknown as TwinObject<TObjectType>),\n hasMore: result.hasMore,\n total: result.total ?? result.objects.length,\n }\n },\n\n appendTelemetryBatch: async (\n items: readonly {\n id: string\n properties: Record<string, unknown | { value: unknown; unit: string }>\n at?: Date\n }[]\n ) => {\n await appendTelemetryBatchLeaf(resolvedCtx, items)\n },\n\n requestAction: async (input: {\n id: string\n action?: ActionDefinition\n actionId?: string\n params?: Record<string, unknown>\n runId?: string\n signal?: AbortSignal\n }) => {\n const actionId = input.action?.id ?? input.actionId\n if (!actionId) {\n throw new OntologyValidationError(\n \"[Sixb] requestAction requires either 'action' or 'actionId'\"\n )\n }\n return requestActionLeaf(resolvedCtx, {\n primaryId: input.id,\n actionId,\n params: input.params,\n options: { runId: input.runId, signal: input.signal },\n })\n },\n\n upsertLink: async (input: {\n sourceId: string\n linkId: string\n targetTypeId: string\n targetId: string\n properties?: Record<string, unknown>\n }) => {\n const linkDefinition = requireLinkDefinition(objectType, input.linkId)\n const linkCtx: ResolvedLinkContext = { ...resolvedCtx, linkDefinition }\n\n await upsertLinkLeaf(linkCtx, {\n sourceId: input.sourceId,\n linkId: input.linkId,\n targetTypeId: input.targetTypeId,\n targetId: input.targetId,\n properties: input.properties,\n })\n },\n\n removeLink: async (input: {\n sourceId: string\n linkId: string\n targetTypeId: string\n targetId: string\n }) => {\n const linkDefinition = requireLinkDefinition(objectType, input.linkId)\n const linkCtx: ResolvedLinkContext = { ...resolvedCtx, linkDefinition }\n\n await removeLinkLeaf(linkCtx, {\n sourceId: input.sourceId,\n linkId: input.linkId,\n targetTypeId: input.targetTypeId,\n targetId: input.targetId,\n })\n },\n }\n\n return objectSet as unknown as ObjectSet<TObjectType>\n}\n",
102
+ "/**\n * Service layer for link operations.\n *\n * Resolves objectTypeId to a typed context and delegates to leaf functions.\n */\nimport type { BatchItemResult, SixbRuntimeContext } from \"../../runtime/types\"\nimport type { ResolvedLinkBatchItem } from \"../context\"\nimport { requireLinkDefinition, resolveLinkContext, resolveObjectContext } from \"../context\"\nimport {\n removeLink as removeLinkLeaf,\n upsertLinkBatch as upsertLinkBatchLeaf,\n upsertLink as upsertLinkLeaf,\n} from \"../link\"\n\nexport async function upsertLink(\n runtime: SixbRuntimeContext,\n objectTypeId: string,\n sourceId: string,\n linkId: string,\n target: { targetTypeId: string; targetId: string; properties?: Record<string, unknown> }\n): Promise<void> {\n const ctx = resolveObjectContext(runtime, objectTypeId)\n const linkCtx = resolveLinkContext(ctx, linkId)\n await upsertLinkLeaf(linkCtx, {\n sourceId,\n linkId,\n targetTypeId: target.targetTypeId,\n targetId: target.targetId,\n properties: target.properties,\n })\n}\n\nexport async function upsertLinkBatch(\n runtime: SixbRuntimeContext,\n items: readonly {\n objectTypeId: string\n sourceId: string\n linkId: string\n target: { targetTypeId: string; targetId: string; properties?: Record<string, unknown> }\n }[]\n): Promise<readonly BatchItemResult<void>[]> {\n const resolvedItems: ResolvedLinkBatchItem[] = items.map((item) => {\n const objectType = runtime.ontology.resolveObjectType(item.objectTypeId)\n const linkDefinition = requireLinkDefinition(objectType, item.linkId)\n return {\n objectType,\n linkDefinition,\n sourceId: item.sourceId,\n linkId: item.linkId,\n targetTypeId: item.target.targetTypeId,\n targetId: item.target.targetId,\n properties: item.target.properties,\n }\n })\n\n return upsertLinkBatchLeaf(runtime, resolvedItems)\n}\n\nexport async function removeLink(\n runtime: SixbRuntimeContext,\n objectTypeId: string,\n sourceId: string,\n linkId: string,\n target: { targetTypeId: string; targetId: string }\n): Promise<void> {\n const ctx = resolveObjectContext(runtime, objectTypeId)\n const linkCtx = resolveLinkContext(ctx, linkId)\n await removeLinkLeaf(linkCtx, {\n sourceId,\n linkId,\n targetTypeId: target.targetTypeId,\n targetId: target.targetId,\n })\n}\n",
103
+ "/**\n * Cross-type object listing for dashboards and search.\n *\n * Type hierarchies are expanded before the request reaches the canonical object\n * reader, which owns authorization and provider-scope enforcement.\n */\n\nimport { resolveRuntimeAuthorizationForProject } from \"../../execution/authorization\"\nimport { getAuthorizedOntologyView } from \"../../execution/authorized-object-reader\"\nimport type { ListResult, SixbRuntimeContext } from \"../../runtime/types\"\nimport type { ObjectRow } from \"../../storage\"\n\nexport interface ListObjectsParams {\n objectTypeIds?: readonly string[]\n idPrefix?: string\n idSuffix?: string\n updatedAfter?: Date\n updatedBefore?: Date\n createdAfter?: Date\n createdBefore?: Date\n limit?: number\n offset?: number\n orderBy?: \"createdAt\" | \"updatedAt\" | \"primaryId\"\n order?: \"asc\" | \"desc\"\n}\n\nexport async function listObjects(\n runtime: SixbRuntimeContext,\n params: ListObjectsParams\n): Promise<ListResult<ObjectRow>> {\n const objectTypeIds = resolveTypeFilter(runtime, params.objectTypeIds)\n\n if (objectTypeIds !== undefined && objectTypeIds.length === 0) {\n return { objects: [], hasMore: false, total: 0 }\n }\n\n const result = await runtime.objectReader.list({\n objectTypeId: objectTypeIds?.length === 1 ? objectTypeIds[0] : objectTypeIds,\n primaryIdPrefix: params.idPrefix,\n primaryIdSuffix: params.idSuffix,\n updatedAfter: params.updatedAfter,\n updatedBefore: params.updatedBefore,\n createdAfter: params.createdAfter,\n createdBefore: params.createdBefore,\n limit: params.limit,\n offset: params.offset,\n orderBy: params.orderBy,\n order: params.order,\n })\n\n return {\n objects: [...result.objects],\n hasMore: result.hasMore,\n total: result.total,\n }\n}\n\nfunction resolveTypeFilter(\n runtime: SixbRuntimeContext,\n requested: readonly string[] | undefined\n): readonly string[] | undefined {\n const ontology =\n resolveRuntimeAuthorizationForProject(runtime).type === \"delegated\"\n ? getAuthorizedOntologyView(runtime.objectReader)\n : runtime.ontology\n if (requested) {\n for (const objectTypeId of requested) {\n ontology.resolveObjectType(objectTypeId)\n }\n }\n\n return requested\n ? [...new Set(requested.flatMap((id) => [id, ...ontology.listSubTypes(id)]))]\n : undefined\n}\n",
104
+ "/**\n * Service layer for object upsert operations.\n *\n * Resolves objectTypeId to a typed context and delegates to leaf functions.\n */\nimport type { BatchItemResult, SixbRuntimeContext } from \"../../runtime/types\"\nimport type { ObjectRow } from \"../../storage\"\nimport { resolveObjectContext } from \"../context\"\nimport {\n upsertObjectBatch as upsertObjectBatchLeaf,\n upsertObject as upsertObjectLeaf,\n} from \"../object\"\n\nexport async function upsertObject(\n runtime: SixbRuntimeContext,\n objectTypeId: string,\n properties: Record<string, unknown>\n): Promise<ObjectRow> {\n return upsertObjectLeaf(resolveObjectContext(runtime, objectTypeId), properties)\n}\n\nexport async function upsertObjectBatch(\n runtime: SixbRuntimeContext,\n objectTypeId: string,\n items: readonly { properties: Record<string, unknown> }[]\n): Promise<readonly BatchItemResult<ObjectRow>[]> {\n return upsertObjectBatchLeaf(resolveObjectContext(runtime, objectTypeId), items)\n}\n",
105
+ "/**\n * Service layer for telemetry operations.\n *\n * Resolves objectTypeId to a typed context and delegates to the leaf function.\n */\nimport type { SixbRuntimeContext } from \"../../runtime/types\"\nimport { resolveObjectContext } from \"../context\"\nimport { appendTelemetryBatch as appendTelemetryBatchLeaf } from \"../telemetry\"\n\nexport async function appendTelemetry(\n runtime: SixbRuntimeContext,\n objectTypeId: string,\n items: readonly { id: string; properties: Record<string, unknown>; at?: Date }[]\n): Promise<void> {\n const ctx = resolveObjectContext(runtime, objectTypeId)\n await appendTelemetryBatchLeaf(ctx, items)\n}\n",
106
+ "import { shareActionRunExecutor } from \"../actions/run/executor\"\nimport type { BlobStorage } from \"../blob-storage\"\nimport { shareSixbErrorReporter } from \"../error-reporting/capability\"\nimport type { ExecutionContext } from \"../execution\"\nimport {\n assertAuthorizedObjectReaderBinding,\n getAuthorizedOntologyView,\n} from \"../execution/authorized-object-reader\"\nimport type { ObjectTypeWithPropertyTokens } from \"../ontology/tokens\"\nimport { assertObjectTypeRegistered } from \"../ontology/validation/properties\"\nimport { shareOntologyMutationRuntime } from \"../runtime/ontology-mutations\"\nimport type {\n ListResult,\n ObjectByIdHandle,\n ObjectReadByIdHandle,\n ObjectReadSet,\n ObjectSet,\n SixbRuntimeContext,\n} from \"../runtime/types\"\nimport type {\n LinkDirection,\n ObjectLinkRow,\n ObjectRow,\n TimeseriesHistoryBatchInput,\n TimeseriesHistoryBatchResult,\n TimeseriesPoint,\n} from \"../storage\"\nimport type {\n ExecuteObjectCountInput,\n ExecuteObjectCountResult,\n ExecuteObjectExistsInput,\n ExecuteObjectExistsResult,\n ExecuteObjectFacetsInput,\n ExecuteObjectFacetsResult,\n ExecuteObjectQueryInput,\n ExecuteObjectQueryLinksInput,\n ExecuteObjectQueryLinksResult,\n ExecuteObjectQueryResult,\n} from \"./query\"\nimport { createObjectSet } from \"./sdk\"\nimport type { ListObjectsParams } from \"./service\"\nimport * as objectService from \"./service\"\nimport { getLatestTelemetryPoint, getTelemetryHistoryBatch } from \"./telemetry\"\n\nexport interface ExecutionObjectOperations {\n listTypes(): readonly ObjectTypeWithPropertyTokens[]\n getTypeById(objectTypeId: string): ObjectTypeWithPropertyTokens | null\n resolveType(objectTypeId: string): ObjectTypeWithPropertyTokens\n getValueTypesById(): ReturnType<SixbRuntimeContext[\"ontology\"][\"getValueTypesById\"]>\n getPrimaryPropertyId(objectTypeId: string): string\n listSubTypes(objectTypeId: string): string[]\n isValidLinkTarget(expected: string | string[], actual: string): boolean\n get(objectTypeId: string, primaryId: string): Promise<ObjectRow | null>\n /** The object of exactly `objectTypeId` holding a unique property's value, or null. */\n getBy(objectTypeId: string, propertyId: string, value: unknown): Promise<ObjectRow | null>\n list(params: ListObjectsParams): Promise<ListResult<ObjectRow>>\n upsert(objectTypeId: string, properties: Record<string, unknown>): Promise<ObjectRow>\n upsertBatch(\n objectTypeId: string,\n items: readonly { properties: Record<string, unknown> }[]\n ): ReturnType<typeof objectService.upsertObjectBatch>\n appendTelemetry(\n objectTypeId: string,\n items: readonly { id: string; properties: Record<string, unknown>; at?: Date }[]\n ): Promise<void>\n upsertLink(\n objectTypeId: string,\n sourceId: string,\n linkId: string,\n target: { targetTypeId: string; targetId: string; properties?: Record<string, unknown> }\n ): Promise<void>\n upsertLinkBatch(\n items: readonly {\n objectTypeId: string\n sourceId: string\n linkId: string\n target: { targetTypeId: string; targetId: string; properties?: Record<string, unknown> }\n }[]\n ): ReturnType<typeof objectService.upsertLinkBatch>\n removeLink(\n objectTypeId: string,\n sourceId: string,\n linkId: string,\n target: { targetTypeId: string; targetId: string }\n ): Promise<void>\n}\n\nexport interface ExecutionObjectByIdHandle<TObjectType extends ObjectTypeWithPropertyTokens>\n extends ObjectReadByIdHandle<TObjectType> {\n vector: ObjectByIdHandle<TObjectType>[\"vector\"]\n requestAction: ObjectByIdHandle<TObjectType>[\"requestAction\"]\n link: ObjectByIdHandle<TObjectType>[\"link\"]\n unlink: ObjectByIdHandle<TObjectType>[\"unlink\"]\n delete: ObjectByIdHandle<TObjectType>[\"delete\"]\n restore: ObjectByIdHandle<TObjectType>[\"restore\"]\n telemetry: ObjectByIdHandle<TObjectType>[\"telemetry\"]\n}\n\nexport interface ExecutionObjectSet<TObjectType extends ObjectTypeWithPropertyTokens>\n extends ObjectReadSet<TObjectType> {\n requestAction: ObjectSet<TObjectType>[\"requestAction\"]\n upsert: ObjectSet<TObjectType>[\"upsert\"]\n upsertLink: ObjectSet<TObjectType>[\"upsertLink\"]\n removeLink: ObjectSet<TObjectType>[\"removeLink\"]\n appendTelemetryBatch: ObjectSet<TObjectType>[\"appendTelemetryBatch\"]\n\n byId(id: string): ExecutionObjectByIdHandle<TObjectType>\n}\n\n/** Public input for querying physical links incident to an object query result. */\nexport type ObjectQueryLinksInput = Omit<ExecuteObjectQueryLinksInput, \"projectId\">\n\n/** Public result returned by {@link ObjectsRuntime.queryLinks}. */\nexport type ObjectQueryLinksResult = ExecuteObjectQueryLinksResult\n\nexport interface ObjectsRuntime extends ExecutionObjectOperations {\n <TObjectType extends ObjectTypeWithPropertyTokens>(\n objectType: TObjectType\n ): ExecutionObjectSet<TObjectType>\n executeQuery(input: Omit<ExecuteObjectQueryInput, \"projectId\">): Promise<ExecuteObjectQueryResult>\n queryLinks(input: ObjectQueryLinksInput): Promise<ObjectQueryLinksResult>\n count(input: Omit<ExecuteObjectCountInput, \"projectId\">): Promise<ExecuteObjectCountResult>\n exists(input: Omit<ExecuteObjectExistsInput, \"projectId\">): Promise<ExecuteObjectExistsResult>\n facet(input: Omit<ExecuteObjectFacetsInput, \"projectId\">): Promise<ExecuteObjectFacetsResult>\n listLinks(input: {\n readonly objectTypeId: string\n readonly objectId: string\n readonly linkId?: string\n readonly direction?: LinkDirection\n }): Promise<readonly ObjectLinkRow[]>\n getTelemetryHistoryBatch(\n input: Omit<TimeseriesHistoryBatchInput, \"projectId\">\n ): Promise<readonly TimeseriesHistoryBatchResult[]>\n getTelemetryHistory(input: {\n readonly objectTypeId: string\n readonly objectId: string\n readonly propertyId: string\n readonly from?: Date\n readonly to?: Date\n readonly limit?: number\n readonly order?: \"asc\" | \"desc\"\n }): Promise<readonly TimeseriesPoint[]>\n getLatestTelemetry(input: {\n readonly objectTypeId: string\n readonly objectId: string\n readonly propertyId: string\n }): Promise<TimeseriesPoint | null>\n}\n\nexport function createObjectsRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n blobStorage: Pick<BlobStorage, \"stat\" | \"open\">\n): ObjectsRuntime {\n const runtimeAuthorization = runtime.runtimeAuthorization\n const objectReader = runtime.objectReader\n assertAuthorizedObjectReaderBinding({\n reader: objectReader,\n scope: { execution, authorization: runtimeAuthorization },\n })\n const authorization = runtime.authorization\n const capturedRuntime: SixbRuntimeContext = {\n projectId: runtime.projectId,\n broker: runtime.broker,\n ontology: runtime.ontology,\n embeddingModels: runtime.embeddingModels,\n actionRegistry: runtime.actionRegistry,\n events: runtime.events,\n storage: runtime.storage,\n queues: runtime.queues,\n runtimeAuthorization,\n objectReader,\n ...(authorization === undefined ? {} : { authorization }),\n }\n shareOntologyMutationRuntime(runtime, capturedRuntime)\n shareSixbErrorReporter(runtime, capturedRuntime)\n shareActionRunExecutor(runtime, capturedRuntime)\n Object.freeze(capturedRuntime)\n const ontologyView = () => getAuthorizedOntologyView(objectReader)\n const objects = Object.assign(\n <TObjectType extends ObjectTypeWithPropertyTokens>(objectType: TObjectType) => {\n assertObjectTypeRegistered(capturedRuntime.ontology.getObjectTypesById(), objectType)\n return createObjectSet<TObjectType>({\n ...capturedRuntime,\n execution,\n objectType,\n blobStorage,\n }) as ExecutionObjectSet<TObjectType>\n },\n {\n listTypes: () => ontologyView().listObjectTypes(),\n getTypeById: (objectTypeId: string) => ontologyView().getObjectTypeById(objectTypeId),\n resolveType: (objectTypeId: string) => ontologyView().resolveObjectType(objectTypeId),\n getValueTypesById: () => ontologyView().getValueTypesById(),\n listSubTypes: (objectTypeId: string) => ontologyView().listSubTypes(objectTypeId),\n isValidLinkTarget: (expected: string | string[], actual: string) =>\n ontologyView().isValidLinkTarget(expected, actual),\n executeQuery: (input: Omit<ExecuteObjectQueryInput, \"projectId\">) =>\n objectReader.executeQuery(input),\n queryLinks: (input: ObjectQueryLinksInput) => objectReader.queryLinks(input),\n count: (input: Omit<ExecuteObjectCountInput, \"projectId\">) => objectReader.count(input),\n exists: (input: Omit<ExecuteObjectExistsInput, \"projectId\">) => objectReader.exists(input),\n facet: (input: Omit<ExecuteObjectFacetsInput, \"projectId\">) => objectReader.facet(input),\n listLinks: async (input: {\n objectTypeId: string\n objectId: string\n linkId?: string\n direction?: LinkDirection\n }) => {\n return objectReader.listLinks(input)\n },\n getTelemetryHistoryBatch: (input: Omit<TimeseriesHistoryBatchInput, \"projectId\">) => {\n const timeseries = capturedRuntime.storage.timeseries\n return getTelemetryHistoryBatch(input, { storage: timeseries, objectReader })\n },\n getTelemetryHistory: async (input: {\n objectTypeId: string\n objectId: string\n propertyId: string\n from?: Date\n to?: Date\n limit?: number\n order?: \"asc\" | \"desc\"\n }) => {\n const timeseries = capturedRuntime.storage.timeseries\n const objectTypeId = input.objectTypeId\n const objectId = input.objectId\n const propertyId = input.propertyId\n const from = input.from\n const to = input.to\n const limit = input.limit\n const order = input.order\n const [result] = await getTelemetryHistoryBatch(\n {\n series: [{ objectTypeId, objectId, propertyId }],\n ...(from === undefined ? {} : { from }),\n ...(to === undefined ? {} : { to }),\n ...(limit === undefined ? {} : { limitPerSeries: limit }),\n ...(order === undefined ? {} : { order }),\n },\n { storage: timeseries, objectReader }\n )\n return result?.points ?? []\n },\n getLatestTelemetry: async (input: {\n objectTypeId: string\n objectId: string\n propertyId: string\n }) => {\n const timeseries = capturedRuntime.storage.timeseries\n const objectTypeId = input.objectTypeId\n const objectId = input.objectId\n const propertyId = input.propertyId\n return getLatestTelemetryPoint(\n { objectTypeId, objectId, propertyId },\n { storage: timeseries, objectReader }\n )\n },\n list: (params: ListObjectsParams) => objectService.listObjects(capturedRuntime, params),\n get: (objectTypeId: string, primaryId: string) =>\n objectReader.getByPrimaryId({ objectTypeId, primaryId }),\n getBy: (objectTypeId: string, propertyId: string, value: unknown) =>\n objectReader.getByUniqueValue({ objectTypeId, propertyId, value }),\n getPrimaryPropertyId: (objectTypeId: string) => {\n return ontologyView().getPrimaryPropertyId(objectTypeId)\n },\n upsert: (objectTypeId: string, properties: Record<string, unknown>) =>\n objectService.upsertObject(capturedRuntime, objectTypeId, properties),\n upsertBatch: (\n objectTypeId: string,\n items: readonly { properties: Record<string, unknown> }[]\n ) => objectService.upsertObjectBatch(capturedRuntime, objectTypeId, items),\n upsertLink: (\n objectTypeId: string,\n sourceId: string,\n linkId: string,\n target: { targetTypeId: string; targetId: string; properties?: Record<string, unknown> }\n ) => objectService.upsertLink(capturedRuntime, objectTypeId, sourceId, linkId, target),\n upsertLinkBatch: (\n items: readonly {\n objectTypeId: string\n sourceId: string\n linkId: string\n target: { targetTypeId: string; targetId: string; properties?: Record<string, unknown> }\n }[]\n ) => objectService.upsertLinkBatch(capturedRuntime, items),\n removeLink: (\n objectTypeId: string,\n sourceId: string,\n linkId: string,\n target: { targetTypeId: string; targetId: string }\n ) => objectService.removeLink(capturedRuntime, objectTypeId, sourceId, linkId, target),\n appendTelemetry: (\n objectTypeId: string,\n items: readonly { id: string; properties: Record<string, unknown>; at?: Date }[]\n ) => objectService.appendTelemetry(capturedRuntime, objectTypeId, items),\n }\n )\n\n return objects as ObjectsRuntime\n}\n",
107
+ "import { assertAuthorized, canViewPipelineRun, isRuntimeAllowed } from \"../authorization\"\nimport type { ExecutionContext } from \"../execution\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type {\n ListLatestPipelineRunsResult,\n ListPipelineRunsInput,\n ListPipelineRunsResult,\n ListPipelineStepRunsInput,\n ListPipelineStepRunsResult,\n PipelineRunRecord,\n} from \"../storage/pipeline-runs\"\nimport { PipelineError } from \"./errors\"\nimport {\n type PipelineRunRequestResult,\n type RequestPipelineRunInput,\n requestPipelineRun,\n} from \"./request\"\nimport type { PipelineDefinition } from \"./types\"\n\nexport interface PipelineRunsRuntime {\n getById(runId: string): Promise<PipelineRunRecord | null>\n list(\n input?: Omit<ListPipelineRunsInput, \"projectId\" | \"pipelineIds\">\n ): Promise<ListPipelineRunsResult>\n listLatest(pipelineIds: readonly string[]): Promise<ListLatestPipelineRunsResult>\n listSteps(\n runId: string,\n input?: Omit<ListPipelineStepRunsInput, \"projectId\" | \"pipelineRunId\">\n ): Promise<ListPipelineStepRunsResult | null>\n}\n\nexport interface PipelinesRuntime {\n list(): readonly PipelineDefinition[]\n getById(pipelineId: string): PipelineDefinition | null\n request(input: RequestPipelineRunInput): Promise<PipelineRunRequestResult>\n readonly runs: PipelineRunsRuntime\n}\n\nexport function createPipelinesRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n source: Pick<PipelinesRuntime, \"list\" | \"getById\">\n): PipelinesRuntime {\n const authority = resolveRuntimeAuthorizationForProject(runtime)\n const allowed = (pipelineId: string) =>\n isRuntimeAllowed(runtime, { kind: \"pipeline.run\", pipelineId })\n const visibleIds = () =>\n source\n .list()\n .filter((pipeline) => allowed(pipeline.id))\n .map((pipeline) => pipeline.id)\n const historyFilterIds = () =>\n authority.type === \"unrestricted\"\n ? undefined\n : authority.type === \"principal\"\n ? visibleIds()\n : []\n\n const getRun = async (runId: string) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const run =\n (await runtime.storage.pipelineRuns?.getById({\n projectId: runtime.projectId,\n id: runId,\n })) ?? null\n if (!run) return null\n return authority.type === \"unrestricted\" || canViewPipelineRun(authority.context, run)\n ? run\n : null\n }\n\n return {\n list: () =>\n authority.type === \"denied\" || authority.type === \"delegated\"\n ? []\n : source.list().filter((pipeline) => allowed(pipeline.id)),\n getById: (pipelineId) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const pipeline = source.getById(pipelineId)\n return pipeline && allowed(pipelineId) ? pipeline : null\n },\n request: async (input) => {\n assertAuthorized(runtime, { kind: \"pipeline.run\", pipelineId: input.pipelineId })\n const pipeline = source.getById(input.pipelineId)\n if (!pipeline) throw new PipelineError(`[Sixb] Unknown pipeline '${input.pipelineId}'`)\n return requestPipelineRun(runtime, execution, pipeline, input)\n },\n runs: {\n getById: getRun,\n list: (input = {}) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") {\n return Promise.resolve({ runs: [], hasMore: false, total: 0 })\n }\n const storage = runtime.storage.pipelineRuns\n if (!storage) return Promise.resolve({ runs: [], hasMore: false, total: 0 })\n return storage.list({\n ...input,\n pipelineIds: historyFilterIds(),\n projectId: runtime.projectId,\n })\n },\n listLatest: (pipelineIds) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") {\n return Promise.resolve({ runs: [] })\n }\n const storage = runtime.storage.pipelineRuns\n if (!storage || pipelineIds.length === 0) return Promise.resolve({ runs: [] })\n const allowedIds = pipelineIds.filter(allowed)\n return allowedIds.length === 0\n ? Promise.resolve({ runs: [] })\n : storage.listLatestByPipelineIds({\n projectId: runtime.projectId,\n pipelineIds: allowedIds,\n })\n },\n listSteps: async (runId, input = {}) => {\n const storage = runtime.storage.pipelineRuns\n if (!storage || !(await getRun(runId))) return null\n return storage.listSteps({\n ...input,\n pipelineRunId: runId,\n projectId: runtime.projectId,\n })\n },\n },\n }\n}\n",
108
+ "import { canViewProjection, canViewProjectionRun } from \"../authorization\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type {\n ListLatestProjectionRunsResult,\n ListProjectionRunsInput,\n ListProjectionRunsResult,\n ProjectionRunRecord,\n} from \"../storage/projection-runs\"\nimport type { ProjectionDefinitionCatalog } from \"./registry\"\nimport type {\n LinkProjectionDefinition,\n ObjectProjectionDefinition,\n ProjectionDefinition,\n TelemetryProjectionDefinition,\n} from \"./types\"\n\nexport interface ProjectionRunsRuntime {\n getById(runId: string): Promise<ProjectionRunRecord | null>\n list(\n input?: Omit<ListProjectionRunsInput, \"projectId\" | \"objectTypeIds\">\n ): Promise<ListProjectionRunsResult>\n listLatest(projectionIds: readonly string[]): Promise<ListLatestProjectionRunsResult>\n}\n\nexport interface ProjectionsRuntime {\n list(): readonly ProjectionDefinition[]\n listObjects(): readonly ObjectProjectionDefinition[]\n listLinks(): readonly LinkProjectionDefinition[]\n listTelemetry(): readonly TelemetryProjectionDefinition[]\n getById(projectionId: string): ProjectionDefinition | null\n readonly runs: ProjectionRunsRuntime\n}\n\nexport function createProjectionsRuntime(\n runtime: SixbRuntimeContext,\n source: ProjectionDefinitionCatalog\n): ProjectionsRuntime {\n const authority = resolveRuntimeAuthorizationForProject(runtime)\n const listVisible = <TProjection extends ProjectionDefinition>(\n list: () => readonly TProjection[]\n ): readonly TProjection[] => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return []\n case \"principal\":\n return list().filter((projection) => canViewProjection(authority.context, projection))\n case \"unrestricted\":\n return [...list()]\n }\n }\n const visible = (projection: ProjectionDefinition) => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return false\n case \"principal\":\n return canViewProjection(authority.context, projection)\n case \"unrestricted\":\n return true\n }\n }\n const visibleIds = (projectionIds: readonly string[]) =>\n projectionIds.filter((projectionId) => {\n const projection = source.getById(projectionId)\n return projection !== null && visible(projection)\n })\n\n return {\n list: () => listVisible(() => source.list()),\n listObjects: () => listVisible(() => source.listObjects()),\n listLinks: () => listVisible(() => source.listLinks()),\n listTelemetry: () => listVisible(() => source.listTelemetry()),\n getById: (projectionId) => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return null\n case \"principal\":\n case \"unrestricted\":\n break\n }\n const projection = source.getById(projectionId)\n return projection && visible(projection) ? projection : null\n },\n runs: {\n getById: async (runId) => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return null\n case \"principal\":\n case \"unrestricted\":\n break\n }\n const run =\n (await runtime.storage.projectionRuns?.getById({\n projectId: runtime.projectId,\n id: runId,\n })) ?? null\n if (!run) return null\n return authority.type === \"unrestricted\" ||\n canViewProjectionRun(authority.context, run.target)\n ? run\n : null\n },\n list: (input = {}) => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return Promise.resolve({ runs: [], hasMore: false, total: 0 })\n case \"principal\":\n case \"unrestricted\":\n break\n }\n const storage = runtime.storage.projectionRuns\n if (!storage) return Promise.resolve({ runs: [], hasMore: false, total: 0 })\n return storage.list({\n ...input,\n objectTypeIds:\n authority.type === \"principal\"\n ? [...authority.context.grants[\"view:object\"]]\n : undefined,\n projectId: runtime.projectId,\n })\n },\n listLatest: (projectionIds) => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return Promise.resolve({ runs: [] })\n case \"principal\":\n case \"unrestricted\":\n break\n }\n const storage = runtime.storage.projectionRuns\n if (!storage || projectionIds.length === 0) return Promise.resolve({ runs: [] })\n const ids = visibleIds(projectionIds)\n return ids.length === 0\n ? Promise.resolve({ runs: [] })\n : storage.listLatestByProjectionIds({ projectId: runtime.projectId, projectionIds: ids })\n },\n },\n }\n}\n",
109
+ "import { isRuntimeAllowed } from \"../authorization\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport { readerClearance, readerViewConditions } from \"../execution/authorized-object-reader\"\nimport type { DefinitionCatalog } from \"../runtime/definitions\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type { ListActiveRuleStatesInput, ListActiveRuleStatesResult } from \"../storage/rules\"\nimport type { RuleDefinition } from \"./types\"\n\nexport interface RuleStatesRuntime {\n list(\n input?: Omit<ListActiveRuleStatesInput, \"projectId\" | \"objectTypeIds\">\n ): Promise<ListActiveRuleStatesResult>\n}\n\nexport interface RulesRuntime {\n list(): readonly RuleDefinition[]\n getById(ruleId: string): RuleDefinition | null\n readonly states: RuleStatesRuntime\n}\n\nexport function createRulesRuntime(\n runtime: SixbRuntimeContext,\n source: DefinitionCatalog<RuleDefinition>\n): RulesRuntime {\n const authority = resolveRuntimeAuthorizationForProject(runtime)\n\n // A rule on a type the reader views under a condition shows: the reader sees some of its objects.\n const visible = (rule: RuleDefinition) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return false\n\n const objectTypeId = rule.subject.objectTypeId\n return (\n isRuntimeAllowed(runtime, { kind: \"object.view\", objectTypeId }) ||\n readerViewConditions(runtime.objectReader).has(objectTypeId)\n )\n }\n\n return {\n list: () =>\n authority.type === \"denied\" || authority.type === \"delegated\"\n ? []\n : source.list().filter(visible),\n getById: (ruleId) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const rule = source.getById(ruleId)\n return rule && visible(rule) ? rule : null\n },\n states: {\n list: async (input = {}) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") {\n return { states: [], hasMore: false, total: 0 }\n }\n const storage = runtime.storage.rules\n if (!storage) return { states: [], hasMore: false, total: 0 }\n if (authority.type === \"unrestricted\") {\n return storage.listActive({ ...input, projectId: runtime.projectId })\n }\n\n // A state names its subject's id: it shows where the reader could read that subject, under\n // the markings of the versions projections applied too.\n const clearance = await readerClearance(runtime.objectReader)\n\n // Storage cannot tell which objects of a type viewed under a condition the reader sees, so\n // their matches list one object at a time, once the reader reads it. A listing that names\n // no object leaves them out: it lists only the types the reader views whole.\n const { objectTypeId, primaryId } = input\n const conditions = readerViewConditions(runtime.objectReader)\n if (objectTypeId !== undefined && primaryId !== undefined && conditions.has(objectTypeId)) {\n if (conditions.get(objectTypeId)!.hiddenBy(clearance)) {\n return { states: [], hasMore: false, total: 0 }\n }\n\n const object = await runtime.objectReader.getByPrimaryId({ objectTypeId, primaryId })\n if (!object) return { states: [], hasMore: false, total: 0 }\n\n return storage.listActive({\n ...input,\n objectTypeIds: [objectTypeId],\n projectId: runtime.projectId,\n })\n }\n\n return storage.listActive({\n ...input,\n objectTypeIds: [...authority.context.grants[\"view:object\"]].filter(\n (objectTypeId) => clearance?.unreadableType(objectTypeId) === undefined\n ),\n projectId: runtime.projectId,\n })\n },\n },\n }\n}\n",
110
+ "import { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport type { DefinitionCatalog } from \"../runtime/definitions\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type { ScheduleDefinition } from \"./types\"\n\n/** Schedule definitions visible to an execution; process lifecycle remains on the host. */\nexport type SchedulesRuntime = DefinitionCatalog<ScheduleDefinition>\n\nexport function createSchedulesRuntime(\n runtime: SixbRuntimeContext,\n schedules: DefinitionCatalog<ScheduleDefinition>\n): SchedulesRuntime {\n const authority = resolveRuntimeAuthorizationForProject(runtime)\n return {\n list: () => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return []\n case \"principal\":\n case \"unrestricted\":\n return schedules.list()\n }\n },\n getById: (scheduleId) => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return null\n case \"principal\":\n case \"unrestricted\":\n return schedules.getById(scheduleId)\n }\n },\n }\n}\n",
111
+ "import { createHash, randomBytes, randomUUID } from \"node:crypto\"\nimport { AuthorizationError, assertAuthorized, isRuntimeAllowed } from \"../authorization\"\nimport type { AuthorizablePrincipal, ExecutionContext } from \"../execution\"\nimport { resolveExecutionScopeAuthorization } from \"../execution/authorization\"\nimport type { ObjectRef } from \"../ontology\"\nimport type { DefinitionCatalog } from \"../runtime/definitions\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport { ObjectNotFoundError, type ShareGrantRecord, ShareGrantStorageError } from \"../storage\"\nimport { compileSelectedObjectReadScope } from \"../storage/objects/read-scope\"\nimport { objectReadScopeForAccessPlan, type ShareAccessPlan } from \"./access-plan\"\nimport { compileShareAccessPlan } from \"./compiler\"\nimport type { ShareDefinition } from \"./types\"\n\nconst MAX_CREATE_ATTEMPTS = 5\n\nexport type ShareErrorReason =\n | \"invalid_input\"\n | \"not_found\"\n | \"unauthenticated\"\n | \"storage_unavailable\"\n | \"storage_failure\"\n\nexport class ShareError extends Error {\n readonly name = \"ShareError\"\n\n constructor(\n readonly reason: ShareErrorReason,\n message: string,\n options?: ErrorOptions\n ) {\n super(message, options)\n }\n}\n\ntype ShareTargetObjectTypeId<TDefinition extends ShareDefinition> =\n TDefinition[\"target\"][\"objectTypeId\"]\n\n/** Public lifecycle view. Durable secrets and authority internals never cross this boundary. */\nexport type SharedAccessGrant = Omit<\n ShareGrantRecord,\n \"projectId\" | \"authoritySnapshot\" | \"authorityDigest\" | \"tokenHash\"\n>\n\nexport interface SharedAccessInvitation {\n readonly grant: SharedAccessGrant\n /** Returned once. Storage retains only its SHA-256 digest. */\n readonly secret: string\n}\n\nexport interface IssueSharedAccessInput<TDefinition extends ShareDefinition = ShareDefinition> {\n readonly target: ObjectRef<NoInfer<ShareTargetObjectTypeId<TDefinition>>>\n readonly destinationPath: string\n readonly expiresAt: Date\n}\n\nexport interface IssueSharedAccessByIdInput extends IssueSharedAccessInput {\n readonly definitionId: string\n}\n\nexport interface ListSharedAccessInput<TDefinition extends ShareDefinition = ShareDefinition> {\n readonly target?: ObjectRef<NoInfer<ShareTargetObjectTypeId<TDefinition>>>\n readonly includeRevoked?: boolean\n readonly includeExpired?: boolean\n readonly limit?: number\n readonly offset?: number\n}\n\nexport interface ListSharedAccessByIdInput extends Omit<ListSharedAccessInput, \"target\"> {\n readonly definitionId: string\n /** Filter within the definition's target Object Type. */\n readonly primaryId?: string\n}\n\nexport interface SharedAccessGrantListResult {\n readonly grants: readonly SharedAccessGrant[]\n readonly total: number\n readonly hasMore: boolean\n}\n\nexport interface SharesRuntime {\n listDefinitions(): readonly ShareDefinition[]\n getDefinitionById(definitionId: string): ShareDefinition | null\n issue<const TDefinition extends ShareDefinition>(\n definition: TDefinition,\n input: IssueSharedAccessInput<TDefinition>\n ): Promise<SharedAccessInvitation>\n issueById(input: IssueSharedAccessByIdInput): Promise<SharedAccessInvitation>\n list<const TDefinition extends ShareDefinition>(\n definition: TDefinition,\n input?: ListSharedAccessInput<TDefinition>\n ): Promise<SharedAccessGrantListResult>\n listById(input: ListSharedAccessByIdInput): Promise<SharedAccessGrantListResult>\n revoke(grantId: string): Promise<SharedAccessGrant | null>\n}\n\nexport function createSharesRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n definitions: DefinitionCatalog<ShareDefinition>\n): SharesRuntime {\n const managementPrincipal = (): AuthorizablePrincipal => {\n const authority = resolveExecutionScopeAuthorization(runtime.projectId, {\n execution,\n authorization: runtime.runtimeAuthorization,\n })\n if (authority.type !== \"principal\" || authority.context.principal.type === \"system\") {\n throw new ShareError(\n \"unauthenticated\",\n \"[Sixb] Shared access grants require user or service-account authority.\"\n )\n }\n return {\n type: authority.context.principal.type,\n id: authority.context.principal.id,\n }\n }\n\n const canManage = (shareId: string): boolean => {\n try {\n managementPrincipal()\n return isRuntimeAllowed(runtime, { kind: \"share.manage\", shareId })\n } catch {\n return false\n }\n }\n\n const resolveManageableDefinition = (definitionId: unknown): ShareDefinition => {\n const id = validDefinitionId(definitionId)\n managementPrincipal()\n // Authorize the opaque id before resolving it so callers without `can.share` cannot use the\n // 403/404 distinction as a Share-definition existence oracle.\n assertCanManage(runtime, id)\n return resolveDefinition(definitions, id)\n }\n\n const issueByDefinition = async (\n definition: ShareDefinition,\n input: IssueSharedAccessInput\n ): Promise<SharedAccessInvitation> => {\n assertInputObject(input, \"Shared access issue input\")\n const issuer = managementPrincipal()\n assertCanManage(runtime, definition.id)\n const storage = requireShareStorage(runtime)\n const createdAt = new Date()\n const expiresAt = validFutureDate(input.expiresAt, createdAt)\n const target = exactTarget(definition, input.target)\n const access = compileShareAccessPlan({\n share: definition,\n target,\n ontology: runtime.ontology,\n actions: runtime.actionRegistry,\n })\n\n // A link keeps showing whatever its target links to, now and later: on a type its issuer sees\n // only through a condition, it would expose the objects that condition hides. Each type its\n // links reach must be viewed whole.\n assertViewsWhole(runtime, definition, issuer, linkedObjectTypeIds(access))\n\n // This canonical read checks both the caller's current object authority and target existence.\n // A target its issuer sees through a condition must be visible now; a hidden one is not found,\n // like a missing one. The link then holds its own grants: it keeps showing the target even\n // once the target stops matching the issuer's condition.\n const object = await runtime.objectReader.getByPrimaryId({\n objectTypeId: target.objectTypeId,\n primaryId: target.primaryId,\n })\n if (!object) {\n throw new ObjectNotFoundError(target.objectTypeId, target.primaryId, \"Share target not found\")\n }\n\n const authoritySnapshot = { version: 1 as const, access }\n\n for (let attempt = 0; attempt < MAX_CREATE_ATTEMPTS; attempt += 1) {\n const secret = randomBytes(32).toString(\"base64url\")\n try {\n const grant = await storage.create({\n id: `shr_${randomUUID()}`,\n projectId: runtime.projectId,\n definitionId: definition.id,\n target,\n issuedBy: issuer,\n authoritySnapshot,\n tokenHash: sha256(secret),\n destinationPath: input.destinationPath,\n createdAt,\n expiresAt,\n })\n return { grant: publicGrant(grant), secret }\n } catch (error) {\n if (error instanceof ShareGrantStorageError && error.code === \"invalid_input\") {\n throw new ShareError(\"invalid_input\", error.message, { cause: error })\n }\n if (\n !(error instanceof ShareGrantStorageError) ||\n error.code !== \"duplicate\" ||\n attempt === MAX_CREATE_ATTEMPTS - 1\n ) {\n throw storageFailure(\"issue\", error)\n }\n }\n }\n\n throw storageFailure(\"issue\")\n }\n\n const listByDefinition = async (\n definition: ShareDefinition,\n input: ListSharedAccessInput = {}\n ): Promise<SharedAccessGrantListResult> => {\n assertInputObject(input, \"Shared access list input\")\n managementPrincipal()\n assertCanManage(runtime, definition.id)\n const storage = requireShareStorage(runtime)\n const target = input.target === undefined ? undefined : exactTarget(definition, input.target)\n try {\n const result = await storage.list({\n projectId: runtime.projectId,\n definitionId: definition.id,\n ...(target === undefined ? {} : { target }),\n includeRevoked: input.includeRevoked,\n includeExpired: input.includeExpired,\n now: new Date(),\n limit: input.limit,\n offset: input.offset,\n })\n return { ...result, grants: result.grants.map(publicGrant) }\n } catch (error) {\n if (error instanceof ShareGrantStorageError && error.code === \"invalid_input\") {\n throw new ShareError(\"invalid_input\", error.message, { cause: error })\n }\n throw storageFailure(\"list\", error)\n }\n }\n\n return {\n listDefinitions: () => definitions.list().filter((definition) => canManage(definition.id)),\n getDefinitionById: (definitionId) => {\n const definition = definitions.getById(definitionId)\n return definition && canManage(definition.id) ? definition : null\n },\n async issue(definition, input) {\n return issueByDefinition(\n resolveManageableDefinition(definitionIdFromReference(definition)),\n input\n )\n },\n async issueById(input) {\n assertInputObject(input, \"Shared access issue input\")\n return issueByDefinition(resolveManageableDefinition(input.definitionId), input)\n },\n async list(definition, input) {\n return listByDefinition(\n resolveManageableDefinition(definitionIdFromReference(definition)),\n input\n )\n },\n async listById(input) {\n assertInputObject(input, \"Shared access list input\")\n const definition = resolveManageableDefinition(input.definitionId)\n const { primaryId, includeRevoked, includeExpired, limit, offset } = input\n return listByDefinition(definition, {\n ...(primaryId === undefined\n ? {}\n : {\n target: {\n objectTypeId: definition.target.objectTypeId,\n primaryId,\n },\n }),\n includeRevoked,\n includeExpired,\n limit,\n offset,\n })\n },\n revoke: async (grantId) => {\n const actor = managementPrincipal()\n const storage = requireShareStorage(runtime)\n if (typeof grantId !== \"string\" || !grantId.trim()) {\n throw new ShareError(\"invalid_input\", \"[Sixb] Shared access grant id must not be empty.\")\n }\n let current: ShareGrantRecord | null\n try {\n current = await storage.getById({ projectId: runtime.projectId, id: grantId })\n } catch (error) {\n throw storageFailure(\"load for revocation\", error)\n }\n if (!current) return null\n // Do not turn grant ids into an existence oracle. Missing definitions and grants outside the\n // caller's management authority are indistinguishable from missing grants.\n if (!definitions.getById(current.definitionId) || !canManage(current.definitionId)) {\n return null\n }\n try {\n const revoked = await storage.revoke({\n projectId: runtime.projectId,\n id: grantId,\n revokedAt: new Date(),\n revokedBy: actor,\n })\n return revoked ? publicGrant(revoked) : null\n } catch (error) {\n throw storageFailure(\"revoke\", error)\n }\n },\n }\n}\n\nfunction definitionIdFromReference(value: unknown): unknown {\n return typeof value === \"object\" && value !== null\n ? (value as { readonly id?: unknown }).id\n : undefined\n}\n\nfunction assertInputObject(value: unknown, label: string): asserts value is object {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ShareError(\"invalid_input\", `[Sixb] ${label} must be an object.`)\n }\n}\n\nfunction resolveDefinition(\n definitions: DefinitionCatalog<ShareDefinition>,\n definitionId: unknown\n): ShareDefinition {\n const id = validDefinitionId(definitionId)\n const definition = definitions.getById(id)\n if (!definition) {\n throw new ShareError(\"not_found\", `[Sixb] Unknown Share definition '${id}'.`)\n }\n return definition\n}\n\nfunction validDefinitionId(value: unknown): string {\n if (typeof value !== \"string\" || !value.trim()) {\n throw new ShareError(\"invalid_input\", \"[Sixb] Share definition id must not be empty.\")\n }\n return value\n}\n\nfunction assertCanManage(runtime: SixbRuntimeContext, shareId: string): void {\n assertAuthorized(runtime, { kind: \"share.manage\", shareId })\n}\n\n/** Every object type a Share's links reach from its target, nested links included. */\nfunction linkedObjectTypeIds(access: ShareAccessPlan): readonly string[] {\n const { steps } = compileSelectedObjectReadScope(objectReadScopeForAccessPlan(access))\n return [...new Set(steps.map((step) => step.targetObjectTypeId))]\n}\n\n/** Refuse links reaching a type the issuer views only through a condition, or not at all. */\nfunction assertViewsWhole(\n runtime: SixbRuntimeContext,\n definition: ShareDefinition,\n issuer: AuthorizablePrincipal,\n objectTypeIds: readonly string[]\n): void {\n const partial = objectTypeIds.filter(\n (objectTypeId) => !isRuntimeAllowed(runtime, { kind: \"object.view\", objectTypeId })\n )\n if (partial.length === 0) return\n\n const types = partial.map((objectTypeId) => `'${objectTypeId}'`).join(\", \")\n throw new AuthorizationError(\n `view:object:${partial[0]}`,\n `[Sixb] Principal '${issuer.id}' cannot issue Share '${definition.id}', whose links show every object of ${types} they reach: the principal views these types only through a condition, or not at all. Grant can.view() on them without a condition, or leave their links out of the Share.`\n )\n}\n\nfunction requireShareStorage(runtime: SixbRuntimeContext) {\n const storage = runtime.storage.shareGrants\n if (!storage) {\n throw new ShareError(\n \"storage_unavailable\",\n \"[Sixb] Share grant storage is not configured on this runtime.\"\n )\n }\n return storage\n}\n\nfunction exactTarget(definition: ShareDefinition, value: unknown): ObjectRef {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ShareError(\"invalid_input\", \"[Sixb] Share target must be an exact object reference.\")\n }\n const objectTypeId = (value as { readonly objectTypeId?: unknown }).objectTypeId\n const primaryId = (value as { readonly primaryId?: unknown }).primaryId\n if (typeof objectTypeId !== \"string\" || typeof primaryId !== \"string\" || !primaryId.trim()) {\n throw new ShareError(\"invalid_input\", \"[Sixb] Share target must be an exact object reference.\")\n }\n if (objectTypeId !== definition.target.objectTypeId) {\n throw new ShareError(\n \"invalid_input\",\n `[Sixb] Share '${definition.id}' targets '${definition.target.objectTypeId}', not '${objectTypeId}'.`\n )\n }\n return Object.freeze({ objectTypeId, primaryId })\n}\n\nfunction validFutureDate(value: unknown, now: Date): Date {\n if (!(value instanceof Date) || !Number.isFinite(value.getTime()) || value <= now) {\n throw new ShareError(\n \"invalid_input\",\n \"[Sixb] Shared access expiry must be a valid future date.\"\n )\n }\n return new Date(value)\n}\n\nfunction sha256(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\")\n}\n\nfunction publicGrant(record: ShareGrantRecord): SharedAccessGrant {\n const {\n projectId: _projectId,\n authoritySnapshot: _authoritySnapshot,\n authorityDigest: _authorityDigest,\n tokenHash: _tokenHash,\n ...grant\n } = record\n return structuredClone(grant)\n}\n\nfunction storageFailure(operation: string, cause?: unknown): ShareError {\n return new ShareError(\"storage_failure\", `[Sixb] Share grant storage failed to ${operation}.`, {\n cause,\n })\n}\n",
112
+ "import { assertAuthorized, isRuntimeAllowed } from \"../authorization\"\nimport type { ExecutionContext } from \"../execution\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type {\n ListLatestSyncRunsResult,\n ListSyncRunsInput,\n ListSyncRunsResult,\n SyncRunRecord,\n} from \"../storage/sync-runs\"\nimport { SyncValidationError } from \"./errors\"\nimport { type RequestSyncRunInput, requestSyncRun, type SyncRunRequestResult } from \"./request\"\nimport type { SyncDefinition } from \"./types\"\n\nexport interface SyncRunsRuntime {\n getById(runId: string): Promise<SyncRunRecord | null>\n list(input?: Omit<ListSyncRunsInput, \"projectId\" | \"syncIds\">): Promise<ListSyncRunsResult>\n listLatest(syncIds: readonly string[]): Promise<ListLatestSyncRunsResult>\n}\n\nexport interface SyncsRuntime {\n list(): readonly SyncDefinition[]\n getById(syncId: string): SyncDefinition | null\n request(input: RequestSyncRunInput): Promise<SyncRunRequestResult>\n readonly runs: SyncRunsRuntime\n}\n\nexport function createSyncsRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n source: Pick<SyncsRuntime, \"list\" | \"getById\">\n): SyncsRuntime {\n const authority = resolveRuntimeAuthorizationForProject(runtime)\n const allowed = (syncId: string) => isRuntimeAllowed(runtime, { kind: \"sync.run\", syncId })\n const visibleIds = () =>\n source\n .list()\n .filter((sync) => allowed(sync.id))\n .map((sync) => sync.id)\n const historyFilterIds = () =>\n authority.type === \"unrestricted\"\n ? undefined\n : authority.type === \"principal\"\n ? visibleIds()\n : []\n\n return {\n list: () =>\n authority.type === \"denied\" || authority.type === \"delegated\"\n ? []\n : source.list().filter((sync) => allowed(sync.id)),\n getById: (syncId) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const sync = source.getById(syncId)\n return sync && allowed(syncId) ? sync : null\n },\n request: async (input) => {\n assertAuthorized(runtime, { kind: \"sync.run\", syncId: input.syncId })\n const sync = source.getById(input.syncId)\n if (!sync) throw new SyncValidationError(`[Sixb] Unknown sync '${input.syncId}'`)\n return requestSyncRun(runtime, execution, sync, input)\n },\n runs: {\n getById: async (runId) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const run =\n (await runtime.storage.syncRuns?.getById({\n projectId: runtime.projectId,\n id: runId,\n })) ?? null\n return run && allowed(run.syncId) ? run : null\n },\n list: (input = {}) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") {\n return Promise.resolve({ runs: [], hasMore: false, total: 0 })\n }\n const storage = runtime.storage.syncRuns\n if (!storage) return Promise.resolve({ runs: [], hasMore: false, total: 0 })\n return storage.list({\n ...input,\n syncIds: historyFilterIds(),\n projectId: runtime.projectId,\n })\n },\n listLatest: (syncIds) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") {\n return Promise.resolve({ runs: [] })\n }\n const storage = runtime.storage.syncRuns\n if (!storage || syncIds.length === 0) return Promise.resolve({ runs: [] })\n const allowedIds = syncIds.filter(allowed)\n return allowedIds.length === 0\n ? Promise.resolve({ runs: [] })\n : storage.listLatestBySyncIds({ projectId: runtime.projectId, syncIds: allowedIds })\n },\n },\n }\n}\n",
113
+ "import {\n assertAuthorized,\n canViewWorkflowIntervention,\n canViewWorkflowRun,\n isRuntimeAllowed,\n} from \"../authorization\"\nimport type { AuthorizablePrincipal, ExecutionContext } from \"../execution\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport { resolveExecutionCosts } from \"../runtime/ai-cost\"\nimport { resolveExecutionUsage } from \"../runtime/ai-usage\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type { AiCostSummary } from \"../storage/ai-cost\"\nimport type { AiModelCallUsage } from \"../storage/ai-usage\"\nimport type {\n ListWorkflowInterventionsInput,\n ListWorkflowInterventionsResult,\n WorkflowInterventionRecord,\n} from \"../storage/workflow-interventions\"\nimport type {\n ListLatestWorkflowRunsResult,\n ListWorkflowNodeRunsInput,\n ListWorkflowNodeRunsResult,\n ListWorkflowRunsInput,\n ListWorkflowRunsResult,\n WorkflowAgentNodeRunRecord,\n WorkflowNodeRunRecord,\n WorkflowRunRecord,\n WorkflowRunStorage,\n} from \"../storage/workflow-runs\"\nimport { WorkflowValidationError } from \"./errors\"\nimport {\n type RequestWorkflowRunInput,\n requestWorkflowRun,\n type WorkflowRunRequestOptions,\n type WorkflowRunRequestResult,\n} from \"./request\"\nimport type { WorkflowDefinition } from \"./types\"\n\nexport interface WorkflowRunsRuntime {\n getById(runId: string): Promise<WorkflowRunView | null>\n list(\n input?: Omit<ListWorkflowRunsInput, \"projectId\" | \"workflowIds\">\n ): Promise<WorkflowRunListResult>\n listLatest(workflowIds: readonly string[]): Promise<LatestWorkflowRunListResult>\n listNodes(\n runId: string,\n input?: ListWorkflowRunNodesInput\n ): Promise<WorkflowNodeRunListResult | null>\n}\n\n/** Execution-facing run view with provenance resolved from the immutable execution ledger. */\nexport interface WorkflowRunView extends WorkflowRunRecord {\n readonly requestedBy?: AuthorizablePrincipal\n}\n\nexport interface WorkflowRunListResult extends Omit<ListWorkflowRunsResult, \"runs\"> {\n readonly runs: readonly WorkflowRunView[]\n}\n\nexport interface LatestWorkflowRunListResult extends Omit<ListLatestWorkflowRunsResult, \"runs\"> {\n readonly runs: readonly WorkflowRunView[]\n}\n\nexport type ListWorkflowRunNodesInput = Omit<\n ListWorkflowNodeRunsInput,\n \"projectId\" | \"workflowRunId\" | \"workflowId\"\n>\n\n/** Execution-facing Agent node view derived from its run row and model-call ledger. */\nexport interface WorkflowAgentNodeRunView\n extends Omit<WorkflowAgentNodeRunRecord, \"execution\" | \"actorId\"> {\n readonly usage?: AiModelCallUsage\n /** Preferred valuation; omitted when there are no calls or cost storage is unavailable. */\n readonly cost?: AiCostSummary\n}\n\n/** Execution-facing workflow node view with optional Agent execution details. */\nexport interface WorkflowNodeRunView extends WorkflowNodeRunRecord {\n readonly agentExecution?: WorkflowAgentNodeRunView\n}\n\nexport interface WorkflowNodeRunListResult extends Omit<ListWorkflowNodeRunsResult, \"nodes\"> {\n readonly nodes: readonly WorkflowNodeRunView[]\n}\n\nexport interface WorkflowInterventionsRuntime {\n getById(interventionId: string): Promise<WorkflowInterventionRecord | null>\n list(\n input?: Omit<ListWorkflowInterventionsInput, \"projectId\" | \"workflowIds\">\n ): Promise<ListWorkflowInterventionsResult>\n}\n\nexport interface WorkflowsRuntime {\n list(): readonly WorkflowDefinition[]\n getById(workflowId: string): WorkflowDefinition | null\n request(\n workflow: WorkflowDefinition,\n options?: WorkflowRunRequestOptions\n ): Promise<WorkflowRunRequestResult>\n requestById(input: RequestWorkflowRunInput): Promise<WorkflowRunRequestResult>\n readonly runs: WorkflowRunsRuntime\n readonly interventions: WorkflowInterventionsRuntime\n}\n\nexport function createWorkflowsRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n source: Pick<WorkflowsRuntime, \"list\" | \"getById\">\n): WorkflowsRuntime {\n const authority = resolveRuntimeAuthorizationForProject(runtime)\n const allowed = (workflowId: string) =>\n isRuntimeAllowed(runtime, { kind: \"workflow.run\", workflowId })\n const canAccessHistory = (workflowId: string) => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return false\n case \"unrestricted\":\n return true\n case \"principal\":\n return allowed(workflowId) && source.getById(workflowId) !== null\n }\n }\n const visibleIds = () =>\n source\n .list()\n .filter((workflow) => allowed(workflow.id))\n .map((workflow) => workflow.id)\n const historyFilterIds = () =>\n authority.type === \"unrestricted\"\n ? undefined\n : authority.type === \"principal\"\n ? visibleIds()\n : []\n const getVisibleRunRecord = async (runId: string): Promise<WorkflowRunRecord | null> => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const run =\n (await runtime.storage.workflowRuns?.getById({\n projectId: runtime.projectId,\n id: runId,\n })) ?? null\n if (!run || !canAccessHistory(run.workflowId)) return null\n return authority.type === \"unrestricted\" || canViewWorkflowRun(authority.context, run)\n ? run\n : null\n }\n const getRun = async (runId: string): Promise<WorkflowRunView | null> => {\n const run = await getVisibleRunRecord(runId)\n return run ? attachRequestedBy(runtime, run) : null\n }\n const listNodes = async (\n runId: string,\n input: ListWorkflowRunNodesInput = {}\n ): Promise<WorkflowNodeRunListResult | null> => {\n const storage = runtime.storage.workflowRuns\n if (!storage || !(await getVisibleRunRecord(runId))) return null\n const result = await storage.nodes.list({\n ...input,\n workflowRunId: runId,\n projectId: runtime.projectId,\n })\n return {\n ...result,\n nodes: await attachWorkflowNodeViews(runtime, storage, result.nodes),\n }\n }\n\n return {\n list: () =>\n authority.type === \"denied\" || authority.type === \"delegated\"\n ? []\n : source.list().filter((workflow) => allowed(workflow.id)),\n getById: (workflowId) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const workflow = source.getById(workflowId)\n return workflow && allowed(workflowId) ? workflow : null\n },\n request: (workflow, options) => requestWorkflowRun(runtime, execution, workflow, options),\n requestById: async (input) => {\n assertAuthorized(runtime, { kind: \"workflow.run\", workflowId: input.workflowId })\n const workflow = source.getById(input.workflowId)\n if (!workflow) {\n throw new WorkflowValidationError(`[Sixb] Unknown workflow '${input.workflowId}'`)\n }\n return requestWorkflowRun(runtime, execution, workflow, input)\n },\n runs: {\n getById: getRun,\n list: async (input = {}) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") {\n return { runs: [], hasMore: false, total: 0 }\n }\n const storage = runtime.storage.workflowRuns\n if (!storage) return { runs: [], hasMore: false, total: 0 }\n const result = await storage.list({\n ...input,\n workflowIds: historyFilterIds(),\n projectId: runtime.projectId,\n })\n return {\n ...result,\n runs: await Promise.all(result.runs.map((run) => attachRequestedBy(runtime, run))),\n }\n },\n listLatest: async (workflowIds) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") {\n return { runs: [] }\n }\n const storage = runtime.storage.workflowRuns\n if (!storage || workflowIds.length === 0) return { runs: [] }\n const allowedIds = workflowIds.filter(canAccessHistory)\n if (allowedIds.length === 0) return { runs: [] }\n const result = await storage.listLatestByWorkflowIds({\n projectId: runtime.projectId,\n workflowIds: allowedIds,\n })\n return {\n runs: await Promise.all(result.runs.map((run) => attachRequestedBy(runtime, run))),\n }\n },\n listNodes,\n },\n interventions: {\n getById: async (interventionId) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const intervention =\n (await runtime.storage.workflowInterventions?.getById({\n projectId: runtime.projectId,\n id: interventionId,\n })) ?? null\n if (!intervention || !canAccessHistory(intervention.workflowId)) return null\n return authority.type === \"unrestricted\" ||\n canViewWorkflowIntervention(authority.context, intervention)\n ? intervention\n : null\n },\n list: (input = {}) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") {\n return Promise.resolve({ interventions: [], hasMore: false, total: 0 })\n }\n const storage = runtime.storage.workflowInterventions\n if (!storage) return Promise.resolve({ interventions: [], hasMore: false, total: 0 })\n return storage.list({\n ...input,\n workflowIds: historyFilterIds(),\n projectId: runtime.projectId,\n })\n },\n },\n }\n}\n\nasync function attachWorkflowNodeViews(\n runtime: SixbRuntimeContext,\n storage: WorkflowRunStorage,\n nodes: readonly WorkflowNodeRunRecord[]\n): Promise<readonly WorkflowNodeRunView[]> {\n const executions = await Promise.all(\n nodes.map((node) =>\n node.nodeType === \"agent\"\n ? storage.agentNodes.getByNodeRunId({\n projectId: runtime.projectId,\n nodeRunId: node.id,\n })\n : null\n )\n )\n const agentExecutions = executions.filter(\n (execution): execution is WorkflowAgentNodeRunRecord => execution !== null\n )\n if (agentExecutions.length === 0) return nodes\n\n const executionIds = agentExecutions.map((execution) => execution.executionId)\n const [usages, costs] = await Promise.all([\n resolveExecutionUsage({\n storage: runtime.storage.aiUsage,\n projectId: runtime.projectId,\n executionIds,\n }),\n resolveExecutionCosts({\n storage: runtime.storage.aiCosts,\n projectId: runtime.projectId,\n executionIds,\n }),\n ])\n const accountingByExecutionId = new Map(\n agentExecutions.map((execution, index) => [\n execution.executionId,\n { usage: usages[index], cost: costs[index] },\n ])\n )\n\n return nodes.map((node, index) => {\n const execution = executions[index]\n if (!execution) return node\n const accounting = accountingByExecutionId.get(execution.executionId)\n return {\n ...node,\n agentExecution: toWorkflowAgentNodeRunView(\n execution,\n accounting?.usage,\n accounting?.usage === undefined ? undefined : accounting.cost\n ),\n }\n })\n}\n\nfunction toWorkflowAgentNodeRunView(\n execution: WorkflowAgentNodeRunRecord,\n usage: AiModelCallUsage | undefined,\n cost: AiCostSummary | undefined\n): WorkflowAgentNodeRunView {\n return {\n projectId: execution.projectId,\n nodeRunId: execution.nodeRunId,\n executionId: execution.executionId,\n status: execution.status,\n prompt: execution.prompt,\n modelId: execution.modelId,\n finishReason: execution.finishReason,\n trace: execution.trace,\n diagnostics: execution.diagnostics,\n error: execution.error,\n attempt: execution.attempt,\n createdAt: execution.createdAt,\n startedAt: execution.startedAt,\n completedAt: execution.completedAt,\n ...(usage === undefined ? {} : { usage }),\n ...(usage === undefined || cost === undefined ? {} : { cost }),\n }\n}\n\nasync function attachRequestedBy(\n runtime: SixbRuntimeContext,\n run: WorkflowRunRecord\n): Promise<WorkflowRunView> {\n const execution = await runtime.storage.executions.getById({\n projectId: runtime.projectId,\n id: run.executionId,\n })\n if (!execution) {\n throw new Error(\n `[Sixb] Workflow run '${run.id}' references missing execution '${run.executionId}'.`\n )\n }\n return {\n ...run,\n ...(execution.requestedBy === undefined\n ? {}\n : { requestedBy: structuredClone(execution.requestedBy) }),\n }\n}\n",
114
+ "import { type ActionsRuntime, createActionsRuntime } from \"../actions/execution\"\nimport {\n type ActivityRuntime,\n createActivityCaptureRuntime,\n createActivityRuntime,\n registerActivityCaptureRuntime,\n} from \"../activity/execution\"\nimport type { ActivityService } from \"../activity/service\"\nimport { type AgentRuntime, createAgentRuntime } from \"../agents/execution\"\nimport { type AiUsageRuntime, createAiUsageRuntime } from \"../ai-usage\"\nimport { type ArtifactsRuntime, createArtifactsRuntime } from \"../artifacts/execution\"\nimport { type BlobsRuntime, createBlobsRuntime } from \"../blob-storage/execution\"\nimport type { BlobStorage } from \"../blob-storage/types\"\nimport { registerConnectorConnectionsRuntime } from \"../connectors/connections/capability\"\nimport type { ConnectorConnectionProcess } from \"../connectors/connections/contracts\"\nimport { createConnectorConnectionsRuntime } from \"../connectors/connections/execution\"\nimport { type ConnectorRuntime, createConnectorRuntime } from \"../connectors/execution\"\nimport type { ConnectorService } from \"../connectors/service\"\nimport { createDatasetsRuntime, type DatasetsRuntime } from \"../datasets/execution\"\nimport { createEventsRuntime, type EventsRuntime } from \"../events/execution\"\nimport type { ExecutionContext } from \"../execution\"\nimport { resolveExecutionScopeAuthorization } from \"../execution/authorization\"\nimport { assertAuthorizedObjectReaderBinding } from \"../execution/authorized-object-reader\"\nimport { registerRequestPreparation } from \"../execution/preparation\"\nimport type { LakeStorage } from \"../lake-storage/types\"\nimport { createLogsRuntime, type LogsRuntime } from \"../logging/execution\"\nimport type { LoggingService } from \"../logging/service\"\nimport { createDecisionRuntime } from \"../models/decision/runtime\"\nimport { createModelsRuntime } from \"../models/execution\"\nimport { ModelExecutionSession } from \"../models/execution/session\"\nimport type { ModelsRuntime } from \"../models/generation-types\"\nimport { createObjectsRuntime, type ObjectsRuntime } from \"../objects/execution\"\nimport { createPipelinesRuntime, type PipelinesRuntime } from \"../pipelines/execution\"\nimport { createProjectionsRuntime, type ProjectionsRuntime } from \"../projections/execution\"\nimport { createRulesRuntime, type RulesRuntime } from \"../rules/execution\"\nimport type { SandboxDefinition } from \"../sandboxes/configuration\"\nimport { createSchedulesRuntime, type SchedulesRuntime } from \"../schedules/execution\"\nimport type { DatasetVersionMarkings } from \"../security/dataset-version-markings\"\nimport { createSharesRuntime, type SharesRuntime } from \"../shares/execution\"\nimport { createSyncsRuntime, type SyncsRuntime } from \"../syncs/execution\"\nimport { createUsersRuntime, type UsersRuntime } from \"../users\"\nimport { createWorkflowsRuntime, type WorkflowsRuntime } from \"../workflows/execution\"\nimport type { SixbDefinitions } from \"./definitions\"\nimport { shareOntologyMutationRuntime } from \"./ontology-mutations\"\nimport type { SixbRuntimeContext } from \"./types\"\n\n/** Domain SDK bound to one immutable execution and one registered runtime authority. */\nexport interface Sixb<TParams extends Record<string, unknown> = Record<string, unknown>> {\n readonly execution: ExecutionContext\n readonly objects: ObjectsRuntime\n readonly actions: ActionsRuntime\n readonly datasets: DatasetsRuntime\n readonly workflows: WorkflowsRuntime\n readonly syncs: SyncsRuntime\n readonly pipelines: PipelinesRuntime\n readonly projections: ProjectionsRuntime\n readonly rules: RulesRuntime\n readonly agent: AgentRuntime<TParams>\n readonly artifacts: ArtifactsRuntime\n readonly models: ModelsRuntime\n readonly aiUsage: AiUsageRuntime\n readonly events: EventsRuntime\n readonly logs: LogsRuntime\n readonly activity: ActivityRuntime\n readonly schedules: SchedulesRuntime\n readonly shares: SharesRuntime\n readonly users: UsersRuntime\n readonly connector: ConnectorRuntime\n readonly blobs: BlobsRuntime\n}\n\nconst boundSixbInstances = new WeakSet<object>()\n\nexport interface SixbDependencies {\n readonly sandbox?: {\n readonly definition: SandboxDefinition\n readonly supportsPersistence: boolean\n }\n readonly definitions: SixbDefinitions\n readonly logging: LoggingService\n readonly activity: ActivityService\n readonly connectorService: ConnectorService\n readonly connectorConnections?: ConnectorConnectionProcess\n readonly blobStorage: BlobStorage\n readonly apiPublicOrigin: () => string | undefined\n readonly lakeStorage: LakeStorage\n readonly datasetVersionMarkings: DatasetVersionMarkings\n}\n\nexport function createBoundSixb<TParams extends Record<string, unknown> = Record<string, unknown>>(\n runtime: SixbRuntimeContext,\n dependencies: SixbDependencies,\n execution: ExecutionContext\n): Sixb<TParams> {\n resolveExecutionScopeAuthorization(runtime.projectId, {\n execution,\n authorization: runtime.runtimeAuthorization,\n })\n assertAuthorizedObjectReaderBinding({\n reader: runtime.objectReader,\n scope: { execution, authorization: runtime.runtimeAuthorization },\n })\n const sixb: Sixb<TParams> = {\n execution,\n ...createExecutionFacades<TParams>(runtime, execution, dependencies),\n }\n shareOntologyMutationRuntime(runtime, sixb)\n registerActivityCaptureRuntime(sixb, createActivityCaptureRuntime(runtime, dependencies.activity))\n registerRequestPreparation(sixb, runtime, execution, dependencies.definitions.workflows)\n if (dependencies.connectorConnections) {\n registerConnectorConnectionsRuntime(\n sixb,\n createConnectorConnectionsRuntime(runtime, execution, dependencies.connectorConnections)\n )\n }\n boundSixbInstances.add(sixb)\n return sixb\n}\n\n/** Internal nominal guard for execution boundaries that accept a narrow structural host. */\nexport function isBoundSixb<TParams extends Record<string, unknown> = Record<string, unknown>>(\n value: unknown\n): value is Sixb<TParams> {\n return typeof value === \"object\" && value !== null && boundSixbInstances.has(value)\n}\n\nfunction createExecutionFacades<TParams extends Record<string, unknown>>(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n dependencies: SixbDependencies\n): Omit<Sixb<TParams>, \"execution\"> {\n const actions = createActionsRuntime(runtime, execution)\n const workflows = createWorkflowsRuntime(runtime, execution, dependencies.definitions.workflows)\n // One session per execution: the facade's model calls and the Agent's decisions share its\n // accounting, AI limits and cancellation.\n const session = runtime.modelExecution ?? new ModelExecutionSession(runtime, execution)\n const agent = createAgentRuntime<TParams>(\n runtime,\n execution,\n dependencies.definitions.models,\n createDecisionRuntime(\n runtime,\n execution,\n dependencies.definitions.models,\n session,\n \"agent.run\"\n ),\n dependencies.sandbox,\n dependencies.definitions.security\n )\n return {\n objects: createObjectsRuntime(runtime, execution, dependencies.blobStorage),\n actions,\n datasets: createDatasetsRuntime(\n runtime,\n execution,\n dependencies.definitions.datasets,\n dependencies.lakeStorage,\n dependencies.blobStorage,\n dependencies.datasetVersionMarkings\n ),\n workflows,\n syncs: createSyncsRuntime(runtime, execution, dependencies.definitions.syncs),\n pipelines: createPipelinesRuntime(runtime, execution, dependencies.definitions.pipelines),\n projections: createProjectionsRuntime(runtime, dependencies.definitions.projections),\n rules: createRulesRuntime(runtime, dependencies.definitions.rules),\n agent,\n artifacts: createArtifactsRuntime(runtime, dependencies.blobStorage),\n models: createModelsRuntime(\n runtime,\n execution,\n dependencies.definitions.models,\n session,\n {\n canViewActionRun: async (id) => (await actions.runs.getById(id)) !== null,\n canViewWorkflowRun: async (id) => (await workflows.runs.getById(id)) !== null,\n canViewAgentRun: async (id) => (await agent.runs.getById(id)) !== null,\n },\n dependencies.blobStorage\n ),\n aiUsage: createAiUsageRuntime(runtime, dependencies.definitions.security),\n events: createEventsRuntime(runtime),\n logs: createLogsRuntime(runtime, dependencies.logging),\n activity: createActivityRuntime(runtime, dependencies.activity),\n schedules: createSchedulesRuntime(runtime, dependencies.definitions.schedules),\n shares: createSharesRuntime(runtime, execution, dependencies.definitions.shares),\n users: createUsersRuntime(runtime),\n connector: createConnectorRuntime(runtime, execution, dependencies.connectorService),\n blobs: createBlobsRuntime(\n runtime,\n execution,\n dependencies.blobStorage,\n dependencies.apiPublicOrigin\n ),\n }\n}\n",
115
+ "import { type AgentExecutionAuthorization, agentServiceAccountId } from \"../agents/authority\"\nimport { bindModelExecutionAttempt } from \"../models/execution/binding\"\nimport type { AiModelCallRecorder } from \"../models/execution/model-call-recorder\"\nimport { isBoundSixb, type Sixb } from \"../runtime/sixb\"\nimport type { ExecutionRecord } from \"../storage/executions\"\nimport { ExecutionStorageError } from \"../storage/executions\"\n\nexport { ensureExecutionRecord } from \"./durable\"\n\nimport { createAgentRuntimeAuthorization, getAuthorizationRef } from \"./authorization\"\nimport type {\n AuthorizablePrincipal,\n ExecutionContext,\n ExecutionScope,\n RuntimeAuthorization,\n} from \"./types\"\n\n/** Minimal host boundary required by agent workers. */\nexport interface AgentExecutionHost {\n readonly id: string\n withScope(scope: ExecutionScope): object\n}\n\n/** Whether a conversational Agent run can durably restore this request authority without widening it. */\nexport function canInheritAgentRequestAuthorization(authorization: RuntimeAuthorization): boolean {\n const ref = getAuthorizationRef(authorization)\n return (\n ref.type === \"disabled\" ||\n (ref.type === \"principal\" && ref.principal.type === \"user\" && ref.credential !== undefined)\n )\n}\n\n/** Build the immutable child execution owned by one direct or Workflow Agent run. */\nexport function createAgentExecutionRecord(input: {\n readonly id: string\n readonly parent: ExecutionRecord\n readonly actorId: string\n readonly runId: string\n readonly principal: Extract<AuthorizablePrincipal, { readonly type: \"serviceAccount\" }>\n}): Omit<ExecutionRecord, \"createdAt\"> {\n assertAgentPrincipal(input.actorId, input.principal)\n return {\n id: input.id,\n projectId: input.parent.projectId,\n requesterGroupIds: [...input.parent.requesterGroupIds],\n ...(input.parent.requestedBy === undefined\n ? {}\n : { requestedBy: structuredClone(input.parent.requestedBy) }),\n executor: { type: \"agent\", runId: input.runId },\n source: { type: \"execution\", executionId: input.parent.id },\n correlationId: input.parent.correlationId,\n authorizationRef: {\n type: \"principal\",\n principal: structuredClone(input.principal),\n },\n }\n}\n\n/** Build an Agent execution that carries its parent's exact durable authority reference. */\nexport function createInheritedAgentExecutionRecord(input: {\n readonly id: string\n readonly parent: ExecutionRecord\n readonly runId: string\n}): Omit<ExecutionRecord, \"createdAt\"> {\n const authority = input.parent.authorizationRef\n if (\n authority.type !== \"disabled\" &&\n !(\n authority.type === \"principal\" &&\n authority.principal.type === \"user\" &&\n authority.credential !== undefined\n )\n ) {\n throw new ExecutionStorageError(\n \"invalid_input\",\n `[Sixb] Agent run '${input.runId}' requires inheritable user or auth-disabled authority.`\n )\n }\n\n return {\n id: input.id,\n projectId: input.parent.projectId,\n requesterGroupIds: [...input.parent.requesterGroupIds],\n ...(input.parent.requestedBy === undefined\n ? {}\n : { requestedBy: structuredClone(input.parent.requestedBy) }),\n executor: { type: \"agent\", runId: input.runId },\n source: { type: \"execution\", executionId: input.parent.id },\n correlationId: input.parent.correlationId,\n authorizationRef: structuredClone(authority),\n }\n}\n\n/** Bind a worker to the immutable execution already owned by its durable Agent run. */\nexport function bindDurableAgentExecution(\n host: AgentExecutionHost,\n input: {\n readonly execution: ExecutionRecord\n readonly actorId?: string\n readonly runId: string\n readonly authorization: AgentExecutionAuthorization\n }\n): Sixb {\n const scope = restoreAgentExecutionScope(input)\n const sixb = host.withScope(scope)\n if (!isBoundSixb(sixb)) {\n throw new Error(\"[Sixb] Agent execution host returned an invalid bound SDK.\")\n }\n return sixb\n}\n\n/**\n * Bind one agent API gateway request to the run's own execution, the way the run's in-process\n * tools are bound: what the request starts is a child of the run, with the run's requester and\n * correlation. Model calls behind it count toward the attempt the request was admitted under, with\n * a recorder of their own: the worker's in-memory failure state and cancellation do not reach them.\n */\nexport function bindAgentGatewayRequestExecution(\n host: AgentExecutionHost,\n input: {\n /** Aborting it cancels the request's model calls. */\n readonly signal: AbortSignal\n readonly execution: ExecutionRecord\n readonly actorId?: string\n readonly runId: string\n readonly attempt: number\n readonly authorization: AgentExecutionAuthorization\n }\n): Sixb {\n const { signal, attempt, ...execution } = input\n const sixb = bindDurableAgentExecution(host, execution)\n\n bindModelExecutionAttempt(sixb.models, { attempt, signal })\n return sixb\n}\n\n/**\n * Account model calls made through a run's bound SDK — by its tools, or embeddings behind their\n * searches — like the run's own: same execution attempt, limits, failure state and cancellation.\n * The attempt is the recorder's, so the two cannot diverge.\n */\nexport function bindAgentModelExecution(\n sixb: Sixb,\n input: {\n readonly signal: AbortSignal\n readonly accounting: AiModelCallRecorder\n }\n): void {\n const { accounting } = input\n if (accounting.executionId !== sixb.execution.id) {\n throw new Error(\n `[Sixb] Agent execution '${sixb.execution.id}' cannot account its model calls to execution '${accounting.executionId}'.`\n )\n }\n bindModelExecutionAttempt(sixb.models, {\n attempt: accounting.attempt,\n signal: input.signal,\n accounting,\n })\n}\n\n/** Restore one provider-validated Agent execution with its currently resolved grants. */\nexport function restoreAgentExecutionScope(input: {\n readonly execution: ExecutionRecord\n readonly actorId?: string\n readonly runId: string\n readonly authorization: AgentExecutionAuthorization\n}): ExecutionScope {\n assertAgentExecutionRecord(input)\n const context: ExecutionContext = Object.freeze({\n id: input.execution.id,\n projectId: input.execution.projectId,\n ...(input.execution.requestedBy === undefined\n ? {}\n : { requestedBy: Object.freeze(structuredClone(input.execution.requestedBy)) }),\n executor: Object.freeze({\n type: \"agent\",\n ...(input.actorId === undefined ? {} : { actorId: input.actorId }),\n runId: input.runId,\n }),\n source: Object.freeze(structuredClone(input.execution.source)),\n correlationId: input.execution.correlationId,\n })\n return Object.freeze({\n execution: context,\n authorization: createAgentRuntimeAuthorization({\n execution: context,\n authority:\n input.authorization.type === \"principal\"\n ? {\n type: \"principal\",\n context: input.authorization.context,\n ...(input.execution.authorizationRef.type === \"principal\" &&\n input.execution.authorizationRef.credential !== undefined\n ? { credential: input.execution.authorizationRef.credential }\n : {}),\n }\n : { type: \"disabled\" },\n }),\n })\n}\n\n/** Validate that a durable record belongs to the exact resolved Agent execution. */\nexport function assertAgentExecutionRecord(input: {\n readonly execution: ExecutionRecord\n readonly actorId?: string\n readonly runId: string\n readonly authorization: AgentExecutionAuthorization\n}): void {\n const authority = input.execution.authorizationRef\n if (\n input.execution.executor.type !== \"agent\" ||\n input.execution.executor.runId !== input.runId ||\n input.execution.source.type !== \"execution\"\n ) {\n invalidAgentExecution(input.execution.id, input.runId)\n }\n\n if (\n input.authorization.type === \"disabled\" ||\n input.authorization.context.principal.type === \"user\"\n ) {\n assertInheritedAgentAuthority(input.execution, input.runId, input.authorization)\n return\n }\n\n if (\n input.authorization.type !== \"principal\" ||\n authority.type !== \"principal\" ||\n authority.principal.type !== \"serviceAccount\" ||\n input.authorization.context.principal.type !== \"serviceAccount\" ||\n authority.principal.id !== input.authorization.context.principal.id ||\n authority.credential !== undefined\n ) {\n invalidAgentExecution(input.execution.id, input.runId)\n }\n if (input.actorId === undefined) {\n invalidAgentExecution(input.execution.id, input.runId)\n }\n assertAgentPrincipal(input.actorId, authority.principal)\n}\n\nfunction assertInheritedAgentAuthority(\n execution: ExecutionRecord,\n runId: string,\n authorization: AgentExecutionAuthorization\n): void {\n const authority = execution.authorizationRef\n if (authorization.type === \"disabled\") {\n if (authority.type !== \"disabled\") invalidAgentExecution(execution.id, runId)\n return\n }\n\n const principal = authorization.context.principal\n if (\n authority.type !== \"principal\" ||\n authority.principal.type !== \"user\" ||\n principal.type !== \"user\" ||\n authority.principal.id !== principal.id ||\n authority.credential === undefined ||\n (authority.credential.type === \"session\"\n ? authorization.context.sessionId !== authority.credential.id\n : authorization.context.sessionId !== undefined)\n ) {\n invalidAgentExecution(execution.id, runId)\n }\n}\n\nfunction assertAgentPrincipal(\n actorId: string,\n principal: Extract<AuthorizablePrincipal, { readonly type: \"serviceAccount\" }>\n): void {\n const expectedId = agentServiceAccountId(actorId)\n if (principal.id !== expectedId) {\n throw new ExecutionStorageError(\n \"invalid_input\",\n `[Sixb] Agent '${actorId}' execution authority must reference service account '${expectedId}'.`\n )\n }\n}\n\nfunction invalidAgentExecution(executionId: string, runId: string): never {\n throw new ExecutionStorageError(\n \"invalid_input\",\n `[Sixb] Execution '${executionId}' does not authorize Agent run '${runId}'.`\n )\n}\n"
116
+ ],
117
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,IAAM,WAAW,IAAI;AAEd,SAAS,6BAA6B,CAC3C,QAC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