@sixb/core 0.1.18 → 0.1.20

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 (523) hide show
  1. package/README.md +7 -6
  2. package/dist/actions/commit-edits.d.ts +7 -19
  3. package/dist/actions/commit-edits.d.ts.map +1 -1
  4. package/dist/actions/errors.d.ts +0 -3
  5. package/dist/actions/errors.d.ts.map +1 -1
  6. package/dist/actions/execution.d.ts +10 -3
  7. package/dist/actions/execution.d.ts.map +1 -1
  8. package/dist/actions/index.d.ts +6 -9
  9. package/dist/actions/index.d.ts.map +1 -1
  10. package/dist/actions/index.js +51 -50
  11. package/dist/actions/index.js.map +1 -1
  12. package/dist/actions/request.d.ts +14 -25
  13. package/dist/actions/request.d.ts.map +1 -1
  14. package/dist/actions/run/context.d.ts +40 -0
  15. package/dist/actions/run/context.d.ts.map +1 -0
  16. package/dist/actions/run/edits-commit.d.ts +31 -0
  17. package/dist/actions/run/edits-commit.d.ts.map +1 -0
  18. package/dist/actions/run/effects.d.ts +23 -0
  19. package/dist/actions/run/effects.d.ts.map +1 -0
  20. package/dist/actions/run/execute.d.ts +30 -0
  21. package/dist/actions/run/execute.d.ts.map +1 -0
  22. package/dist/actions/run/executor.d.ts +95 -0
  23. package/dist/actions/run/executor.d.ts.map +1 -0
  24. package/dist/actions/run/normalize.d.ts +36 -0
  25. package/dist/actions/run/normalize.d.ts.map +1 -0
  26. package/dist/actions/run/phase-types.d.ts +18 -0
  27. package/dist/actions/run/phase-types.d.ts.map +1 -0
  28. package/dist/actions/run/phases.d.ts +20 -0
  29. package/dist/actions/run/phases.d.ts.map +1 -0
  30. package/dist/actions/run/run-action.d.ts +25 -0
  31. package/dist/actions/run/run-action.d.ts.map +1 -0
  32. package/dist/actions/run/signals.d.ts +67 -0
  33. package/dist/actions/run/signals.d.ts.map +1 -0
  34. package/dist/actions/run/state.d.ts +47 -0
  35. package/dist/actions/run/state.d.ts.map +1 -0
  36. package/dist/actions/run/types.d.ts +54 -0
  37. package/dist/actions/run/types.d.ts.map +1 -0
  38. package/dist/actions/run/writeback.d.ts +17 -0
  39. package/dist/actions/run/writeback.d.ts.map +1 -0
  40. package/dist/actions/run-authorization.d.ts +1 -1
  41. package/dist/actions/run-authorization.d.ts.map +1 -1
  42. package/dist/actions/run-persistence.d.ts +53 -0
  43. package/dist/actions/run-persistence.d.ts.map +1 -0
  44. package/dist/actions/types/context.d.ts +10 -0
  45. package/dist/actions/types/context.d.ts.map +1 -1
  46. package/dist/agents/index.js +52 -55
  47. package/dist/agents/index.js.map +1 -1
  48. package/dist/agents/streams/index.js +2 -2
  49. package/dist/agents/streams/internal.js +2 -2
  50. package/dist/auth/cookies.d.ts +2 -4
  51. package/dist/auth/cookies.d.ts.map +1 -1
  52. package/dist/auth/index.d.ts +0 -2
  53. package/dist/auth/index.d.ts.map +1 -1
  54. package/dist/auth/index.js +15 -21
  55. package/dist/auth/index.js.map +1 -1
  56. package/dist/auth/runtime.d.ts +8 -10
  57. package/dist/auth/runtime.d.ts.map +1 -1
  58. package/dist/auth/session-cache.d.ts +1 -5
  59. package/dist/auth/session-cache.d.ts.map +1 -1
  60. package/dist/auth/strategy.js +1 -1
  61. package/dist/auth/types.d.ts +4 -8
  62. package/dist/auth/types.d.ts.map +1 -1
  63. package/dist/auth/validation.d.ts +0 -1
  64. package/dist/auth/validation.d.ts.map +1 -1
  65. package/dist/authorization/decision.d.ts +0 -4
  66. package/dist/authorization/decision.d.ts.map +1 -1
  67. package/dist/authorization/event-visibility.d.ts.map +1 -1
  68. package/dist/authorization/grant-kinds.d.ts +6 -8
  69. package/dist/authorization/grant-kinds.d.ts.map +1 -1
  70. package/dist/authorization/index.d.ts +0 -1
  71. package/dist/authorization/index.d.ts.map +1 -1
  72. package/dist/authorization/index.js +5 -9
  73. package/dist/authorization/index.js.map +1 -1
  74. package/dist/authorization/resolve.d.ts +1 -1
  75. package/dist/authorization/resolve.d.ts.map +1 -1
  76. package/dist/bootstrap/index.js +50 -53
  77. package/dist/bootstrap/index.js.map +2 -2
  78. package/dist/{chunk-vz3gc1tm.js → chunk-0rbyz4qy.js} +67 -69
  79. package/dist/{chunk-vz3gc1tm.js.map → chunk-0rbyz4qy.js.map} +4 -4
  80. package/dist/{chunk-rz53yb4v.js → chunk-0yh890a4.js} +1 -1
  81. package/dist/{chunk-vgk3hknm.js → chunk-1k89ecfr.js} +1 -1
  82. package/dist/{chunk-ny3xyvcn.js → chunk-1zq2p6g0.js} +3 -3
  83. package/dist/{chunk-dnmadg9k.js → chunk-3t2hgbgd.js} +2 -2
  84. package/dist/{chunk-k6hrnf35.js → chunk-4vyr1j8f.js} +51 -4
  85. package/dist/chunk-4vyr1j8f.js.map +11 -0
  86. package/dist/{chunk-22v5bpz3.js → chunk-5e43w60z.js} +1 -1
  87. package/dist/{chunk-de4z2bj6.js → chunk-5j58wjct.js} +17 -17
  88. package/dist/chunk-5j58wjct.js.map +18 -0
  89. package/dist/{chunk-fe52eczz.js → chunk-6c6sn0bh.js} +6352 -2127
  90. package/dist/chunk-6c6sn0bh.js.map +106 -0
  91. package/dist/{chunk-7hpdd6r9.js → chunk-6p49a5cq.js} +4 -4
  92. package/dist/{chunk-b9affek3.js → chunk-7n440zgt.js} +30 -30
  93. package/dist/{chunk-b9affek3.js.map → chunk-7n440zgt.js.map} +4 -4
  94. package/dist/{chunk-kkqwzy6h.js → chunk-7t429e3f.js} +1 -1
  95. package/dist/{chunk-6fsr7y93.js → chunk-8mx7qw3y.js} +14 -13
  96. package/dist/{chunk-6fsr7y93.js.map → chunk-8mx7qw3y.js.map} +4 -4
  97. package/dist/{chunk-kpx7jrmn.js → chunk-91mg3nj9.js} +59 -59
  98. package/dist/{chunk-kpx7jrmn.js.map → chunk-91mg3nj9.js.map} +5 -5
  99. package/dist/{chunk-ex496vct.js → chunk-9dmt152s.js} +1 -1
  100. package/dist/{chunk-48e3cn2d.js → chunk-9gyp8hg1.js} +2 -2
  101. package/dist/{chunk-ewqa58h9.js → chunk-9k93ah50.js} +4 -4
  102. package/dist/{chunk-ewqa58h9.js.map → chunk-9k93ah50.js.map} +1 -1
  103. package/dist/{chunk-zxawp1n2.js → chunk-9w055r5b.js} +1 -1
  104. package/dist/{chunk-4wn7bxxa.js → chunk-9ybhtmg4.js} +1 -1
  105. package/dist/{chunk-fc5zfxy1.js → chunk-a40ad1ft.js} +5 -13
  106. package/dist/chunk-a40ad1ft.js.map +10 -0
  107. package/dist/{chunk-y2aq6ag9.js → chunk-b38szspf.js} +5 -14
  108. package/dist/chunk-b38szspf.js.map +11 -0
  109. package/dist/{chunk-r2y23egw.js → chunk-bkpke1sg.js} +1 -10
  110. package/dist/chunk-bkpke1sg.js.map +10 -0
  111. package/dist/{chunk-htr6wjmv.js → chunk-bx9q3cwv.js} +22 -22
  112. package/dist/{chunk-htr6wjmv.js.map → chunk-bx9q3cwv.js.map} +1 -1
  113. package/dist/{chunk-vx2yp45y.js → chunk-c85m1hyj.js} +2 -2
  114. package/dist/{chunk-bs7sqkre.js → chunk-d09tj99x.js} +2 -2
  115. package/dist/{chunk-qkbx3tf6.js → chunk-d0bqz29d.js} +27 -47
  116. package/dist/chunk-d0bqz29d.js.map +23 -0
  117. package/dist/{chunk-zb77kjth.js → chunk-dk8tkk5f.js} +4 -4
  118. package/dist/{chunk-xt1zt7gv.js → chunk-es1gxsbf.js} +24 -15
  119. package/dist/chunk-es1gxsbf.js.map +13 -0
  120. package/dist/{chunk-vjcd8d27.js → chunk-fa02jy15.js} +1 -1
  121. package/dist/{chunk-za5yd58j.js → chunk-fkgc1wt8.js} +2 -2
  122. package/dist/{chunk-enpsx8k5.js → chunk-gsjm1wms.js} +16 -20
  123. package/dist/chunk-gsjm1wms.js.map +10 -0
  124. package/dist/{chunk-2jntasmh.js → chunk-hcbyfxbe.js} +25 -49
  125. package/dist/chunk-hcbyfxbe.js.map +12 -0
  126. package/dist/{chunk-p0dqwj3n.js → chunk-hjzdd750.js} +66 -47
  127. package/dist/{chunk-p0dqwj3n.js.map → chunk-hjzdd750.js.map} +4 -4
  128. package/dist/chunk-hkc3jct7.js.map +1 -1
  129. package/dist/{chunk-y05543x6.js → chunk-hvsb78a1.js} +4 -4
  130. package/dist/{chunk-y05543x6.js.map → chunk-hvsb78a1.js.map} +1 -1
  131. package/dist/{chunk-1b1f2d5f.js → chunk-k6q3n2sc.js} +9 -9
  132. package/dist/{chunk-1b1f2d5f.js.map → chunk-k6q3n2sc.js.map} +1 -1
  133. package/dist/{chunk-wr8qp979.js → chunk-m427qgq0.js} +9 -5
  134. package/dist/{chunk-wr8qp979.js.map → chunk-m427qgq0.js.map} +4 -3
  135. package/dist/{chunk-qq90g05n.js → chunk-n33z5bjw.js} +50 -240
  136. package/dist/{chunk-qq90g05n.js.map → chunk-n33z5bjw.js.map} +4 -4
  137. package/dist/{chunk-e1c18xjx.js → chunk-nq6gpjt7.js} +4 -45
  138. package/dist/{chunk-e1c18xjx.js.map → chunk-nq6gpjt7.js.map} +5 -5
  139. package/dist/{chunk-1hqwggsn.js → chunk-nzapm6p0.js} +1 -2
  140. package/dist/chunk-nzapm6p0.js.map +12 -0
  141. package/dist/{chunk-wt4szfec.js → chunk-pbcbn83d.js} +4 -4
  142. package/dist/{chunk-wt4szfec.js.map → chunk-pbcbn83d.js.map} +1 -1
  143. package/dist/{chunk-s4jhg8a3.js → chunk-ren4kg2j.js} +15 -15
  144. package/dist/{chunk-s4jhg8a3.js.map → chunk-ren4kg2j.js.map} +1 -1
  145. package/dist/{chunk-d0eb5yy6.js → chunk-rrzt8jdy.js} +5 -5
  146. package/dist/{chunk-d0eb5yy6.js.map → chunk-rrzt8jdy.js.map} +1 -1
  147. package/dist/{chunk-y9jmd7e5.js → chunk-s16apyk9.js} +102 -16
  148. package/dist/chunk-s16apyk9.js.map +16 -0
  149. package/dist/{chunk-6gmfggss.js → chunk-t7x8dmn0.js} +2 -2
  150. package/dist/{chunk-f1zxad2t.js → chunk-tg2cw67r.js} +6 -6
  151. package/dist/{chunk-f1zxad2t.js.map → chunk-tg2cw67r.js.map} +1 -1
  152. package/dist/{chunk-p844e0rn.js → chunk-tpn40322.js} +2 -2
  153. package/dist/{chunk-rt9p8m9t.js → chunk-v9xd5wzd.js} +1 -1
  154. package/dist/{chunk-6h5m9xjx.js → chunk-vpq4shxz.js} +49 -113
  155. package/dist/chunk-vpq4shxz.js.map +39 -0
  156. package/dist/{chunk-2vhg6ysa.js → chunk-vyf9kfqf.js} +1 -1
  157. package/dist/{chunk-bwjcehza.js → chunk-way52z4h.js} +1 -1
  158. package/dist/{chunk-qkvz64nd.js → chunk-x6m907x7.js} +3 -3
  159. package/dist/{chunk-yv9czyfr.js → chunk-xfs8x8m9.js} +5 -5
  160. package/dist/chunk-y0c4e6ex.js +16 -0
  161. package/dist/chunk-y0c4e6ex.js.map +10 -0
  162. package/dist/{chunk-v6xpd60t.js → chunk-yevzdx4y.js} +5 -5
  163. package/dist/{chunk-dfm066qg.js → chunk-yxd3nnqt.js} +2 -29
  164. package/dist/chunk-yxd3nnqt.js.map +11 -0
  165. package/dist/{chunk-70jmg2zx.js → chunk-yzwja0mj.js} +4 -19
  166. package/dist/{chunk-70jmg2zx.js.map → chunk-yzwja0mj.js.map} +3 -3
  167. package/dist/{chunk-qmnnhde6.js → chunk-z4m0yz8c.js} +1 -1
  168. package/dist/datasets/write.js +5 -5
  169. package/dist/deploy/index.d.ts +1 -1
  170. package/dist/deploy/index.d.ts.map +1 -1
  171. package/dist/deploy/internal.js +13 -10
  172. package/dist/deploy/internal.js.map +4 -4
  173. package/dist/deploy/services.d.ts +1 -2
  174. package/dist/deploy/services.d.ts.map +1 -1
  175. package/dist/deploy/types.d.ts +7 -7
  176. package/dist/deploy/types.d.ts.map +1 -1
  177. package/dist/deploy/validation.d.ts.map +1 -1
  178. package/dist/edits/index.js +3 -5
  179. package/dist/edits/index.js.map +1 -1
  180. package/dist/error-reporting/internal.js +3 -3
  181. package/dist/error-reporting/types.d.ts +2 -9
  182. package/dist/error-reporting/types.d.ts.map +1 -1
  183. package/dist/errors/catalog.d.ts +12 -0
  184. package/dist/errors/catalog.d.ts.map +1 -1
  185. package/dist/errors/internal.js +1 -1
  186. package/dist/events/definitions.d.ts +0 -5
  187. package/dist/events/definitions.d.ts.map +1 -1
  188. package/dist/events/index.d.ts +3 -3
  189. package/dist/events/index.d.ts.map +1 -1
  190. package/dist/events/index.js +6 -8
  191. package/dist/events/index.js.map +1 -1
  192. package/dist/events/scope.d.ts +0 -1
  193. package/dist/events/scope.d.ts.map +1 -1
  194. package/dist/events/scope.js +1 -1
  195. package/dist/events/selectors/builder.d.ts +1 -8
  196. package/dist/events/selectors/builder.d.ts.map +1 -1
  197. package/dist/events/selectors/index.d.ts +2 -2
  198. package/dist/events/selectors/index.d.ts.map +1 -1
  199. package/dist/events/selectors/index.js +2 -2
  200. package/dist/events/selectors/predicate.d.ts.map +1 -1
  201. package/dist/events/selectors/types.d.ts +2 -33
  202. package/dist/events/selectors/types.d.ts.map +1 -1
  203. package/dist/events/types/index.d.ts +1 -12
  204. package/dist/events/types/index.d.ts.map +1 -1
  205. package/dist/execution/agent.js +41 -44
  206. package/dist/execution/agent.js.map +1 -1
  207. package/dist/execution/authorization.d.ts.map +1 -1
  208. package/dist/execution/primitive.js +60 -91
  209. package/dist/execution/primitive.js.map +3 -4
  210. package/dist/execution/request.js +40 -43
  211. package/dist/execution/request.js.map +2 -2
  212. package/dist/index.d.ts +8 -8
  213. package/dist/index.d.ts.map +1 -1
  214. package/dist/index.js +105 -127
  215. package/dist/index.js.map +1 -1
  216. package/dist/lake-storage/index.js +5 -5
  217. package/dist/materialization/index.js +3 -3
  218. package/dist/materialization/index.js.map +1 -1
  219. package/dist/materialization/model.d.ts +19 -6
  220. package/dist/materialization/model.d.ts.map +1 -1
  221. package/dist/materializer/index.js +31 -31
  222. package/dist/materializer/index.js.map +1 -1
  223. package/dist/materializer/shared/normalize.d.ts.map +1 -1
  224. package/dist/models/execution/index.js +21 -21
  225. package/dist/objects/action/errors.d.ts +0 -9
  226. package/dist/objects/action/errors.d.ts.map +1 -1
  227. package/dist/objects/action/index.d.ts +3 -3
  228. package/dist/objects/action/index.d.ts.map +1 -1
  229. package/dist/objects/action/request.d.ts +2 -8
  230. package/dist/objects/action/request.d.ts.map +1 -1
  231. package/dist/objects/execution.d.ts +0 -2
  232. package/dist/objects/execution.d.ts.map +1 -1
  233. package/dist/objects/index.js +44 -29
  234. package/dist/objects/index.js.map +1 -1
  235. package/dist/objects/query/index.js +29 -29
  236. package/dist/objects/query/index.js.map +1 -1
  237. package/dist/objects/sdk/object-handle.d.ts.map +1 -1
  238. package/dist/objects/sdk/object-set.d.ts.map +1 -1
  239. package/dist/objects/service/index.d.ts +0 -1
  240. package/dist/objects/service/index.d.ts.map +1 -1
  241. package/dist/objects/vectors/handle.d.ts.map +1 -1
  242. package/dist/objects/vectors/profile.d.ts +5 -0
  243. package/dist/objects/vectors/profile.d.ts.map +1 -1
  244. package/dist/ontology/index.js +6 -6
  245. package/dist/ontology/index.js.map +1 -1
  246. package/dist/ontology/internal.js +2 -2
  247. package/dist/pipelines/index.js +28 -28
  248. package/dist/projections/internal.js +22 -22
  249. package/dist/projections/internal.js.map +1 -1
  250. package/dist/query.js +2 -2
  251. package/dist/queues/in-memory.d.ts +1 -2
  252. package/dist/queues/in-memory.d.ts.map +1 -1
  253. package/dist/queues/index.d.ts +1 -1
  254. package/dist/queues/index.d.ts.map +1 -1
  255. package/dist/queues/index.js +1 -1
  256. package/dist/queues/types.d.ts +0 -7
  257. package/dist/queues/types.d.ts.map +1 -1
  258. package/dist/runtime/host.d.ts.map +1 -1
  259. package/dist/runtime/internal.js +27 -28
  260. package/dist/runtime/internal.js.map +1 -1
  261. package/dist/runtime/resolve-definitions.d.ts.map +1 -1
  262. package/dist/runtime/types.d.ts +16 -36
  263. package/dist/runtime/types.d.ts.map +1 -1
  264. package/dist/sandboxes/index.js +5 -5
  265. package/dist/schedules/builders.d.ts.map +1 -1
  266. package/dist/schedules/index.js +3 -3
  267. package/dist/schedules/runtime.d.ts.map +1 -1
  268. package/dist/schedules/validation.d.ts +0 -1
  269. package/dist/schedules/validation.d.ts.map +1 -1
  270. package/dist/security/builders.d.ts.map +1 -1
  271. package/dist/security/every.d.ts +2 -5
  272. package/dist/security/every.d.ts.map +1 -1
  273. package/dist/security/grants.d.ts +2 -4
  274. package/dist/security/grants.d.ts.map +1 -1
  275. package/dist/security/index.d.ts +1 -2
  276. package/dist/security/index.d.ts.map +1 -1
  277. package/dist/security/membership-policies.d.ts.map +1 -1
  278. package/dist/security/public.d.ts +10 -0
  279. package/dist/security/public.d.ts.map +1 -0
  280. package/dist/security/public.js +10 -0
  281. package/dist/security/public.js.map +9 -0
  282. package/dist/security/registry.d.ts +0 -1
  283. package/dist/security/registry.d.ts.map +1 -1
  284. package/dist/security/types.d.ts +13 -18
  285. package/dist/security/types.d.ts.map +1 -1
  286. package/dist/security/validation.d.ts +0 -6
  287. package/dist/security/validation.d.ts.map +1 -1
  288. package/dist/shares/internal.js +20 -20
  289. package/dist/storage/action-runs/failure.js +2 -2
  290. package/dist/storage/action-runs/idempotency.d.ts +3 -4
  291. package/dist/storage/action-runs/idempotency.d.ts.map +1 -1
  292. package/dist/storage/action-runs/in-memory.d.ts +2 -9
  293. package/dist/storage/action-runs/in-memory.d.ts.map +1 -1
  294. package/dist/storage/action-runs/index.d.ts +1 -3
  295. package/dist/storage/action-runs/index.d.ts.map +1 -1
  296. package/dist/storage/action-runs/provider.js +1 -1
  297. package/dist/storage/action-runs/record.d.ts +20 -0
  298. package/dist/storage/action-runs/record.d.ts.map +1 -0
  299. package/dist/storage/action-runs/types.d.ts +39 -68
  300. package/dist/storage/action-runs/types.d.ts.map +1 -1
  301. package/dist/storage/agents/types.d.ts +1 -1
  302. package/dist/storage/ai-limits/enforcement.js +2 -2
  303. package/dist/storage/auth/in-memory/auth-storage.d.ts.map +1 -1
  304. package/dist/storage/auth/in-memory/magic-links.d.ts.map +1 -1
  305. package/dist/storage/auth/in-memory/oidc-attempts.d.ts.map +1 -1
  306. package/dist/storage/auth/in-memory/sessions.d.ts +0 -10
  307. package/dist/storage/auth/in-memory/sessions.d.ts.map +1 -1
  308. package/dist/storage/auth/in-memory/shared.d.ts +1 -2
  309. package/dist/storage/auth/in-memory/shared.d.ts.map +1 -1
  310. package/dist/storage/auth/types.d.ts +1 -17
  311. package/dist/storage/auth/types.d.ts.map +1 -1
  312. package/dist/storage/connector-connections/provider.js +1 -1
  313. package/dist/storage/file-upload-sessions/provider.js +10 -10
  314. package/dist/storage/index.d.ts +2 -2
  315. package/dist/storage/index.d.ts.map +1 -1
  316. package/dist/storage/index.js +21 -22
  317. package/dist/storage/index.js.map +1 -1
  318. package/dist/storage/internal.d.ts +1 -1
  319. package/dist/storage/internal.d.ts.map +1 -1
  320. package/dist/storage/internal.js +9 -12
  321. package/dist/storage/internal.js.map +1 -1
  322. package/dist/storage/objects/execution-limits.d.ts +1 -1
  323. package/dist/storage/objects/execution-limits.d.ts.map +1 -1
  324. package/dist/storage/ontology/provider.js +2 -2
  325. package/dist/storage/projection-runs/provider.js +2 -2
  326. package/dist/storage/types.d.ts +1 -1
  327. package/dist/storage/types.d.ts.map +1 -1
  328. package/dist/storage/workflow-runs/provider.js +10 -10
  329. package/dist/syncs/index.js +29 -29
  330. package/dist/testing/action-execution.d.ts +34 -4
  331. package/dist/testing/action-execution.d.ts.map +1 -1
  332. package/dist/testing/action-run-storage-contract.d.ts +11 -0
  333. package/dist/testing/action-run-storage-contract.d.ts.map +1 -0
  334. package/dist/testing/auth-storage-contract.d.ts.map +1 -1
  335. package/dist/testing/index.d.ts +2 -1
  336. package/dist/testing/index.d.ts.map +1 -1
  337. package/dist/testing/index.js +3205 -2946
  338. package/dist/testing/index.js.map +9 -8
  339. package/dist/testing/materializer-storage-contract.d.ts.map +1 -1
  340. package/dist/testing/queues-contract.d.ts.map +1 -1
  341. package/dist/webhooks/internal.js +26 -26
  342. package/dist/webhooks/internal.js.map +1 -1
  343. package/dist/workers/index.js +1 -1
  344. package/dist/workflows/index.js +48 -51
  345. package/dist/workflows/index.js.map +1 -1
  346. package/package.json +8 -8
  347. package/src/actions/commit-edits.ts +9 -37
  348. package/src/actions/errors.ts +0 -4
  349. package/src/actions/execution.ts +10 -10
  350. package/src/actions/index.ts +5 -24
  351. package/src/actions/request.ts +157 -295
  352. package/src/actions/run/context.ts +193 -0
  353. package/src/actions/run/edits-commit.ts +102 -0
  354. package/src/actions/run/effects.ts +105 -0
  355. package/src/actions/run/execute.ts +113 -0
  356. package/src/actions/run/executor.ts +314 -0
  357. package/src/actions/run/normalize.ts +142 -0
  358. package/src/actions/run/phase-types.ts +20 -0
  359. package/src/actions/run/phases.ts +150 -0
  360. package/src/actions/run/run-action.ts +170 -0
  361. package/src/actions/run/signals.ts +118 -0
  362. package/src/actions/run/state.ts +95 -0
  363. package/src/actions/run/types.ts +61 -0
  364. package/src/actions/run/writeback.ts +79 -0
  365. package/src/actions/run-authorization.ts +1 -1
  366. package/src/actions/run-persistence.ts +105 -0
  367. package/src/actions/types/context.ts +10 -0
  368. package/src/auth/cookies.ts +3 -20
  369. package/src/auth/index.ts +0 -6
  370. package/src/auth/runtime.ts +59 -76
  371. package/src/auth/session-cache.ts +2 -9
  372. package/src/auth/types.ts +4 -8
  373. package/src/auth/validation.ts +0 -2
  374. package/src/authorization/decision.ts +8 -23
  375. package/src/authorization/event-visibility.ts +0 -12
  376. package/src/authorization/grant-kinds.ts +20 -27
  377. package/src/authorization/index.ts +0 -1
  378. package/src/authorization/resolve.ts +10 -6
  379. package/src/deploy/index.ts +0 -1
  380. package/src/deploy/services.ts +2 -12
  381. package/src/deploy/types.ts +7 -8
  382. package/src/deploy/validation.ts +15 -7
  383. package/src/error-reporting/types.ts +2 -10
  384. package/src/errors/catalog.ts +13 -0
  385. package/src/events/definitions.ts +0 -17
  386. package/src/events/index.ts +0 -14
  387. package/src/events/scope.ts +0 -12
  388. package/src/events/selectors/builder.ts +0 -51
  389. package/src/events/selectors/index.ts +0 -6
  390. package/src/events/selectors/predicate.ts +0 -2
  391. package/src/events/selectors/types.ts +7 -65
  392. package/src/events/types/index.ts +0 -11
  393. package/src/execution/authorization.ts +11 -5
  394. package/src/index.ts +2 -33
  395. package/src/materialization/model.ts +26 -9
  396. package/src/materializer/README.md +6 -1
  397. package/src/materializer/edits/commit.ts +42 -32
  398. package/src/materializer/shared/normalize.ts +25 -14
  399. package/src/models/execution/embedding.ts +6 -6
  400. package/src/objects/action/errors.ts +0 -12
  401. package/src/objects/action/index.ts +3 -3
  402. package/src/objects/action/request.ts +2 -29
  403. package/src/objects/execution.ts +2 -2
  404. package/src/objects/sdk/object-handle.ts +3 -29
  405. package/src/objects/sdk/object-set.ts +5 -30
  406. package/src/objects/service/index.ts +0 -1
  407. package/src/objects/vectors/README.md +4 -0
  408. package/src/objects/vectors/handle.ts +11 -2
  409. package/src/objects/vectors/indexing-generate.ts +2 -2
  410. package/src/objects/vectors/profile.ts +5 -0
  411. package/src/queues/in-memory.ts +0 -6
  412. package/src/queues/index.ts +0 -2
  413. package/src/queues/types.ts +0 -11
  414. package/src/runtime/host.ts +5 -0
  415. package/src/runtime/resolve-definitions.ts +0 -1
  416. package/src/runtime/types.ts +16 -45
  417. package/src/schedules/builders.ts +1 -4
  418. package/src/schedules/runtime.ts +0 -41
  419. package/src/schedules/validation.ts +2 -16
  420. package/src/security/builders.ts +7 -2
  421. package/src/security/every.ts +1 -5
  422. package/src/security/grants.ts +5 -25
  423. package/src/security/index.ts +0 -3
  424. package/src/security/membership-policies.ts +3 -1
  425. package/src/security/public.ts +10 -0
  426. package/src/security/registry.ts +0 -8
  427. package/src/security/types.ts +19 -25
  428. package/src/security/validation.ts +19 -17
  429. package/src/storage/action-runs/idempotency.ts +13 -41
  430. package/src/storage/action-runs/in-memory.ts +20 -311
  431. package/src/storage/action-runs/index.ts +1 -16
  432. package/src/storage/action-runs/record.ts +130 -0
  433. package/src/storage/action-runs/types.ts +37 -92
  434. package/src/storage/agents/types.ts +1 -1
  435. package/src/storage/auth/in-memory/auth-storage.ts +0 -18
  436. package/src/storage/auth/in-memory/magic-links.ts +0 -3
  437. package/src/storage/auth/in-memory/oidc-attempts.ts +0 -3
  438. package/src/storage/auth/in-memory/sessions.ts +1 -25
  439. package/src/storage/auth/in-memory/shared.ts +1 -10
  440. package/src/storage/auth/types.ts +2 -18
  441. package/src/storage/index.ts +1 -9
  442. package/src/storage/internal.ts +1 -7
  443. package/src/storage/objects/execution-limits.ts +3 -2
  444. package/src/storage/types.ts +2 -4
  445. package/src/testing/action-execution.ts +73 -13
  446. package/src/testing/action-run-storage-contract.ts +335 -0
  447. package/src/testing/auth-storage-contract.ts +14 -107
  448. package/src/testing/execution-storage-contract.ts +0 -2
  449. package/src/testing/index.ts +8 -1
  450. package/src/testing/materializer-storage-contract.ts +174 -18
  451. package/src/testing/queues-contract.ts +0 -18
  452. package/dist/actions/run-dispatch.d.ts +0 -25
  453. package/dist/actions/run-dispatch.d.ts.map +0 -1
  454. package/dist/actions/worker.d.ts +0 -3
  455. package/dist/actions/worker.d.ts.map +0 -1
  456. package/dist/actions/worker.js +0 -325
  457. package/dist/actions/worker.js.map +0 -11
  458. package/dist/auth/audience.d.ts +0 -8
  459. package/dist/auth/audience.d.ts.map +0 -1
  460. package/dist/authorization/application-access.d.ts +0 -18
  461. package/dist/authorization/application-access.d.ts.map +0 -1
  462. package/dist/chunk-1hqwggsn.js.map +0 -12
  463. package/dist/chunk-2jntasmh.js.map +0 -13
  464. package/dist/chunk-6h5m9xjx.js.map +0 -40
  465. package/dist/chunk-85cd7e8c.js +0 -51
  466. package/dist/chunk-85cd7e8c.js.map +0 -10
  467. package/dist/chunk-de4z2bj6.js.map +0 -18
  468. package/dist/chunk-dfm066qg.js.map +0 -11
  469. package/dist/chunk-enpsx8k5.js.map +0 -10
  470. package/dist/chunk-fc5zfxy1.js.map +0 -11
  471. package/dist/chunk-fe52eczz.js.map +0 -49
  472. package/dist/chunk-fx93hd2n.js +0 -1614
  473. package/dist/chunk-fx93hd2n.js.map +0 -20
  474. package/dist/chunk-k6hrnf35.js.map +0 -10
  475. package/dist/chunk-qkbx3tf6.js.map +0 -24
  476. package/dist/chunk-qxvp5epv.js +0 -1329
  477. package/dist/chunk-qxvp5epv.js.map +0 -36
  478. package/dist/chunk-r2y23egw.js.map +0 -10
  479. package/dist/chunk-tffvfy6s.js +0 -593
  480. package/dist/chunk-tffvfy6s.js.map +0 -15
  481. package/dist/chunk-xt1zt7gv.js.map +0 -13
  482. package/dist/chunk-y2aq6ag9.js.map +0 -11
  483. package/dist/chunk-y9jmd7e5.js.map +0 -15
  484. package/dist/chunk-zvx7h87b.js +0 -12
  485. package/dist/chunk-zvx7h87b.js.map +0 -10
  486. package/dist/events/types/actions.d.ts +0 -39
  487. package/dist/events/types/actions.d.ts.map +0 -1
  488. package/dist/objects/service/action-service.d.ts +0 -13
  489. package/dist/objects/service/action-service.d.ts.map +0 -1
  490. package/dist/security/applications.d.ts +0 -15
  491. package/dist/security/applications.d.ts.map +0 -1
  492. package/src/actions/run-dispatch.ts +0 -282
  493. package/src/actions/worker.ts +0 -2
  494. package/src/auth/audience.ts +0 -28
  495. package/src/authorization/application-access.ts +0 -34
  496. package/src/events/types/actions.ts +0 -42
  497. package/src/objects/service/action-service.ts +0 -43
  498. package/src/security/applications.ts +0 -11
  499. /package/dist/{chunk-rz53yb4v.js.map → chunk-0yh890a4.js.map} +0 -0
  500. /package/dist/{chunk-vgk3hknm.js.map → chunk-1k89ecfr.js.map} +0 -0
  501. /package/dist/{chunk-ny3xyvcn.js.map → chunk-1zq2p6g0.js.map} +0 -0
  502. /package/dist/{chunk-dnmadg9k.js.map → chunk-3t2hgbgd.js.map} +0 -0
  503. /package/dist/{chunk-22v5bpz3.js.map → chunk-5e43w60z.js.map} +0 -0
  504. /package/dist/{chunk-7hpdd6r9.js.map → chunk-6p49a5cq.js.map} +0 -0
  505. /package/dist/{chunk-kkqwzy6h.js.map → chunk-7t429e3f.js.map} +0 -0
  506. /package/dist/{chunk-ex496vct.js.map → chunk-9dmt152s.js.map} +0 -0
  507. /package/dist/{chunk-48e3cn2d.js.map → chunk-9gyp8hg1.js.map} +0 -0
  508. /package/dist/{chunk-zxawp1n2.js.map → chunk-9w055r5b.js.map} +0 -0
  509. /package/dist/{chunk-4wn7bxxa.js.map → chunk-9ybhtmg4.js.map} +0 -0
  510. /package/dist/{chunk-vx2yp45y.js.map → chunk-c85m1hyj.js.map} +0 -0
  511. /package/dist/{chunk-bs7sqkre.js.map → chunk-d09tj99x.js.map} +0 -0
  512. /package/dist/{chunk-zb77kjth.js.map → chunk-dk8tkk5f.js.map} +0 -0
  513. /package/dist/{chunk-vjcd8d27.js.map → chunk-fa02jy15.js.map} +0 -0
  514. /package/dist/{chunk-za5yd58j.js.map → chunk-fkgc1wt8.js.map} +0 -0
  515. /package/dist/{chunk-6gmfggss.js.map → chunk-t7x8dmn0.js.map} +0 -0
  516. /package/dist/{chunk-p844e0rn.js.map → chunk-tpn40322.js.map} +0 -0
  517. /package/dist/{chunk-rt9p8m9t.js.map → chunk-v9xd5wzd.js.map} +0 -0
  518. /package/dist/{chunk-2vhg6ysa.js.map → chunk-vyf9kfqf.js.map} +0 -0
  519. /package/dist/{chunk-bwjcehza.js.map → chunk-way52z4h.js.map} +0 -0
  520. /package/dist/{chunk-qkvz64nd.js.map → chunk-x6m907x7.js.map} +0 -0
  521. /package/dist/{chunk-yv9czyfr.js.map → chunk-xfs8x8m9.js.map} +0 -0
  522. /package/dist/{chunk-v6xpd60t.js.map → chunk-yevzdx4y.js.map} +0 -0
  523. /package/dist/{chunk-qmnnhde6.js.map → chunk-z4m0yz8c.js.map} +0 -0
@@ -0,0 +1,106 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/models/execution/binding.ts", "../src/assert-never.ts", "../src/objects/authorized-ontology-view.ts", "../src/objects/query/selected-read-admission.ts", "../src/objects/telemetry/workload.ts", "../src/execution/authorized-object-reader.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/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/run-authorization.ts", "../src/actions/request.ts", "../src/actions/execution.ts", "../src/runtime/ai-cost.ts", "../src/runtime/ai-usage.ts", "../src/agents/ids.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/sandbox.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/events/execution.ts", "../src/logging/execution.ts", "../src/agents/model-loop.ts", "../src/models/audio/runtime.ts", "../src/models/audio/file.ts", "../src/models/decision/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/link/authorization.ts", "../src/objects/link/remove.ts", "../src/objects/link/endpoints.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/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/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.\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
+ "/**\n * Closes a switch over a union: the call stops compiling when a new member has no case, and throws\n * if an untyped value reaches it at runtime.\n */\nexport function assertNever(_value: never, message: string): never {\n throw new Error(message)\n}\n",
7
+ "import {\n formatUnknownObjectTypeMessage,\n OntologyNotFoundError,\n OntologyValidationError,\n} from \"../ontology/errors\"\nimport type { OntologyDefinitionCatalog } from \"../ontology/registry\"\nimport type { ObjectTypeWithPropertyTokens } from \"../ontology/tokens\"\nimport { createLinkTokenMap, createPropertyTokenMap } from \"../ontology/tokens\"\nimport type {\n ObjectLink,\n ObjectType,\n ObjectTypeSearchMetadata,\n Property,\n PropertyQueryMetadata,\n Schema,\n ValueType,\n} from \"../ontology/types\"\nimport { snapshotVectorProfiles } from \"../ontology/vector-profiles\"\nimport type { CompiledSelectedObjectReadScope } from \"../storage/objects/types\"\n\n/** Public ontology operations that may cross an execution-bound authorization boundary. */\nexport type AuthorizedOntologyView = Pick<\n OntologyDefinitionCatalog,\n | \"listObjectTypes\"\n | \"getObjectTypeById\"\n | \"resolveObjectType\"\n | \"getValueTypesById\"\n | \"getPrimaryPropertyId\"\n | \"listSubTypes\"\n | \"isValidLinkTarget\"\n>\n\nexport type AuthorizedOntologySelection =\n | { readonly kind: \"all\" }\n | { readonly kind: \"types\"; readonly objectTypeIds: readonly string[] }\n | { readonly kind: \"selected\"; readonly scope: CompiledSelectedObjectReadScope }\n\ninterface LinkSelection {\n readonly targetObjectTypeIds: Set<string>\n readonly propertyIds: Set<string>\n}\n\ninterface SelectedSchema {\n readonly propertyIdsByObjectType: ReadonlyMap<string, ReadonlySet<string>>\n readonly linksBySourceType: ReadonlyMap<string, ReadonlyMap<string, LinkSelection>>\n}\n\n/**\n * Project inert ontology metadata from one already-captured authority.\n *\n * Query validation intentionally keeps using the complete internal registry. This view is only\n * the discovery surface returned to application code and HTTP serializers.\n */\nexport function createAuthorizedOntologyView(input: {\n readonly ontology: OntologyDefinitionCatalog\n readonly selection: AuthorizedOntologySelection\n readonly assertOutputWithinLimit?: (value: unknown) => void\n}): AuthorizedOntologyView {\n const allObjectTypes = input.ontology.listObjectTypes()\n const registeredObjectTypeIds = new Set(allObjectTypes.map((objectType) => objectType.id))\n const requestedObjectTypeIds = selectedObjectTypeIds(input.selection, allObjectTypes)\n const visibleObjectTypeIds = new Set(\n [...requestedObjectTypeIds].filter((objectTypeId) => registeredObjectTypeIds.has(objectTypeId))\n )\n const selectedSchema =\n input.selection.kind === \"selected\" ? collectSelectedSchema(input.selection.scope) : undefined\n const projectedObjectTypes: ObjectTypeWithPropertyTokens[] = []\n\n for (const objectType of allObjectTypes) {\n if (!visibleObjectTypeIds.has(objectType.id)) continue\n const propertyIds =\n selectedSchema?.propertyIdsByObjectType.get(objectType.id) ??\n new Set(objectType.properties.map((property) => property.id))\n const links = selectedSchema\n ? (selectedSchema.linksBySourceType.get(objectType.id) ?? new Map())\n : input.selection.kind === \"all\"\n ? allDeclaredLinks(objectType)\n : allVisibleLinks(input.ontology, objectType, visibleObjectTypeIds)\n projectedObjectTypes.push(\n projectObjectType({\n objectType,\n propertyIds,\n links,\n visibleObjectTypeIds,\n ontology: input.ontology,\n targetMode:\n input.selection.kind === \"all\"\n ? \"original\"\n : input.selection.kind === \"types\"\n ? \"principal\"\n : \"exact\",\n exposeContracts: input.selection.kind !== \"selected\",\n })\n )\n }\n\n const objectTypes = projectedObjectTypes\n const objectTypesById = new Map(objectTypes.map((objectType) => [objectType.id, objectType]))\n const valueTypesById =\n input.selection.kind === \"selected\"\n ? collectVisibleValueTypes(input.ontology.getValueTypesById(), objectTypes)\n : snapshotAllValueTypes(input.ontology.getValueTypesById())\n const release = <T>(value: T, budgetValue: unknown = value): T => {\n input.assertOutputWithinLimit?.(budgetValue)\n return value\n }\n const cloneObjectType = (objectType: ObjectTypeWithPropertyTokens) => structuredClone(objectType)\n const cloneValueTypes = () =>\n new Map(\n [...valueTypesById].map(([valueTypeId, valueType]) => [\n valueTypeId,\n structuredClone(valueType),\n ])\n )\n\n return Object.freeze({\n listObjectTypes: () => release(objectTypes.map(cloneObjectType)),\n getObjectTypeById: (objectTypeId: string) => {\n const objectType = objectTypesById.get(objectTypeId)\n return release(objectType ? cloneObjectType(objectType) : null)\n },\n resolveObjectType: (objectTypeId: string) => {\n const objectType = objectTypesById.get(objectTypeId)\n return objectType ? release(cloneObjectType(objectType)) : unknownObjectType(objectTypeId)\n },\n getValueTypesById: () => {\n const valueTypes = cloneValueTypes()\n return release(valueTypes, [...valueTypes.entries()])\n },\n getPrimaryPropertyId: (objectTypeId: string) => {\n const objectType = objectTypesById.get(objectTypeId)\n if (!objectType) return unknownObjectType(objectTypeId)\n const primary = objectType.properties.find((property) => property.primary)\n if (!primary) {\n throw new OntologyValidationError(\n `[Sixb] Object type '${objectTypeId}' does not expose its primary property in this execution scope.`\n )\n }\n return release(primary.id)\n },\n listSubTypes: (objectTypeId: string) => {\n const subTypes = visibleObjectTypeIds.has(objectTypeId)\n ? input.ontology\n .listSubTypes(objectTypeId)\n .filter((subTypeId) => visibleObjectTypeIds.has(subTypeId))\n : []\n return release(subTypes)\n },\n isValidLinkTarget: (expected: string | string[], actual: string) => {\n if (input.selection.kind === \"all\") {\n return release(input.ontology.isValidLinkTarget(expected, actual))\n }\n if (!visibleObjectTypeIds.has(actual)) return release(false)\n const expectedTypes = Array.isArray(expected) ? expected : [expected]\n if (input.selection.kind === \"selected\") {\n return release(\n expectedTypes.some((expectedType) => expectedType === \"*\" || expectedType === actual)\n )\n }\n return release(\n expectedTypes.some(\n (expectedType) =>\n expectedType === \"*\" ||\n (visibleObjectTypeIds.has(expectedType) &&\n input.ontology.isValidLinkTarget(expectedType, actual))\n )\n )\n },\n })\n}\n\nfunction selectedObjectTypeIds(\n selection: AuthorizedOntologySelection,\n allObjectTypes: readonly ObjectTypeWithPropertyTokens[]\n): ReadonlySet<string> {\n switch (selection.kind) {\n case \"all\":\n return new Set(allObjectTypes.map((objectType) => objectType.id))\n case \"types\":\n return new Set(selection.objectTypeIds)\n case \"selected\":\n return new Set(selection.scope.objects.map((object) => object.objectTypeId))\n }\n}\n\nfunction collectSelectedSchema(scope: CompiledSelectedObjectReadScope): SelectedSchema {\n const propertyIdsByObjectType = new Map<string, Set<string>>()\n for (const object of scope.objects) {\n const properties = propertyIdsByObjectType.get(object.objectTypeId) ?? new Set<string>()\n for (const propertyId of object.propertyIds) properties.add(propertyId)\n propertyIdsByObjectType.set(object.objectTypeId, properties)\n }\n\n const linksBySourceType = new Map<string, Map<string, LinkSelection>>()\n for (const step of scope.steps) {\n const links = linksBySourceType.get(step.sourceObjectTypeId) ?? new Map()\n const selected = links.get(step.linkId) ?? {\n targetObjectTypeIds: new Set<string>(),\n propertyIds: new Set<string>(),\n }\n selected.targetObjectTypeIds.add(step.targetObjectTypeId)\n for (const propertyId of step.propertyIds) selected.propertyIds.add(propertyId)\n links.set(step.linkId, selected)\n linksBySourceType.set(step.sourceObjectTypeId, links)\n }\n\n return { propertyIdsByObjectType, linksBySourceType }\n}\n\nfunction allDeclaredLinks(\n objectType: ObjectTypeWithPropertyTokens\n): ReadonlyMap<string, LinkSelection> {\n return new Map(\n objectType.links.map((link) => [\n link.id,\n {\n targetObjectTypeIds: new Set(\n typeof link.targetObjectTypeId === \"string\"\n ? [link.targetObjectTypeId]\n : link.targetObjectTypeId\n ),\n propertyIds: new Set(link.properties?.map((property) => property.id) ?? []),\n },\n ])\n )\n}\n\nfunction allVisibleLinks(\n ontology: OntologyDefinitionCatalog,\n objectType: ObjectTypeWithPropertyTokens,\n visibleObjectTypeIds: ReadonlySet<string>\n): ReadonlyMap<string, LinkSelection> {\n const links = new Map<string, LinkSelection>()\n for (const link of objectType.links) {\n const targetObjectTypeIds = new Set(\n [...visibleObjectTypeIds].filter((targetObjectTypeId) =>\n ontology.isValidLinkTarget(link.targetObjectTypeId, targetObjectTypeId)\n )\n )\n if (targetObjectTypeIds.size === 0) continue\n links.set(link.id, {\n targetObjectTypeIds,\n propertyIds: new Set(link.properties?.map((property) => property.id) ?? []),\n })\n }\n return links\n}\n\nfunction projectObjectType(input: {\n readonly ontology: OntologyDefinitionCatalog\n readonly objectType: ObjectTypeWithPropertyTokens\n readonly propertyIds: ReadonlySet<string>\n readonly links: ReadonlyMap<string, LinkSelection>\n readonly visibleObjectTypeIds: ReadonlySet<string>\n readonly targetMode: \"original\" | \"principal\" | \"exact\"\n readonly exposeContracts: boolean\n}): ObjectTypeWithPropertyTokens {\n const properties = input.objectType.properties\n .filter((property) => input.propertyIds.has(property.id))\n .map(snapshotProperty)\n const visiblePropertyIds = new Set(properties.map((property) => property.id))\n const links = input.objectType.links.flatMap((link): ObjectLink[] => {\n const selected = input.links.get(link.id)\n if (!selected) return []\n if (input.targetMode === \"original\") {\n return [snapshotLink(link, snapshotLinkTarget(link.targetObjectTypeId), selected.propertyIds)]\n }\n const targetObjectTypeIds = new Set(\n [...selected.targetObjectTypeIds].filter(\n (targetObjectTypeId) =>\n input.visibleObjectTypeIds.has(targetObjectTypeId) &&\n input.ontology.isValidLinkTarget(link.targetObjectTypeId, targetObjectTypeId)\n )\n )\n if (targetObjectTypeIds.size === 0) return []\n const target =\n input.targetMode === \"principal\"\n ? principalLinkTargets(link, targetObjectTypeIds, input.visibleObjectTypeIds)\n : exactLinkTargets(targetObjectTypeIds)\n return [snapshotLink(link, target, selected.propertyIds, { omitEmptyProperties: true })]\n })\n\n // Whitelist top-level metadata so future cross-ontology fields remain closed until reviewed.\n const projected: ObjectType = {\n id: input.objectType.id,\n name: input.objectType.name,\n description: input.objectType.description,\n quantityKind: input.objectType.quantityKind,\n seeAlso: input.objectType.seeAlso ? [...input.objectType.seeAlso] : undefined,\n extends:\n input.objectType.extends && input.visibleObjectTypeIds.has(input.objectType.extends)\n ? input.objectType.extends\n : undefined,\n parents: projectOptionalIds(\n input.objectType.parents,\n input.visibleObjectTypeIds,\n input.targetMode === \"original\"\n ),\n implements:\n input.exposeContracts && input.objectType.implements\n ? [...input.objectType.implements]\n : undefined,\n properties,\n links,\n search: projectSearch(input.objectType.search, visiblePropertyIds, {\n preserveEmpty: input.targetMode !== \"exact\",\n }),\n }\n const withTokens = {\n ...projected,\n p: createPropertyTokenMap(projected),\n l: createLinkTokenMap(projected),\n }\n return deepFreeze(withTokens) as ObjectTypeWithPropertyTokens\n}\n\nfunction principalLinkTargets(\n link: ObjectLink,\n allowedTargetObjectTypeIds: ReadonlySet<string>,\n visibleObjectTypeIds: ReadonlySet<string>\n): string | string[] {\n if (link.targetObjectTypeId === \"*\") return exactLinkTargets(allowedTargetObjectTypeIds)\n const declared = Array.isArray(link.targetObjectTypeId)\n ? link.targetObjectTypeId\n : [link.targetObjectTypeId]\n if (declared.every((objectTypeId) => visibleObjectTypeIds.has(objectTypeId))) {\n return snapshotLinkTarget(link.targetObjectTypeId)\n }\n return exactLinkTargets(allowedTargetObjectTypeIds)\n}\n\nfunction exactLinkTargets(targetObjectTypeIds: ReadonlySet<string>): string | string[] {\n const targets = [...targetObjectTypeIds].sort()\n return targets.length === 1 ? targets[0]! : targets\n}\n\nfunction projectOptionalIds(\n ids: readonly string[] | undefined,\n visibleObjectTypeIds: ReadonlySet<string>,\n preserveOriginal: boolean\n): string[] | undefined {\n if (!ids) return undefined\n if (preserveOriginal) return [...ids]\n const visible = ids.filter((id) => visibleObjectTypeIds.has(id))\n return visible.length > 0 ? visible : undefined\n}\n\nfunction snapshotLink(\n link: ObjectLink,\n targetObjectTypeId: string | string[],\n propertyIds: ReadonlySet<string>,\n options: { readonly omitEmptyProperties?: boolean } = {}\n): ObjectLink {\n const properties = link.properties\n ?.filter((property) => propertyIds.has(property.id))\n .map(snapshotProperty)\n return {\n id: link.id,\n name: link.name,\n description: link.description,\n targetObjectTypeId,\n cardinality: link.cardinality,\n properties: options.omitEmptyProperties && properties?.length === 0 ? undefined : properties,\n }\n}\n\nfunction snapshotLinkTarget(target: string | readonly string[]): string | string[] {\n return typeof target === \"string\" ? target : [...target]\n}\n\nfunction snapshotProperty(property: Property): Property {\n return {\n id: property.id,\n name: property.name,\n schema: snapshotSchema(property.schema),\n description: property.description,\n required: property.required,\n nullable: property.nullable,\n primary: property.primary,\n mode: property.mode,\n semanticType: property.semanticType,\n query: snapshotPropertyQuery(property.query),\n }\n}\n\nfunction snapshotPropertyQuery(\n query: PropertyQueryMetadata | undefined\n): PropertyQueryMetadata | undefined {\n if (!query) return undefined\n return {\n searchable: query.searchable,\n filterable: query.filterable,\n sortable: query.sortable,\n text: query.text,\n exact: query.exact,\n facet: query.facet,\n weight: query.weight,\n }\n}\n\nfunction projectSearch(\n search: ObjectTypeSearchMetadata | undefined,\n visiblePropertyIds: ReadonlySet<string>,\n options: { readonly preserveEmpty: boolean }\n): ObjectTypeSearchMetadata | undefined {\n if (!search) return undefined\n const title = search.title && visiblePropertyIds.has(search.title) ? search.title : undefined\n const selectedDefaultText = search.defaultText?.filter((propertyId) =>\n visiblePropertyIds.has(propertyId)\n )\n const selectedExact = search.exact?.filter((propertyId) => visiblePropertyIds.has(propertyId))\n const defaultText =\n options.preserveEmpty || selectedDefaultText?.length ? selectedDefaultText : undefined\n const exact = options.preserveEmpty || selectedExact?.length ? selectedExact : undefined\n const vectors =\n search.vectors === undefined\n ? undefined\n : snapshotVectorProfiles(\n Object.fromEntries(\n Object.entries(search.vectors).filter(([, profile]) =>\n profile.source.every((id) => visiblePropertyIds.has(id))\n )\n )\n )\n const projected: ObjectTypeSearchMetadata = {\n ...(vectors === undefined || Object.keys(vectors).length === 0 ? {} : { vectors }),\n ...(title === undefined ? {} : { title }),\n ...(defaultText === undefined ? {} : { defaultText }),\n ...(exact === undefined ? {} : { exact }),\n }\n return Object.keys(projected).length > 0 || options.preserveEmpty ? projected : undefined\n}\n\nfunction snapshotAllValueTypes(\n registered: ReadonlyMap<string, ValueType>\n): ReadonlyMap<string, ValueType> {\n return new Map(\n [...registered.values()].map((valueType) => {\n const snapshot = snapshotValueType(valueType)\n return [snapshot.id, snapshot] as const\n })\n )\n}\n\nfunction collectVisibleValueTypes(\n registered: ReadonlyMap<string, ValueType>,\n objectTypes: readonly ObjectTypeWithPropertyTokens[]\n): ReadonlyMap<string, ValueType> {\n const referencedIds = new Set<string>()\n const pendingSchemas: Schema[] = []\n const visitedSchemas = new Set<object>()\n for (const objectType of objectTypes) {\n for (const property of objectType.properties) pendingSchemas.push(property.schema)\n for (const link of objectType.links) {\n for (const property of link.properties ?? []) pendingSchemas.push(property.schema)\n }\n }\n\n while (pendingSchemas.length > 0) {\n const schema = pendingSchemas.pop()!\n if (typeof schema === \"string\" || visitedSchemas.has(schema)) continue\n visitedSchemas.add(schema)\n if (schema.type === \"valueTypeRef\") {\n if (!referencedIds.has(schema.valueTypeId)) {\n referencedIds.add(schema.valueTypeId)\n const valueType = registered.get(schema.valueTypeId)\n if (valueType) pendingSchemas.push(valueType.schema)\n }\n if (schema._resolved) pendingSchemas.push(schema._resolved)\n } else if (schema.type === \"object\") {\n for (const field of Object.values(schema.properties)) pendingSchemas.push(field.schema)\n } else if (schema.type === \"array\") {\n pendingSchemas.push(schema.items)\n } else if (schema.type === \"map\") {\n pendingSchemas.push(schema.valueSchema)\n }\n }\n\n return new Map(\n [...referencedIds]\n .map((valueTypeId) => registered.get(valueTypeId))\n .filter((valueType): valueType is ValueType => valueType !== undefined)\n .map((valueType) => {\n const snapshot = snapshotValueType(valueType)\n return [snapshot.id, snapshot] as const\n })\n )\n}\n\nfunction snapshotValueType(valueType: ValueType): ValueType {\n return deepFreeze({\n id: valueType.id,\n name: valueType.name,\n description: valueType.description,\n schema: snapshotSchema(valueType.schema),\n semanticType: valueType.semanticType,\n })\n}\n\nfunction snapshotSchema(schema: Schema): Schema {\n return deepFreeze(structuredClone(schema))\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\nfunction unknownObjectType(objectTypeId: string): never {\n throw new OntologyNotFoundError(formatUnknownObjectTypeMessage(objectTypeId))\n}\n",
8
+ "import { AuthorizationError } from \"../../authorization/errors\"\nimport type {\n CompiledObjectReadObjectSelection,\n CompiledObjectReadStep,\n CompiledSelectedObjectReadScope,\n} from \"../../storage/objects/types\"\nimport type {\n ObjectQueryAdmissionState,\n ObjectQueryAdmissionTransition,\n ObjectQueryEdgeUse,\n ObjectQueryPropertyUse,\n ObjectQuerySemanticAdmission,\n} from \"./validate\"\n\nconst selectedStateBrand = Symbol(\"sixb.selected-object-query-admission-state\")\n\ninterface SelectedObjectQueryState extends ObjectQueryAdmissionState {\n readonly [selectedStateBrand]: true\n readonly selections: readonly CompiledObjectReadObjectSelection[]\n}\n\nexport interface SelectedObjectQueryAdmission extends ObjectQuerySemanticAdmission {\n /** Terminal hook for property-bearing operations outside the query IR, such as facets. */\n assertPropertySelected(input: {\n readonly state: ObjectQueryAdmissionState\n readonly propertyId: string\n readonly objectTypeId?: string\n readonly use: ObjectQueryPropertyUse\n readonly path: string\n }): void\n /** Terminal hook for the physical-link selector that sits outside `queryLinks.query`. */\n assertIncidentEdgeSelected(input: {\n readonly state: ObjectQueryAdmissionState\n readonly linkId?: string\n readonly direction: \"outgoing\" | \"incoming\" | \"both\"\n readonly path: string\n }): void\n}\n\n/**\n * Build an immutable semantic admission over one already-compiled selected reader scope.\n *\n * Object identities remain provider-owned: query admission follows exact path occurrences while\n * the selected storage relation decides which live roots and linked instances exist.\n */\nexport function createSelectedObjectQueryAdmission(\n scope: CompiledSelectedObjectReadScope\n): SelectedObjectQueryAdmission {\n const selectionByKey = new Map<string, CompiledObjectReadObjectSelection>()\n const selectionsByType = new Map<string, CompiledObjectReadObjectSelection[]>()\n const propertiesBySelection = new Map<string, ReadonlySet<string>>()\n\n for (const selection of scope.objects) {\n const key = selectionKey(selection.nodeId, selection.objectTypeId)\n selectionByKey.set(key, selection)\n propertiesBySelection.set(key, new Set(selection.propertyIds))\n const byType = selectionsByType.get(selection.objectTypeId) ?? []\n byType.push(selection)\n selectionsByType.set(selection.objectTypeId, byType)\n }\n\n const outgoing = indexSteps(scope.steps, \"outgoing\", selectionByKey)\n const incoming = indexSteps(scope.steps, \"incoming\", selectionByKey)\n const emptyState = selectedState([])\n\n const admission: SelectedObjectQueryAdmission = {\n empty: () => emptyState,\n source: (input) => {\n const selections = input.result.objectTypeIds.flatMap(\n (objectTypeId) => selectionsByType.get(objectTypeId) ?? []\n )\n const state = selectedState(selections)\n\n if (input.kind === \"refs\") {\n const missingType = [...new Set(input.refs?.map((ref) => ref.objectTypeId) ?? [])]\n .sort()\n .find((objectTypeId) => !selectionsByType.has(objectTypeId))\n if (missingType) {\n return denied(\n state,\n new AuthorizationError(\n `view:object:${missingType}`,\n `[Sixb] Delegated query cannot reference object type '${missingType}' at '${input.path}': the selected object scope does not contain that type.`\n )\n )\n }\n }\n\n if (state.selections.length > 0) return { state }\n const objectTypeId = input.objectTypeId ?? input.result.objectTypeIds[0] ?? \"unknown\"\n return denied(\n state,\n new AuthorizationError(\n `view:object:${objectTypeId}`,\n `[Sixb] Delegated query cannot start from object type '${objectTypeId}' at '${input.path}': the selected object scope does not contain that type.`\n )\n )\n },\n property: (input) =>\n propertyDenial(\n asSelectedState(input.state),\n input.propertyId,\n input.objectTypeId,\n input.use,\n input.path,\n propertiesBySelection\n ),\n edge: (input) => {\n const state = asSelectedState(input.state)\n const next = followEdge(\n state,\n input.linkId,\n input.direction,\n input.sourceObjectTypeId,\n outgoing,\n incoming,\n input.result.objectTypeIds\n )\n if (next.selections.length > 0 || state.selections.length === 0) return { state: next }\n return denied(\n next,\n edgeDenial(\n state,\n input.linkId,\n input.direction,\n input.sourceObjectTypeId,\n input.use,\n input.path\n )\n )\n },\n set: ({ op, states }) => {\n if (op === \"subtract\") return asSelectedState(states[0] ?? emptyState)\n return selectedState(states.flatMap((state) => asSelectedState(state).selections))\n },\n assertPropertySelected: (input) => {\n const denial = propertyDenial(\n asSelectedState(input.state),\n input.propertyId,\n input.objectTypeId,\n input.use,\n input.path,\n propertiesBySelection\n )\n if (denial) throw denial\n },\n assertIncidentEdgeSelected: (input) => {\n if (input.linkId === undefined) return\n const state = asSelectedState(input.state)\n const directions: readonly (\"outgoing\" | \"incoming\")[] =\n input.direction === \"both\" ? [\"outgoing\", \"incoming\"] : [input.direction]\n const next = selectedState(\n directions.flatMap(\n (direction) =>\n followEdge(state, input.linkId!, direction, undefined, outgoing, incoming).selections\n )\n )\n if (next.selections.length > 0 || state.selections.length === 0) return\n throw edgeDenial(state, input.linkId, input.direction, undefined, \"queryLinks\", input.path)\n },\n }\n\n return Object.freeze(admission)\n}\n\nfunction indexSteps(\n steps: readonly CompiledObjectReadStep[],\n direction: \"outgoing\" | \"incoming\",\n selectionByKey: ReadonlyMap<string, CompiledObjectReadObjectSelection>\n): ReadonlyMap<string, readonly CompiledObjectReadObjectSelection[]> {\n const index = new Map<string, CompiledObjectReadObjectSelection[]>()\n for (const step of steps) {\n const fromKey =\n direction === \"outgoing\"\n ? selectionKey(step.parentNodeId, step.sourceObjectTypeId)\n : selectionKey(step.nodeId, step.targetObjectTypeId)\n const toKey =\n direction === \"outgoing\"\n ? selectionKey(step.nodeId, step.targetObjectTypeId)\n : selectionKey(step.parentNodeId, step.sourceObjectTypeId)\n const target = selectionByKey.get(toKey)\n if (!selectionByKey.has(fromKey) || !target) {\n throw new Error(\"[Sixb] Compiled selected object scope contains an invalid query path step.\")\n }\n const key = edgeKey(\n direction === \"outgoing\" ? step.parentNodeId : step.nodeId,\n direction === \"outgoing\" ? step.sourceObjectTypeId : step.targetObjectTypeId,\n step.linkId\n )\n const targets = index.get(key) ?? []\n targets.push(target)\n index.set(key, targets)\n }\n return index\n}\n\nfunction followEdge(\n state: SelectedObjectQueryState,\n linkId: string,\n direction: \"outgoing\" | \"incoming\",\n sourceObjectTypeId: string | undefined,\n outgoing: ReadonlyMap<string, readonly CompiledObjectReadObjectSelection[]>,\n incoming: ReadonlyMap<string, readonly CompiledObjectReadObjectSelection[]>,\n resultObjectTypeIds?: readonly string[]\n): SelectedObjectQueryState {\n const index = direction === \"outgoing\" ? outgoing : incoming\n const resultTypes = resultObjectTypeIds ? new Set(resultObjectTypeIds) : undefined\n const selections = state.selections.flatMap((selection) => {\n const candidates = index.get(edgeKey(selection.nodeId, selection.objectTypeId, linkId)) ?? []\n return candidates.filter(\n (candidate) =>\n (resultTypes === undefined || resultTypes.has(candidate.objectTypeId)) &&\n (direction === \"outgoing\" ||\n sourceObjectTypeId === undefined ||\n candidate.objectTypeId === sourceObjectTypeId)\n )\n })\n return selectedState(selections)\n}\n\nfunction propertyDenial(\n state: SelectedObjectQueryState,\n propertyId: string,\n objectTypeId: string | undefined,\n use: ObjectQueryPropertyUse,\n path: string,\n propertiesBySelection: ReadonlyMap<string, ReadonlySet<string>>\n): AuthorizationError | undefined {\n const candidates = objectTypeId\n ? state.selections.filter((selection) => selection.objectTypeId === objectTypeId)\n : state.selections\n // A selected reader has no rows for result types absent from this provenance. Those empty\n // branches cannot observe a property and must not make includeSubtypes queries fail closed.\n if (candidates.length === 0) return undefined\n\n const missing = candidates.find(\n (selection) =>\n !propertiesBySelection\n .get(selectionKey(selection.nodeId, selection.objectTypeId))\n ?.has(propertyId)\n )\n if (!missing) return undefined\n\n const objectTypeIds = [...new Set(candidates.map((selection) => selection.objectTypeId))].sort()\n return new AuthorizationError(\n `view:object:${objectTypeIds.join(\",\")}:property:${propertyId}`,\n `[Sixb] Delegated query cannot use property '${propertyId}' for ${use} at '${path}': it is not selected on every matching read-scope path (missing on ${formatSelection(missing)}).`\n )\n}\n\nfunction edgeDenial(\n state: SelectedObjectQueryState,\n linkId: string,\n direction: \"outgoing\" | \"incoming\" | \"both\",\n sourceObjectTypeId: string | undefined,\n use: ObjectQueryEdgeUse,\n path: string\n): AuthorizationError {\n const source = sourceObjectTypeId ? `:${sourceObjectTypeId}` : \"\"\n return new AuthorizationError(\n `view:link:${direction}${source}:${linkId}`,\n `[Sixb] Delegated query cannot use ${direction} link '${linkId}' for ${use} from ${formatState(state)} at '${path}': that exact read-scope path is not selected.`\n )\n}\n\nfunction formatState(state: SelectedObjectQueryState): string {\n if (state.selections.length === 0) return \"an empty read-scope provenance\"\n return `read-scope provenance ${state.selections.map(formatSelection).join(\", \")}`\n}\n\nfunction formatSelection(selection: CompiledObjectReadObjectSelection): string {\n return `'${selection.objectTypeId}'@node ${selection.nodeId}`\n}\n\nfunction selectedState(\n selections: readonly CompiledObjectReadObjectSelection[]\n): SelectedObjectQueryState {\n const unique = new Map<string, CompiledObjectReadObjectSelection>()\n for (const selection of selections) {\n unique.set(selectionKey(selection.nodeId, selection.objectTypeId), selection)\n }\n return Object.freeze({\n [selectedStateBrand]: true as const,\n selections: Object.freeze(\n [...unique.values()].sort(\n (left, right) =>\n left.nodeId - right.nodeId || left.objectTypeId.localeCompare(right.objectTypeId)\n )\n ),\n })\n}\n\nfunction asSelectedState(state: ObjectQueryAdmissionState): SelectedObjectQueryState {\n if ((state as Partial<SelectedObjectQueryState>)[selectedStateBrand] !== true) {\n throw new Error(\"[Sixb] Object query admission state belongs to another semantic admission.\")\n }\n return state as SelectedObjectQueryState\n}\n\nfunction denied(state: SelectedObjectQueryState, denial: Error): ObjectQueryAdmissionTransition {\n return { state, denial }\n}\n\nfunction selectionKey(nodeId: number, objectTypeId: string): string {\n return JSON.stringify([nodeId, objectTypeId])\n}\n\nfunction edgeKey(nodeId: number, objectTypeId: string, linkId: string): string {\n return JSON.stringify([nodeId, objectTypeId, linkId])\n}\n",
9
+ "const MAX_DELEGATED_TELEMETRY_HISTORY_SERIES = 100\nconst MAX_DELEGATED_TELEMETRY_HISTORY_POINTS = 10_000\nconst DEFAULT_DELEGATED_TELEMETRY_HISTORY_LIMIT_PER_SERIES = 100\n\nexport interface TelemetryHistoryReadWorkloadInput {\n readonly seriesCount: number\n readonly limitPerSeries?: number\n}\n\nexport interface TelemetryHistoryReadAdmission {\n readonly limitPerSeries?: number\n readonly maxPointOccurrences?: number\n}\n\ntype TelemetryHistoryWorkloadMetric = \"series\" | \"points\"\n\nclass TelemetryHistoryWorkloadExceededError extends Error {\n readonly name = \"TelemetryHistoryWorkloadExceededError\"\n readonly code = \"telemetry_history_workload_exceeded\"\n\n constructor(\n readonly metric: TelemetryHistoryWorkloadMetric,\n readonly limit: number\n ) {\n super(`[Sixb] Delegated telemetry history exceeded its ${metric} limit (${limit}).`)\n }\n}\n\n/** Resolve one history request without exposing the authority that selected its policy. */\nexport function admitTelemetryHistoryReadWorkload(\n input: TelemetryHistoryReadWorkloadInput,\n delegated: boolean\n): TelemetryHistoryReadAdmission {\n const seriesCount = input.seriesCount\n const limitPerSeries = input.limitPerSeries\n if (!Number.isSafeInteger(seriesCount) || seriesCount < 0) {\n throw new Error(\"[Sixb] Telemetry history series must have a non-negative safe integer length.\")\n }\n if (\n limitPerSeries !== undefined &&\n (!Number.isSafeInteger(limitPerSeries) || limitPerSeries < 0)\n ) {\n throw new Error(\"[Sixb] Telemetry history limit must be a non-negative safe integer.\")\n }\n\n if (!delegated) {\n const admission: TelemetryHistoryReadAdmission =\n limitPerSeries === undefined ? {} : { limitPerSeries }\n return Object.freeze(admission)\n }\n if (seriesCount > MAX_DELEGATED_TELEMETRY_HISTORY_SERIES) {\n throw new TelemetryHistoryWorkloadExceededError(\n \"series\",\n MAX_DELEGATED_TELEMETRY_HISTORY_SERIES\n )\n }\n if (seriesCount === 0) {\n return Object.freeze({\n ...(limitPerSeries === undefined ? {} : { limitPerSeries }),\n maxPointOccurrences: MAX_DELEGATED_TELEMETRY_HISTORY_POINTS,\n })\n }\n\n const maxLimitPerSeries = Math.floor(MAX_DELEGATED_TELEMETRY_HISTORY_POINTS / seriesCount)\n const effectiveLimitPerSeries =\n limitPerSeries ??\n Math.min(DEFAULT_DELEGATED_TELEMETRY_HISTORY_LIMIT_PER_SERIES, maxLimitPerSeries)\n if (effectiveLimitPerSeries > maxLimitPerSeries) {\n throw new TelemetryHistoryWorkloadExceededError(\n \"points\",\n MAX_DELEGATED_TELEMETRY_HISTORY_POINTS\n )\n }\n\n return Object.freeze({\n limitPerSeries: effectiveLimitPerSeries,\n maxPointOccurrences: MAX_DELEGATED_TELEMETRY_HISTORY_POINTS,\n })\n}\n",
10
+ "import { assertNever } from \"../assert-never\"\nimport { assertAuthorized, isAllowed } from \"../authorization\"\nimport { AuthorizationError } from \"../authorization/errors\"\nimport type { AuthorizationContext } from \"../authorization/types\"\nimport type { EmbeddingModelCatalog, RerankingModelCatalog } from \"../models/catalog\"\nimport {\n type AuthorizedOntologySelection,\n type AuthorizedOntologyView,\n createAuthorizedOntologyView,\n} from \"../objects/authorized-ontology-view\"\nimport {\n createClearanceQueryAdmission,\n type PropertyClearance,\n redactObjectRow,\n resolvePropertyClearance,\n} from \"../objects/property-clearance\"\nimport {\n countObjects,\n type ExecuteObjectCountInput,\n type ExecuteObjectCountResult,\n type ExecuteObjectExistsInput,\n type ExecuteObjectExistsResult,\n type ExecuteObjectFacetsInput,\n type ExecuteObjectFacetsResult,\n type ExecuteObjectQueryInput,\n type ExecuteObjectQueryLinksInput,\n type ExecuteObjectQueryLinksResult,\n type ExecuteObjectQueryResult,\n executeObjectQuery,\n executeObjectQueryLinks,\n existsObjects,\n facetObjects,\n} from \"../objects/query\"\nimport { ObjectQueryValidationError } from \"../objects/query/errors\"\nimport { validateObjectFacetRequests } from \"../objects/query/executor\"\nimport type { ObjectQuery } from \"../objects/query/ir\"\nimport { preflightObjectQueryLinks } from \"../objects/query/links\"\nimport {\n createSelectedObjectQueryAdmission,\n type SelectedObjectQueryAdmission,\n} from \"../objects/query/selected-read-admission\"\nimport {\n type AdmittedObjectQuery,\n composeObjectQueryAdmissions,\n type ObjectQuerySemanticAdmission,\n validateObjectQuery,\n validateObjectQueryWithAdmission,\n} from \"../objects/query/validate\"\nimport {\n admitTelemetryHistoryReadWorkload,\n type TelemetryHistoryReadAdmission,\n type TelemetryHistoryReadWorkloadInput,\n} from \"../objects/telemetry/workload\"\nimport type { OntologyRegistry } from \"../ontology\"\nimport type {\n CompiledObjectReadStep,\n LinkBatchKey,\n ObjectFacetRequest,\n ObjectLinkRow,\n ObjectReadStorage,\n ObjectRow,\n ObjectStorage,\n} from \"../storage\"\nimport { assertObjectReadOutputWithinLimit, MAX_OBJECT_READ_FACETS } from \"../storage\"\nimport { captureExecutionScope, resolveExecutionScopeAuthorization } from \"./authorization\"\nimport type { ExecutionScope, RuntimeAuthorization } from \"./types\"\n\ntype RuntimeReadAuthorization = {\n readonly projectId: string\n readonly runtimeAuthorization: RuntimeAuthorization\n readonly authorization?: AuthorizationContext\n}\n\ntype ResolvedExecutionAuthority = ReturnType<typeof resolveExecutionScopeAuthorization>\ntype GetObjectInput = Omit<Parameters<ObjectReadStorage[\"getByPrimaryId\"]>[0], \"projectId\">\ntype GetObjectsInput = Omit<Parameters<ObjectReadStorage[\"getByPrimaryIdBatch\"]>[0], \"projectId\">\ntype SelectObjectPropertiesInput = Parameters<ObjectReadStorage[\"selectsObjectProperties\"]>[0]\ntype CanReadObjectPropertyInput = SelectObjectPropertiesInput[\"items\"][number]\ntype CanReadObjectPropertiesBatchInput = Omit<SelectObjectPropertiesInput, \"projectId\">\ntype ListObjectsInput = Omit<Parameters<ObjectReadStorage[\"list\"]>[0], \"projectId\">\ntype ListLinksInput = Omit<Parameters<ObjectReadStorage[\"listLinks\"]>[0], \"projectId\">\ntype ListLinksBatchInput = Omit<Parameters<ObjectReadStorage[\"listLinksBatch\"]>[0], \"projectId\">\n\nconst readerConstructionKey = Object.freeze({})\n\n/**\n * Core-owned object read boundary for one exact execution authority.\n *\n * The implementation class is intentionally private to this module. Its private fields make the\n * exported instance type nominal, while the construction key prevents code that discovers the\n * JavaScript constructor through an instance from manufacturing another reader.\n */\nclass AuthorizedObjectReaderImpl {\n readonly #authorization: RuntimeAuthorization\n readonly #authority: ResolvedExecutionAuthority\n readonly #runtime: RuntimeReadAuthorization\n readonly #ontology: OntologyRegistry\n readonly #embeddingModels?: EmbeddingModelCatalog\n readonly #rerankingModels?: RerankingModelCatalog\n #ontologyView?: AuthorizedOntologyView\n readonly #storage: ObjectReadStorage\n readonly #delegatedObjectTypeIds?: ReadonlySet<string>\n readonly #delegatedLinkDefinitions?: ReadonlySet<string>\n readonly #delegatedQueryAdmission?: SelectedObjectQueryAdmission\n /** Marked properties this authority cannot read; absent when it reads every property. */\n readonly #clearance?: PropertyClearance\n\n constructor(\n key: typeof readerConstructionKey,\n input: {\n readonly scope: ExecutionScope\n readonly ontology: OntologyRegistry\n readonly embeddingModels?: EmbeddingModelCatalog\n readonly rerankingModels?: RerankingModelCatalog\n readonly storage: ObjectReadStorage\n readonly authority: ResolvedExecutionAuthority\n }\n ) {\n if (key !== readerConstructionKey) {\n throw new Error(\"[Sixb] AuthorizedObjectReader can only be created by Core.\")\n }\n\n this.#authorization = input.scope.authorization\n this.#authority = input.authority\n this.#ontology = input.ontology\n this.#embeddingModels = input.embeddingModels\n this.#rerankingModels = input.rerankingModels\n this.#storage = input.storage\n this.#delegatedObjectTypeIds =\n input.authority.type === \"delegated\"\n ? new Set(input.authority.objectRead.scope.objects.map((object) => object.objectTypeId))\n : undefined\n this.#delegatedLinkDefinitions =\n input.authority.type === \"delegated\"\n ? new Set(input.authority.objectRead.scope.steps.map(delegatedLinkDefinitionKey))\n : undefined\n this.#delegatedQueryAdmission =\n input.authority.type === \"delegated\"\n ? createSelectedObjectQueryAdmission(input.authority.objectRead.scope)\n : undefined\n this.#clearance = clearanceForAuthority(input.authority, input.ontology)\n this.#runtime = Object.freeze({\n projectId: input.scope.execution.projectId,\n runtimeAuthorization: input.scope.authorization,\n ...(input.authority.type === \"principal\" ? { authorization: input.authority.context } : {}),\n })\n }\n\n static assertBound(reader: AuthorizedObjectReaderImpl, scope: ExecutionScope): void {\n const capturedScope = captureExecutionScope(scope)\n resolveExecutionScopeAuthorization(reader.#runtime.projectId, capturedScope)\n if (capturedScope.authorization !== reader.#authorization) {\n throw new Error(\n \"[Sixb] AuthorizedObjectReader is not bound to this exact execution authority.\"\n )\n }\n }\n\n static ontologyView(reader: AuthorizedObjectReaderImpl): AuthorizedOntologyView {\n const authority = reader.#authority\n reader.#ontologyView ??= createAuthorizedOntologyView({\n ontology: reader.#ontology,\n selection: ontologySelectionForAuthority(authority, reader.#ontology),\n ...(authority.type === \"delegated\"\n ? {\n assertOutputWithinLimit: (value: unknown) =>\n assertObjectReadOutputWithinLimit(value, authority.objectRead.limits),\n }\n : {}),\n })\n return reader.#ontologyView\n }\n\n /** Project identity carried by this nominal reader capability. */\n get projectId(): string {\n return this.#runtime.projectId\n }\n\n async getByPrimaryId(input: GetObjectInput): ReturnType<ObjectReadStorage[\"getByPrimaryId\"]> {\n const request = snapshotReadValue({\n objectTypeId: input.objectTypeId,\n primaryId: input.primaryId,\n })\n this.#assertObjectTypesViewable([request.objectTypeId])\n const row = await this.#storage.getByPrimaryId({\n ...request,\n projectId: this.#runtime.projectId,\n })\n return detachReadResult(row && this.#redact(row))\n }\n\n async getByPrimaryIdBatch(\n input: GetObjectsInput\n ): ReturnType<ObjectReadStorage[\"getByPrimaryIdBatch\"]> {\n const request = snapshotReadValue({\n items: input.items.map((item) => ({\n objectTypeId: item.objectTypeId,\n primaryId: item.primaryId,\n })),\n })\n this.#assertObjectTypesViewable(request.items.map((item) => item.objectTypeId))\n const rows = await this.#storage.getByPrimaryIdBatch({\n ...request,\n projectId: this.#runtime.projectId,\n })\n return detachReadResult(\n new Map([...rows].map(([key, row]) => [key, this.#redact(row)] as const))\n )\n }\n\n async canReadObjectProperty(input: CanReadObjectPropertyInput): Promise<boolean> {\n const request = snapshotReadValue({\n objectTypeId: input.objectTypeId,\n primaryId: input.primaryId,\n propertyId: input.propertyId,\n })\n this.#assertObjectTypesViewable([request.objectTypeId])\n if (this.#hidesProperty(request)) return false\n if (this.#authority.type !== \"delegated\") return true\n const [readable] = await this.#storage.selectsObjectProperties({\n projectId: this.#runtime.projectId,\n items: [request],\n })\n return readable ?? false\n }\n\n async canReadObjectPropertiesBatch(\n input: CanReadObjectPropertiesBatchInput\n ): Promise<readonly boolean[]> {\n const request = snapshotReadValue({\n items: input.items.map((item) => ({\n objectTypeId: item.objectTypeId,\n primaryId: item.primaryId,\n propertyId: item.propertyId,\n })),\n })\n this.#assertObjectTypesViewable(request.items.map((item) => item.objectTypeId))\n const selected =\n this.#authority.type === \"delegated\"\n ? await this.#storage.selectsObjectProperties({\n ...request,\n projectId: this.#runtime.projectId,\n })\n : request.items.map(() => true)\n return request.items.map(\n (item, index) => !this.#hidesProperty(item) && selected[index] === true\n )\n }\n\n async list(input: ListObjectsInput): ReturnType<ObjectReadStorage[\"list\"]> {\n const request = snapshotReadValue({\n objectTypeId:\n typeof input.objectTypeId === \"string\"\n ? input.objectTypeId\n : input.objectTypeId === undefined\n ? undefined\n : [...input.objectTypeId],\n primaryIdPrefix: input.primaryIdPrefix,\n primaryIdSuffix: input.primaryIdSuffix,\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 const objectTypeId = this.#resolveListObjectTypes(request.objectTypeId)\n\n // An empty type selection means \"none\", never \"all\". Short-circuiting here prevents a\n // provider with different empty-array semantics from turning a principal read into a broad one.\n if (Array.isArray(objectTypeId) && objectTypeId.length === 0) {\n return { objects: [], hasMore: false, total: 0 }\n }\n\n const page = await this.#storage.list({\n ...request,\n ...(objectTypeId === undefined ? {} : { objectTypeId }),\n projectId: this.#runtime.projectId,\n })\n return detachReadResult({ ...page, objects: page.objects.map((row) => this.#redact(row)) })\n }\n\n async listLinks(input: ListLinksInput): ReturnType<ObjectReadStorage[\"listLinks\"]> {\n const request = snapshotReadValue({\n objectTypeId: input.objectTypeId,\n objectId: input.objectId,\n linkId: input.linkId,\n direction: input.direction,\n })\n this.#assertObjectTypesViewable([request.objectTypeId])\n const links = detachReadResult(\n await this.#storage.listLinks({\n ...request,\n projectId: this.#runtime.projectId,\n })\n )\n return links.filter((link) => this.#isLinkViewable(link))\n }\n\n async listLinksBatch(\n input: ListLinksBatchInput\n ): ReturnType<ObjectReadStorage[\"listLinksBatch\"]> {\n const request = snapshotReadValue({\n direction: input.direction,\n items: input.items.map((item) => ({\n objectTypeId: item.objectTypeId,\n objectId: item.objectId,\n linkId: item.linkId,\n })),\n })\n this.#assertObjectTypesViewable(request.items.map((item) => item.objectTypeId))\n const pages = detachReadResult(\n await this.#storage.listLinksBatch({\n ...request,\n projectId: this.#runtime.projectId,\n })\n )\n const filtered = new Map<LinkBatchKey, ObjectLinkRow[]>()\n for (const [key, links] of pages) {\n filtered.set(\n key,\n links.filter((link) => this.#isLinkViewable(link))\n )\n }\n return filtered\n }\n\n async executeQuery(\n input: Omit<ExecuteObjectQueryInput, \"projectId\">\n ): Promise<ExecuteObjectQueryResult> {\n const query = snapshotAuthoredQuery(input.query)\n const includeTotal = snapshotReadValue(input.includeTotal)\n const executionQuery = this.#admitDelegatedQuery(query)?.query ?? query\n const result = await executeObjectQuery(\n {\n query: executionQuery,\n ...(includeTotal === undefined ? {} : { includeTotal }),\n projectId: this.#runtime.projectId,\n signal: input.signal,\n },\n this.#queryExecutorOptions()\n )\n return detachReadResult({ ...result, objects: result.objects.map((row) => this.#redact(row)) })\n }\n\n async queryLinks(\n input: Omit<ExecuteObjectQueryLinksInput, \"projectId\">\n ): Promise<ExecuteObjectQueryLinksResult> {\n const query = snapshotAuthoredQuery(input.query)\n const request = snapshotReadValue({\n direction: input.direction,\n linkId: input.linkId,\n includeObjects: input.includeObjects,\n pageSize: input.pageSize,\n pageToken: input.pageToken,\n })\n let executionQuery = query\n const admission = this.#delegatedQueryAdmission\n if (admission) {\n const preflight = preflightObjectQueryLinks(\n { query, ...request, projectId: this.#runtime.projectId },\n { ontology: this.#ontology }\n )\n const admitted = validateObjectQueryWithAdmission(\n preflight.validated.query,\n { ontology: this.#ontology, normalize: false },\n admission\n )\n admission.assertIncidentEdgeSelected({\n state: admitted.admissionState,\n ...(preflight.linkId === undefined ? {} : { linkId: preflight.linkId }),\n direction: preflight.direction,\n path: \"$.linkId\",\n })\n executionQuery = admitted.query\n }\n const result = detachReadResult(\n await executeObjectQueryLinks(\n { query: executionQuery, ...request, projectId: this.#runtime.projectId },\n this.#queryExecutorOptions()\n )\n )\n\n // Link pagination is computed by the provider-facing executor. Filtering afterward would make\n // its cursor and hasMore metadata describe hidden rows, so a provider contract violation must\n // fail closed instead of returning a partially filtered page.\n if (\n result.objects.some((row) => !this.#isObjectTypeViewable(row.objectTypeId)) ||\n result.links.some((link) => !this.#isLinkViewable(link))\n ) {\n throw new Error(\"[Sixb] Object storage returned a link page outside its authorized scope.\")\n }\n return { ...result, objects: result.objects.map((row) => this.#redact(row)) }\n }\n\n async count(\n input: Omit<ExecuteObjectCountInput, \"projectId\">\n ): Promise<ExecuteObjectCountResult> {\n const query = snapshotAuthoredQuery(input.query)\n const executionQuery = this.#admitDelegatedQuery(query)?.query ?? query\n return detachReadResult(\n await countObjects(\n { query: executionQuery, projectId: this.#runtime.projectId },\n this.#queryExecutorOptions()\n )\n )\n }\n\n async exists(\n input: Omit<ExecuteObjectExistsInput, \"projectId\">\n ): Promise<ExecuteObjectExistsResult> {\n const query = snapshotAuthoredQuery(input.query)\n const executionQuery = this.#admitDelegatedQuery(query)?.query ?? query\n return detachReadResult(\n await existsObjects(\n { query: executionQuery, projectId: this.#runtime.projectId },\n this.#queryExecutorOptions()\n )\n )\n }\n\n async facet(\n input: Omit<ExecuteObjectFacetsInput, \"projectId\">\n ): Promise<ExecuteObjectFacetsResult> {\n const query = snapshotAuthoredQuery(input.query)\n const facets = snapshotFacetRequests(input.facets)\n let executionQuery = query\n let executionFacets = facets\n const admission = this.#delegatedQueryAdmission\n if (admission) {\n // Terminal arguments are ordinary validation errors, not an authorization oracle. Validate\n // them against the canonical result shape before raising any delegated-scope denial.\n const validated = validateObjectQuery(query, { ontology: this.#ontology })\n const normalizedFacets = validateObjectFacetRequests(facets, validated.result.objectTypeIds, {\n ontology: this.#ontology,\n })\n const admitted = validateObjectQueryWithAdmission(\n validated.query,\n { ontology: this.#ontology, normalize: false },\n admission\n )\n normalizedFacets.forEach((facet, index) => {\n admission.assertPropertySelected({\n state: admitted.admissionState,\n propertyId: facet.propertyId,\n use: \"facet\",\n path: `$.facets[${index}].propertyId`,\n })\n })\n executionQuery = admitted.query\n executionFacets = normalizedFacets\n }\n return detachReadResult(\n await facetObjects(\n {\n query: executionQuery,\n facets: executionFacets,\n projectId: this.#runtime.projectId,\n },\n this.#queryExecutorOptions()\n )\n )\n }\n\n /**\n * Redact a row returned by a write. An upsert returns the merged effective row, which may hold\n * marked values the writer never sent and cannot read.\n */\n redactWrittenRow<TRow extends ObjectRow>(row: TRow): TRow {\n return this.#redact(row)\n }\n\n /** Enforce the delegated response budget without exposing or recombining its limits. */\n assertVisibleOutputWithinLimit(value: unknown): void {\n if (this.#authority.type !== \"delegated\") return\n assertObjectReadOutputWithinLimit(value, this.#authority.objectRead.limits)\n }\n\n /** Admit adjacent telemetry work without exposing which authority policy was selected. */\n admitTelemetryHistoryRead(\n input: TelemetryHistoryReadWorkloadInput\n ): TelemetryHistoryReadAdmission {\n return admitTelemetryHistoryReadWorkload(input, this.#authority.type === \"delegated\")\n }\n\n #queryExecutorOptions() {\n const admission = this.#executorAdmission()\n if (this.#authority.type === \"delegated\") {\n // The selected storage instance is the private execution capability. Passing the delegated\n // runtime token into the generic executor would either reject this admitted query or tempt a\n // forgeable bypass flag; neither is needed at this nominal boundary.\n return {\n ontology: this.#ontology,\n storage: this.#storage,\n embeddingModels: this.#embeddingModels,\n rerankingModels: this.#rerankingModels,\n ...(admission === undefined ? {} : { admission }),\n }\n }\n return {\n ontology: this.#ontology,\n embeddingModels: this.#embeddingModels,\n rerankingModels: this.#rerankingModels,\n storage: this.#storage,\n runtimeAuthorization: this.#runtime.runtimeAuthorization,\n ...(this.#runtime.authorization === undefined\n ? {}\n : { authorization: this.#runtime.authorization }),\n ...(admission === undefined ? {} : { admission }),\n }\n }\n\n /**\n * The executor validates the query it runs, and that validation resolves default text fields.\n * Every admission that narrows those fields must therefore apply there, not only beforehand.\n */\n #executorAdmission(): ObjectQuerySemanticAdmission | undefined {\n const clearance = this.#clearance && createClearanceQueryAdmission(this.#clearance)\n const selected = this.#delegatedQueryAdmission\n if (selected && clearance) return composeObjectQueryAdmissions(selected, clearance)\n return selected ?? clearance\n }\n\n #redact<TRow extends ObjectRow>(row: TRow): TRow {\n return this.#clearance ? redactObjectRow(row, this.#clearance) : row\n }\n\n #hidesProperty(item: { readonly objectTypeId: string; readonly propertyId: string }): boolean {\n return this.#clearance?.hiddenPropertyIds(item.objectTypeId).has(item.propertyId) ?? false\n }\n\n #admitDelegatedQuery(query: ObjectQuery): AdmittedObjectQuery | undefined {\n if (!this.#delegatedQueryAdmission) return undefined\n return validateObjectQueryWithAdmission(\n query,\n { ontology: this.#ontology },\n this.#delegatedQueryAdmission\n )\n }\n\n #assertObjectTypesViewable(objectTypeIds: readonly string[]): void {\n if (this.#authority.type === \"delegated\") {\n for (const objectTypeId of new Set(objectTypeIds)) {\n if (this.#delegatedObjectTypeIds?.has(objectTypeId)) continue\n throw new AuthorizationError(\n `delegated:object.view:${objectTypeId}`,\n `[Sixb] Delegated authorization does not select object type '${objectTypeId}'.`\n )\n }\n return\n }\n\n for (const objectTypeId of new Set(objectTypeIds)) {\n assertAuthorized(this.#runtime, { kind: \"object.view\", objectTypeId })\n }\n }\n\n #resolveListObjectTypes(\n requested: ListObjectsInput[\"objectTypeId\"]\n ): ListObjectsInput[\"objectTypeId\"] {\n if (requested !== undefined) {\n const objectTypeIds = typeof requested === \"string\" ? [requested] : [...new Set(requested)]\n for (const objectTypeId of objectTypeIds) {\n this.#ontology.resolveObjectType(objectTypeId)\n }\n this.#assertObjectTypesViewable(objectTypeIds)\n return typeof requested === \"string\" ? requested : objectTypeIds\n }\n\n if (this.#authority.type === \"unrestricted\") return undefined\n return this.#ontology\n .listObjectTypes()\n .map((objectType) => objectType.id)\n .filter((objectTypeId) => this.#isObjectTypeViewable(objectTypeId))\n }\n\n #isObjectTypeViewable(objectTypeId: string): boolean {\n if (this.#authority.type === \"delegated\") {\n return this.#delegatedObjectTypeIds?.has(objectTypeId) ?? false\n }\n return isAllowed(this.#runtime.authorization, { kind: \"object.view\", objectTypeId })\n }\n\n #isLinkViewable(link: ObjectLinkRow): boolean {\n if (\n !this.#isObjectTypeViewable(link.sourceTypeId) ||\n !this.#isObjectTypeViewable(link.targetTypeId)\n ) {\n return false\n }\n return (\n this.#delegatedLinkDefinitions?.has(delegatedLinkDefinitionKey(link)) ??\n this.#authority.type !== \"delegated\"\n )\n }\n}\n\nObject.freeze(AuthorizedObjectReaderImpl.prototype)\nObject.freeze(AuthorizedObjectReaderImpl)\n\nexport type AuthorizedObjectReader = AuthorizedObjectReaderImpl\n\n/** Build the sole application-facing object reader for one registered execution scope. */\nexport function createAuthorizedObjectReader(input: {\n readonly scope: ExecutionScope\n readonly ontology: OntologyRegistry\n readonly embeddingModels?: EmbeddingModelCatalog\n readonly rerankingModels?: RerankingModelCatalog\n readonly objectStorage: ObjectStorage\n}): AuthorizedObjectReader {\n const scope = captureExecutionScope(input.scope)\n const projectId = scope.execution.projectId\n const authority = resolveExecutionScopeAuthorization(projectId, scope)\n const storage = objectStorageForAuthority(authority, input.objectStorage)\n const reader = new AuthorizedObjectReaderImpl(readerConstructionKey, {\n scope,\n ontology: input.ontology,\n embeddingModels: input.embeddingModels,\n rerankingModels: input.rerankingModels,\n storage,\n authority,\n })\n Object.freeze(reader)\n return reader\n}\n\n/** Reject recombining an authorized reader with any other execution authority. */\nexport function assertAuthorizedObjectReaderBinding(input: {\n readonly reader: AuthorizedObjectReader\n readonly scope: ExecutionScope\n}): void {\n AuthorizedObjectReaderImpl.assertBound(input.reader, input.scope)\n}\n\n/** Return inert metadata projected from the exact authority already owned by the reader. */\nexport function getAuthorizedOntologyView(reader: AuthorizedObjectReader): AuthorizedOntologyView {\n return AuthorizedObjectReaderImpl.ontologyView(reader)\n}\n\n/**\n * Unrestricted authority reads every property. A principal reads what its roles clear; delegated\n * shared access carries no clearance, so no share can expose a marked property.\n */\nfunction clearanceForAuthority(\n authority: ResolvedExecutionAuthority,\n ontology: OntologyRegistry\n): PropertyClearance | undefined {\n switch (authority.type) {\n case \"unrestricted\":\n return undefined\n case \"principal\":\n return resolvePropertyClearance(ontology, authority.context.clearances ?? new Set())\n case \"delegated\":\n return resolvePropertyClearance(ontology, new Set())\n }\n}\n\nfunction objectStorageForAuthority(\n authority: ResolvedExecutionAuthority,\n objectStorage: ObjectStorage\n): ObjectReadStorage {\n switch (authority.type) {\n case \"principal\":\n case \"unrestricted\":\n return objectStorage\n case \"delegated\":\n return objectStorage.createSelectedReadScope({\n projectId: authority.projectId,\n scope: authority.objectRead.scope,\n limits: authority.objectRead.limits,\n })\n default:\n return assertNever(\n authority,\n `[Sixb] Unsupported object reader authority '${String((authority as { type?: unknown }).type)}'.`\n )\n }\n}\n\nfunction ontologySelectionForAuthority(\n authority: ResolvedExecutionAuthority,\n ontology: OntologyRegistry\n): AuthorizedOntologySelection {\n switch (authority.type) {\n case \"unrestricted\":\n return { kind: \"all\" }\n case \"principal\":\n return {\n kind: \"types\",\n objectTypeIds: ontology\n .listObjectTypes()\n .filter((objectType) =>\n isAllowed(authority.context, {\n kind: \"object.view\",\n objectTypeId: objectType.id,\n })\n )\n .map((objectType) => objectType.id),\n }\n case \"delegated\":\n return { kind: \"selected\", scope: authority.objectRead.scope }\n }\n}\n\nfunction delegatedLinkDefinitionKey(\n input:\n | Pick<CompiledObjectReadStep, \"sourceObjectTypeId\" | \"linkId\" | \"targetObjectTypeId\">\n | Pick<ObjectLinkRow, \"sourceTypeId\" | \"linkId\" | \"targetTypeId\">\n): string {\n return \"sourceObjectTypeId\" in input\n ? JSON.stringify([input.sourceObjectTypeId, input.linkId, input.targetObjectTypeId])\n : JSON.stringify([input.sourceTypeId, input.linkId, input.targetTypeId])\n}\n\n/**\n * Storage providers may optimize trusted reads with live references. Values crossing the\n * application-facing authorization boundary must not retain them.\n */\nfunction detachReadResult<T>(value: T): T {\n return structuredClone(value)\n}\n\n/** Capture caller-owned values before authorization and execution. */\nfunction snapshotReadValue<T>(value: T): T {\n return structuredClone(value)\n}\n\n/** Bound and capture facet arguments before reading any caller-owned element. */\nfunction snapshotFacetRequests(facets: readonly ObjectFacetRequest[]): ObjectFacetRequest[] {\n if (!Array.isArray(facets)) {\n throw new ObjectQueryValidationError([\n {\n path: \"$.facets\",\n code: \"invalid_facets\",\n message: \"facets must be an array\",\n },\n ])\n }\n const length = facets.length\n if (!Number.isSafeInteger(length) || length > MAX_OBJECT_READ_FACETS) {\n throw new ObjectQueryValidationError([\n {\n path: \"$.facets\",\n code: \"too_many_facets\",\n message: `facets must include at most ${MAX_OBJECT_READ_FACETS} facet requests`,\n },\n ])\n }\n\n const snapshot: ObjectFacetRequest[] = []\n for (let index = 0; index < length; index += 1) {\n const facet = facets[index]\n snapshot.push({ propertyId: facet.propertyId, limit: facet.limit })\n }\n return snapshot\n}\n\n/** Capture one serializable query before either authorization or execution sees it. */\nfunction snapshotAuthoredQuery(query: ObjectQuery): ObjectQuery {\n try {\n const snapshot = structuredClone(query)\n const pending = [snapshot]\n const seen = new Set<ObjectQuery>()\n for (const node of pending) {\n if (seen.has(node)) continue\n seen.add(node)\n if (\n node.kind === \"vector\" &&\n (typeof node.vector !== \"string\" ||\n typeof node.profile !== \"string\" ||\n \"propertyId\" in node)\n ) {\n throw new ObjectQueryValidationError([\n {\n path: \"$\",\n code: \"invalid_vector_search_input\",\n message: \"Vector search requires a named profile and search text\",\n },\n ])\n }\n if (\"input\" in node) pending.push(node.input)\n if (node.kind === \"set\") pending.push(...node.inputs)\n }\n return snapshot\n } catch (error) {\n if (error instanceof ObjectQueryValidationError) throw error\n throw new ObjectQueryValidationError([\n {\n path: \"$\",\n code: \"query_not_cloneable\",\n message: \"Object query must contain only structured-cloneable data\",\n },\n ])\n }\n}\n",
11
+ "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",
12
+ "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",
13
+ "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",
14
+ "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",
15
+ "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",
16
+ "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",
17
+ "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} 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\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 dependencies(): ActionReadDependencies {\n return {\n objects: [...this.objects.values()],\n links: [...this.links.values()],\n linkScopes: [...this.linkScopes.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 /** 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 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",
18
+ "import { createSixbError } from \"../../errors/internal\"\nimport type { Logger } from \"../../logging\"\nimport type { ObjectTypeWithPropertyTokens } from \"../../ontology/tokens\"\nimport { ObjectNotFoundError } 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 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 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 }\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 return {\n subjectObjectType,\n snapshot: toActionTargetObject(targetRow, input.action.binding.objectType.id),\n row: targetRow,\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",
19
+ "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 /** Test-only override of {@link ACTION_TIMEOUT_MS}. */\n readonly timeoutMs?: number\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(\n input: Pick<ActionRunSignalsInput, \"actionId\" | \"runId\" | \"timeoutMs\">,\n scope: \"run\" | \"effects\"\n ) {\n const controller = new AbortController()\n const timeoutMs = input.timeoutMs ?? ACTION_TIMEOUT_MS\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 ${timeoutMs} ms ${scope} deadline.`,\n { details: { actionId: input.actionId, runId: input.runId } }\n )\n )\n }, timeoutMs)\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",
20
+ "import {\n createSixbError,\n isSixbError,\n type SixbCodedError,\n summarizeErrorMessage,\n toSixbFailure,\n} from \"../../errors/internal\"\nimport { isMaterializationConflictError } from \"../../materialization/errors\"\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.\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 (phase === \"commit\" && isMaterializationConflictError(error) && error.kind === \"expectation\") {\n return createSixbError(\"action.read_conflict\", error.message, { cause: error, details })\n }\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\" || error.code === \"action.read_conflict\")\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",
21
+ "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",
22
+ "import { 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 new ActionValidationError(result.error, {\n actionId: input.action.id,\n subject: input.subject,\n })\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 new ActionValidationError(result.error, {\n actionId: input.action.id,\n subject: input.subject,\n })\n }\n }\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",
23
+ "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",
24
+ "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",
25
+ "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 } 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}\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 })\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",
26
+ "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",
27
+ "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",
28
+ "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 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",
29
+ "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",
30
+ "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 * Record a failed run, and report its failure to `onError` once this request recorded it. A run its\n * caller cancelled is not reported: it did not fail on its own.\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 && record.error.code !== \"runtime.cancelled\") {\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",
31
+ "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 { ActionRunContext, ActionRunOutcome, PendingActionRun } 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 /** Test-only override of the 30-second deadlines of the run and of its effects. */\n readonly timeoutMs?: number\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 timeoutMs: input.timeoutMs,\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),\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): 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 }\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 }\n}\n",
32
+ "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 } 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}\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, { run, execution, signal: request.signal })\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",
33
+ "import type { ResolvedRuntimeAuthorization } from \"../execution/authorization\"\nimport type { Storage } from \"../storage\"\nimport type { ActionRunRecord } from \"../storage/action-runs\"\nimport { findPrimitiveParentRequestExecution } from \"../storage/executions/run-link\"\n\n/** Check both current grant scope and immutable request provenance for a delegated Action run. */\nexport async function canDelegationAccessActionRun(input: {\n readonly storage: Storage\n readonly projectId: string\n readonly authority: Extract<ResolvedRuntimeAuthorization, { readonly type: \"delegated\" }>\n readonly run: ActionRunRecord\n}): Promise<boolean> {\n const subject = input.run.subject\n if (\n !input.authority.delegation ||\n subject.kind !== \"object\" ||\n !input.authority.actionApply.some(\n (target) =>\n target.actionId === input.run.actionId &&\n target.subject.objectTypeId === subject.objectTypeId &&\n target.subject.primaryId === subject.primaryId\n )\n ) {\n return false\n }\n return actionRunBelongsToShareGrant({\n storage: input.storage,\n projectId: input.projectId,\n run: input.run,\n grantId: input.authority.delegation.grantId,\n })\n}\n\n/** Session ids remain audit provenance; the issued grant is the durable capability identity. */\nexport async function actionRunBelongsToShareGrant(input: {\n readonly storage: Storage\n readonly projectId: string\n readonly run: Pick<ActionRunRecord, \"id\" | \"actionId\" | \"executionId\">\n readonly grantId: string\n}): Promise<boolean> {\n const parent = await findPrimitiveParentRequestExecution({\n executions: input.storage.executions,\n projectId: input.projectId,\n executionId: input.run.executionId,\n primitive: { kind: \"action\", id: input.run.actionId, runId: input.run.id },\n })\n const authorization = parent?.authorizationRef\n return (\n authorization?.type === \"delegated\" &&\n authorization.delegation.kind === \"share\" &&\n authorization.delegation.grantId === input.grantId\n )\n}\n",
34
+ "import { AuthorizationError, assertAuthorized, canViewActionRun } 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 { OntologyValidationError } from \"../ontology/errors\"\nimport type { ObjectTypeWithPropertyTokens } from \"../ontology/tokens\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport { assertParamUsersActive } from \"../shared/params/user-refs\"\nimport type { ActionRunRecord } from \"../storage\"\nimport {\n assertObjectReadOutputWithinLimit,\n ObjectReadLimitExceededError,\n} from \"../storage/objects/execution-limits\"\nimport { admitDelegatedObjectAction, assertDelegatedActionTarget } from \"./delegated-admission\"\nimport { getActionRunExecutor } from \"./run/executor\"\nimport { actionRunBelongsToShareGrant } 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 // 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 actionId = action.id\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({ projectId, runtimeAuthorization }, { kind: \"action.apply\", actionId })\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 assertAuthorized(\n { projectId, runtimeAuthorization },\n { kind: \"object.view\", objectTypeId: action.binding.objectType.id }\n )\n }\n\n validateActionSubject(action, subject)\n\n let pathPrefix = action.id\n let objectType: ObjectTypeWithPropertyTokens | null = null\n\n if (isObjectActionDefinition(action)) {\n objectType = resolveObjectActionSubject({ runtime, action, subject })\n pathPrefix = `${objectType.id}.${action.id}`\n if (authorization.type !== \"delegated\") {\n // A run is visible to whoever may view its subject's type (`canViewActionRun`). A subtype\n // excluded from a broad grant is not visible through its parent, so admitting the request on\n // the bound type alone would run what its caller can never read back.\n assertAuthorized(\n { projectId, runtimeAuthorization },\n { kind: \"object.view\", objectTypeId: objectType.id }\n )\n }\n }\n\n const actionParams = normalizeActionParams(runtime, action.params, rawParams, pathPrefix)\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({ storage: runtime.storage, projectId, authorization, run })\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 const run = await executor.request({\n runId,\n payload,\n persist,\n assertCanReuse,\n signal: request.signal,\n onRequested: request.onRequested,\n })\n return enforceDelegatedOutputBudget(authorization, run)\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 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\" || canViewActionRun(authorization.context, 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",
35
+ "import { canViewActionRun, 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 { canDelegationAccessActionRun } 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 return (\n isAllowed(authorization.context, { kind: \"action.apply\", actionId: action.id }) &&\n (action.binding.kind === \"global\" ||\n isAllowed(authorization.context, {\n kind: \"object.view\",\n objectTypeId: action.binding.objectType.id,\n }))\n )\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\" && canViewActionRun(authorization.context, run)) ||\n (authorization.type === \"delegated\" &&\n (await canDelegationAccessActionRun({\n storage: runtime.storage,\n projectId,\n authority: authorization,\n run,\n }))))\n ? release(run)\n : null\n },\n list: (input = {}) => {\n if (authorization.type === \"denied\" || authorization.type === \"delegated\") {\n return Promise.resolve({ runs: [], hasMore: false, total: 0 })\n }\n const storage = runtime.storage.actionRuns\n if (!storage) return Promise.resolve({ runs: [], hasMore: false, total: 0 })\n return storage.list({\n ...input,\n projectId,\n actionIds:\n authorization.type === \"principal\"\n ? [...authorization.context.grants[\"apply:action\"]]\n : undefined,\n objectTypeIds:\n authorization.type === \"principal\"\n ? [...authorization.context.grants[\"view:object\"]]\n : undefined,\n })\n },\n },\n }\n}\n",
36
+ "import type { AiCostStorage, AiCostSummary } from \"../storage/ai-cost\"\n\n/** Resolve preferred cost summaries in input order without inventing unavailable accounting. */\nexport async function resolveExecutionCosts(input: {\n readonly storage: AiCostStorage | undefined\n readonly projectId: string\n readonly executionIds: readonly string[]\n}): Promise<readonly (AiCostSummary | undefined)[]> {\n if (input.executionIds.length === 0) return []\n if (!input.storage) return input.executionIds.map(() => undefined)\n return input.storage.summarizeExecutions({\n projectId: input.projectId,\n executionIds: input.executionIds,\n })\n}\n",
37
+ "import type { AiModelCallUsage, AiUsageStorage } from \"../storage/ai-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",
38
+ "import { createHash, randomUUID } from \"node:crypto\"\n\n/**\n * Id helpers for agent persistence. Threads, the run id, and the user (trigger) message are minted\n * by the trigger; the queued run is persisted with the user message, and the assistant message id\n * is minted when the turn finalizes. Prefixes make ids self-describing in logs.\n */\n\nexport function createAgentThreadId(): string {\n return `agt_thr_${randomUUID()}`\n}\n\n/** A fresh provider name, scoped to one project's thread; never a filesystem revision. */\nexport function createAgentThreadSandboxName(projectId: string, threadId: string): string {\n const digest = createHash(\"sha256\")\n .update(JSON.stringify([projectId, threadId, randomUUID()]))\n .digest(\"hex\")\n return `sixb-sb-${digest}`\n}\n\nexport function createAgentRunId(): string {\n return `agt_run_${randomUUID()}`\n}\n\n/** One stable child identity per parent-selected spawn key. */\nexport function createSubagentRunId(parentRunId: string, spawnKey: string): string {\n const digest = createHash(\"sha256\")\n .update(parentRunId)\n .update(\"\\0\")\n .update(spawnKey)\n .digest(\"hex\")\n return `agt_run_child_${digest}`\n}\n\n/** Stable execution identity paired with a deterministic child run. */\nexport function createSubagentExecutionId(runId: string): string {\n return `exec_${runId}`\n}\n\nexport function createAgentMessageId(): string {\n return `agt_msg_${randomUUID()}`\n}\n\n/** One deterministic context-checkpoint identity per conversational run. */\nexport function agentContextCheckpointId(runId: string): string {\n return `agt_ctx_${runId}`\n}\n\n/** A queue delivery's fencing token for writes to an `agent_runs` record. */\nexport function createAgentRunExecutionToken(): string {\n return `agt_exec_${randomUUID()}`\n}\n",
39
+ "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 { LanguageModelCatalog, LanguageModelEntry, LanguageModelRef } 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 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 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 { assertNoAgentSelector } from \"./retired-config\"\nimport { publishAgentRunActivity } from \"./streams/protocol\"\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 /** 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\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: LanguageModelCatalog | undefined,\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, input) : {}\n const spec = await resolveConversationRunSpec({\n models,\n input: {\n ...input,\n model: input.model ?? continued.model,\n reasoning: input.reasoning ?? continued.reasoning,\n },\n })\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 { thread, createdThread } = await resolveThread(agents, {\n projectId,\n threadId: input.threadId,\n title: input.title,\n principal,\n })\n\n assertSandboxExecutionAvailable(thread)\n // Fast single-flight check for a clear error. `runs.create` below 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 const triggerMessageId = input.messageId ?? createAgentMessageId()\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 await tx.executions.create(durableExecution)\n await agents.messages.append({\n id: triggerMessageId,\n projectId,\n threadId: thread.id,\n runId: null,\n role: \"user\",\n 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 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 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({\n models,\n input: {},\n })),\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/**\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 { runs } = await agents.runs.list({\n projectId: runtime.projectId,\n threadId,\n kinds: [\"conversation\"],\n order: \"desc\",\n limit: 1,\n })\n const spec = runs[0]?.kind === \"conversation\" ? runs[0].spec : undefined\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/** 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 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 input: Pick<RequestAgentRunInput, \"model\" | \"reasoning\" | \"timeZone\" | \"locale\">\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.input.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.input.reasoning\n if (explicitReasoning !== undefined) {\n await assertModelSupportsReasoning(model, explicitReasoning)\n }\n const reasoning = explicitReasoning ?? model.model.defaultReasoning\n const timeZone = requestedSetting(\n \"timeZone\",\n input.input.timeZone,\n canonicalTimeZone,\n \"an IANA time zone\"\n )\n const locale = requestedSetting(\n \"locale\",\n input.input.locale,\n canonicalLocale,\n \"a BCP 47 language tag\"\n )\n\n return Object.freeze({\n model: Object.freeze({ provider: selected.provider, modelId: selected.modelId }),\n ...(reasoning === undefined ? {} : { reasoning }),\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\nasync function resolveThread(\n agents: AgentStorage,\n params: {\n readonly projectId: string\n readonly threadId?: string\n readonly title?: string\n readonly principal: Principal\n }\n): Promise<{ thread: AgentThreadRecord; createdThread: boolean }> {\n if (params.threadId) {\n const existing = await agents.threads.getById({\n projectId: params.projectId,\n id: params.threadId,\n })\n if (existing) {\n return { thread: existing, createdThread: false }\n }\n }\n\n const thread = await 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 return { thread, createdThread: true }\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",
40
+ "/** 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",
41
+ "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",
42
+ "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",
43
+ "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",
44
+ "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",
45
+ "import { principalsEqual, SYSTEM_PRINCIPAL } from \"../auth\"\nimport { assertAuthorized, isRuntimeAllowed } from \"../authorization\"\nimport type { AuthorizablePrincipal, ExecutionContext } from \"../execution\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport type { ModelCatalog } from \"../models\"\nimport { resolveExecutionCosts } from \"../runtime/ai-cost\"\nimport { resolveExecutionUsage } from \"../runtime/ai-usage\"\nimport type { SixbDependencies } from \"../runtime/sixb\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport type {\n AgentThreadRecord,\n ConversationAgentRunRecord,\n ListAgentRunsInput,\n ListAgentRunsResult,\n ListAgentThreadsInput,\n ListAgentThreadsResult,\n} from \"../storage/agents\"\nimport type { AiCostSummary } from \"../storage/ai-cost\"\nimport type { AiModelCallUsage } from \"../storage/ai-usage\"\nimport { AgentRequestError } from \"./errors\"\nimport { createAgentThreadId, createAgentThreadSandboxName } from \"./ids\"\nimport {\n type RequestAgentRunInput,\n type RequestAgentRunResult,\n requestAgentRun,\n retryAgentRun,\n} from \"./request\"\nimport { assertNoAgentSelector } from \"./retired-config\"\nimport { normalizeSandboxBinding } from \"./sandbox\"\nimport type { AgentDescriptor } from \"./types\"\n\nexport type ExecutionAgentRequestInput = Omit<RequestAgentRunInput, \"principal\">\n\n/** Execution ownership tokens never leave the storage/worker boundary. */\nfunction publicThread(thread: AgentThreadRecord): AgentThreadRecord {\n if (!thread.sandboxState) return thread\n const { name, status, initialized } = thread.sandboxState\n return { ...thread, sandboxState: { name, status, initialized } }\n}\nexport type ListExecutionAgentThreadsInput = Omit<\n ListAgentThreadsInput,\n \"projectId\" | \"ownerPrincipal\"\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. */\n recreateSandbox(\n threadId: string,\n input: { readonly expectedSandboxName: string }\n ): Promise<AgentThreadRecord>\n create(input: CreateExecutionAgentThreadInput<TParams>): Promise<AgentThreadRecord>\n getById(threadId: string): Promise<AgentThreadRecord | null>\n list(input?: ListExecutionAgentThreadsInput): Promise<ListAgentThreadsResult>\n }\n\nexport interface AgentRunsRuntime {\n request(input: ExecutionAgentRequestInput): Promise<ExecutionAgentRunResult>\n retry(runId: string): Promise<ExecutionAgentRunResult>\n getById(runId: string): Promise<AgentRunView | null>\n listForThread(\n threadId: string,\n input?: Omit<ListAgentRunsInput, \"projectId\" | \"threadId\">\n ): Promise<AgentRunListResult | null>\n}\n\n/** Execution-facing run view with provenance resolved from the immutable execution ledger. */\nexport interface AgentRunView extends ConversationAgentRunRecord {\n readonly requestedBy?: AuthorizablePrincipal\n /** Derived from the model-call ledger; never persisted on the Agent run row. */\n readonly usage?: AiModelCallUsage\n /** Preferred valuation; omitted when there are no calls or cost storage is unavailable. */\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: AgentRunView\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}\n\nexport function createAgentRuntime<\n TParams extends Record<string, unknown> = Record<string, unknown>,\n>(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n models?: ModelCatalog,\n sandbox?: SixbDependencies[\"sandbox\"]\n): AgentRuntime<TParams> {\n const authority = resolveRuntimeAuthorizationForProject(runtime)\n const principal = authority.type === \"principal\" ? authority.context.principal : SYSTEM_PRINCIPAL\n const allowed = () => isRuntimeAllowed(runtime, { kind: \"agent.run\" })\n\n const getVisibleThreadRecord = async (threadId: string): Promise<AgentThreadRecord | null> => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return null\n const thread =\n (await runtime.storage.agents?.threads.getById({\n projectId: runtime.projectId,\n id: threadId,\n })) ?? null\n if (!thread || !allowed()) return null\n return authority.type === \"principal\" && !principalsEqual(principal, thread.ownerPrincipal)\n ? null\n : publicThread(thread)\n }\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 const getVisibleRunRecord = async (runId: string): Promise<ConversationAgentRunRecord | 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 || run.kind !== \"conversation\") 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 return {\n get: getAgent,\n threads: {\n recreateSandbox: async (threadId, input) => {\n const thread = await getVisibleThreadRecord(threadId)\n if (!thread)\n throw new AgentRequestError(\"thread_not_found\", \"[Sixb] Agent thread not found.\")\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 return publicThread({ ...thread, sandboxState })\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 return 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 },\n getById: getVisibleThreadRecord,\n list: async (input = {}) => {\n assertNoAgentSelector(input)\n if (authority.type === \"denied\" || authority.type === \"delegated\") {\n return { threads: [], hasMore: false, total: 0 }\n }\n const storage = runtime.storage.agents\n if (!storage || !allowed()) return { threads: [], hasMore: false, total: 0 }\n const result = await storage.threads.list({\n ...input,\n projectId: runtime.projectId,\n ownerPrincipal: authority.type === \"principal\" ? principal : undefined,\n })\n return { ...result, threads: result.threads.map(publicThread) }\n },\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, models?.language, {\n ...input,\n principal,\n })\n return { ...result, run: await attachRunView(runtime, result.run) }\n },\n retry: async (runId) => {\n const failedRun = await getVisibleRunRecord(runId)\n if (!failedRun) {\n throw new AgentRequestError(\"run_not_found\", `[Sixb] Agent run '${runId}' was not found.`)\n }\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 getById: getRun,\n listForThread: async (threadId, input = {}) => {\n assertNoAgentSelector(input)\n const storage = runtime.storage.agents\n if (!storage || !(await getVisibleThreadRecord(threadId))) return null\n const result = await storage.runs.list({\n ...input,\n projectId: runtime.projectId,\n threadId,\n })\n return {\n ...result,\n runs: await attachRunViews(\n runtime,\n result.runs.filter((run) => run.kind === \"conversation\")\n ),\n }\n },\n },\n }\n}\n\nasync function attachRunView(\n runtime: SixbRuntimeContext,\n run: ConversationAgentRunRecord\n): Promise<AgentRunView> {\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(\n runtime: SixbRuntimeContext,\n runs: readonly ConversationAgentRunRecord[]\n): Promise<readonly AgentRunView[]> {\n const executionIds = runs.map((run) => run.executionId)\n const [executions, usages, costs] = 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 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\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 = usages[index]\n const cost = usage === undefined ? undefined : costs[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",
46
+ "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",
47
+ "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",
48
+ "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",
49
+ "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 { 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 dataset 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): 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(registered, assertRuntimeAuthorizationBound(runtime))\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 the reader cannot read. Trusted code reads every column, a principal reads what its roles\n * clear, and any other authority is cleared for nothing.\n */\nfunction redactedColumns(\n dataset: DatasetDefinition,\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 return new Set(\n dataset.schema.columns\n .filter((column) => column.markings?.some((markingId) => !clearances.has(markingId)))\n .map((column) => column.name)\n )\n}\n\nasync function* emptyRows(rows: AsyncIterable<DatasetRow>): AsyncIterable<DatasetRow> {\n for await (const _row of rows) yield {}\n}\n",
50
+ "import { assertPrivileged, canViewEvent } from \"../authorization\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\nimport { redactDomainEvent, resolvePropertyClearance } 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\"\n\nexport interface EventsRuntime {\n /** The event as this execution may read it: hidden events are `undefined`, others redacted. */\n readable(event: StoredDomainEvent): StoredDomainEvent | undefined\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 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 const clearance =\n authority.type === \"principal\"\n ? resolvePropertyClearance(runtime.ontology, authority.context.clearances ?? new Set())\n : undefined\n const readable = (event: StoredDomainEvent): StoredDomainEvent | undefined => {\n switch (authority.type) {\n case \"denied\":\n case \"delegated\":\n return undefined\n case \"principal\":\n if (!canViewEvent(authority.context, event)) return undefined\n return clearance ? redactDomainEvent(event, clearance) : event\n case \"unrestricted\":\n return event\n }\n }\n const visibleEvents = (events: readonly StoredDomainEvent[]): readonly StoredDomainEvent[] =>\n events.flatMap((event) => readable(event) ?? [])\n\n return {\n readable,\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 const events = await runtime.events.read(input)\n return visibleEvents(events)\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, (events) => {\n const visible = visibleEvents(events)\n if (visible.length > 0) return handler(visible)\n })\n },\n }\n}\n",
51
+ "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",
52
+ "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 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\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>\n): Promise<ModelLoopResult<TOutput>>\nexport async function runModelLoop(\n input: RunModelLoopInput<unknown>\n): Promise<ModelLoopResult<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 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 response = accumulator.complete()\n const responseId = response.responseId ?? `${callId}:response`\n if (terminalStreamError) throw terminalStreamError.error\n if (response.projectionError) throw response.projectionError\n if (input.signal.aborted) {\n return { status: \"aborted\", steps, partialContent: response.content }\n }\n\n const localCalls = response.toolCalls.filter((call) => call.part.providerExecuted !== true)\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 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 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\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 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 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 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",
53
+ "import { randomUUID } from \"node:crypto\"\nimport { assertProviderAccess } 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 { assertTranscriptionModel } from \"./catalog\"\nimport { TranscriptionModelResponseError } from \"./errors\"\nimport { prepareTranscriptionFile, readTranscriptionFile } from \"./file\"\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 async transcribe(input) {\n assertProviderAccess(runtime, execution, \"models.audio.transcribe\")\n\n const { audio, mediaType } = prepareTranscriptionFile(input.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 readTranscriptionFile(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 if (!catalog && requested) return requested\n\n const transcribers = catalog?.audio?.transcription\n const selected = requested\n ? transcribers?.getByRef({ provider: requested.providerId, modelId: requested.modelId })?.model\n : transcribers?.default.model\n\n if (!selected) {\n throw new Error(\n \"[SixbModels] Configure the selected model in models.audio.transcription, or supply a model when no catalog is configured.\"\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",
54
+ "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 prepareTranscriptionFile(input: FileRef): { audio: FileRef; mediaType: string } {\n if (!isFileRef(input) || !Number.isSafeInteger(input.sizeBytes) || input.sizeBytes <= 0) {\n throw new TypeError(\"[SixbModels] Transcription requires a nonempty FileRef.\")\n }\n\n const audio = { ...input }\n const mediaType = audio.mediaType?.split(\";\", 1)[0]?.trim().toLowerCase()\n if (!mediaType || !/^audio\\/[a-z0-9.+-]+$/.test(mediaType)) {\n throw new TypeError(\"[SixbModels] Audio FileRef must declare an audio mediaType.\")\n }\n\n return { audio, mediaType }\n}\n\n/** Read an already validated reference, bounded by its verified size and the model's limit. */\nexport async function readTranscriptionFile(\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] Audio 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] Audio 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] Audio 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",
55
+ "import { randomUUID } from \"node:crypto\"\nimport { assertProviderAccess } 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\nexport function createDecisionRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n catalog: ModelCatalog | undefined,\n session: ModelExecutionSession\n): DecisionModelsRuntime {\n return {\n async evaluate(input) {\n assertProviderAccess(runtime, execution, \"models.decision.evaluate\")\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 if (!requested) {\n const model = catalog?.decision?.default.model\n if (!model) {\n throw new Error(\"[SixbModels] Configure models.decision or supply a model to evaluate().\")\n }\n return model\n }\n\n if (!catalog) return requested\n\n // The catalog owns the binding, even when a caller supplies another object with the same ID.\n const entry = catalog.decision?.getByRef({\n provider: requested.providerId,\n modelId: requested.modelId,\n })\n if (!entry) {\n throw new Error(\n `[SixbModels] Model '${requested.providerId}/${requested.modelId}' is not configured in models.decision.`\n )\n }\n return entry.model\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 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",
56
+ "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",
57
+ "import { runModelLoop } from \"../agents/model-loop\"\nimport { assertProviderAccess } 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 type { ModelCatalog } 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 { ModelExecutionSession } from \"./execution/session\"\nimport type {\n InferLanguageModelOutput,\n LanguageModelGenerateInput,\n LanguageModelGenerateResult,\n LanguageModelOutputShape,\n ModelsRuntime,\n} from \"./generation-types\"\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 blobs?: BlobStorage\n): ModelsRuntime {\n const session = runtime.modelExecution ?? new ModelExecutionSession(runtime, execution)\n\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 assertProviderAccess(runtime, execution, \"models.language.generate\")\n const messages = generationMessages(input)\n const signal = session.signal(input.signal)\n signal.throwIfAborted()\n // The catalog's binding is the configured one, default reasoning included.\n const selected = input.model\n ? catalog\n ? catalog.language?.getByRef({\n provider: input.model.providerId,\n modelId: input.model.modelId,\n })?.model\n : input.model\n : catalog?.language?.default.model\n if (!selected) {\n throw new Error(\n input.model\n ? `[SixbModels] Model '${input.model.providerId}/${input.model.modelId}' is not configured in models.language.`\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 // The default was checked against the capabilities known at startup; like any request, a level\n // 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 const maxOutputTokens = Math.min(\n aiModelCallOutputTokenAllowance(input.maxOutputTokens ?? model.definition.maxOutputTokens),\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),\n audio: createAudioRuntime(runtime, execution, catalog, session, blobs),\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",
58
+ "/**\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",
59
+ "/**\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 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\"\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.\n */\nexport async function commitRuntimeOperations(\n ctx: RuntimeMaterializerContext,\n operations: readonly OntologyEditOperation[]\n): Promise<EditCommitResult> {\n const mutations = getOntologyMutationRuntime(ctx)\n const commit = await mutations.commitEdits({\n mode: \"atomic\",\n source: { kind: \"runtime\", requestId: randomUUID() },\n operations,\n expectedObjects: [],\n expectedLinks: [],\n expectedLinkScopes: [],\n })\n return commit\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): 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 const mutations = getOntologyMutationRuntime(ctx)\n const commit = await mutations.commitEdits({\n mode: \"continue\",\n source: { kind: \"runtime\", requestId: randomUUID() },\n operations,\n ...(operationGroups.length > 0 ? { operationGroups } : {}),\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\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/** 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 }\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",
60
+ "/**\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",
61
+ "/**\n * The authorization rule for writing a link, in one place because all three link leaves need it.\n */\nimport { assertAuthorized, assertCanEdit } from \"../../authorization\"\nimport type { SixbRuntimeContext } from \"../../runtime/types\"\n\n/**\n * Assert a principal may create or remove a link.\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 */\nexport function assertCanWriteLink(\n ctx: Pick<SixbRuntimeContext, \"projectId\" | \"runtimeAuthorization\" | \"authorization\">,\n endpoints: { readonly sourceTypeId: string; readonly targetTypeId: string }\n): void {\n assertCanEdit(ctx, endpoints.sourceTypeId)\n assertAuthorized(ctx, { kind: \"object.view\", objectTypeId: endpoints.targetTypeId })\n}\n",
62
+ "/**\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 linkDeleteOperation,\n runtimeOperationId,\n} from \"../materializer-adapter\"\nimport { assertCanWriteLink } from \"./authorization\"\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 assertCanWriteLink(ctx, { sourceTypeId: objectType.id, targetTypeId })\n\n assertLinkTargetType(objectType.id, linkId, linkDefinition, targetTypeId, (expected, actual) =>\n ontology.isValidLinkTarget(expected, actual)\n )\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(ctx, [\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}\n",
63
+ "/**\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\nimport type { SixbRuntimeContext } from \"../../runtime/types\"\nimport { 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 type EndpointExistence = ReadonlySet<string>\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: Pick<SixbRuntimeContext, \"projectId\" | \"storage\">,\n lookups: readonly { objectTypeId: string; primaryId: string }[]\n): Promise<EndpointExistence> {\n if (lookups.length === 0) return new Set()\n const rows = await ctx.storage.objects.getByPrimaryIdBatch({\n projectId: ctx.projectId,\n items: lookups,\n })\n return new Set(rows.keys())\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.has(endpointKey(item.objectType.id, item.sourceId))) {\n throw new ObjectNotFoundError(item.objectType.id, item.sourceId, \"Source object not found\")\n }\n if (!existing.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",
64
+ "/**\n * Leaf operation: upsert a single link through the ontology Materializer.\n */\nimport type { ResolvedLinkContext } from \"../context\"\nimport {\n commitRuntimeOperations,\n linkUpsertOperation,\n normalizeRuntimeLink,\n runtimeOperationId,\n} from \"../materializer-adapter\"\nimport { assertCanWriteLink } 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 assertCanWriteLink(ctx, { sourceTypeId: objectType.id, 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 requireEndpoints(endpoints, await loadEndpointExistence(ctx, collectEndpointLookups([endpoints])))\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(ctx, [\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}\n",
65
+ "/**\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 { OntologyEditOperation, OntologyOperationOutcome } 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}\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)\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",
66
+ "/**\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 linkUpsertOperation,\n normalizeRuntimeLink,\n runtimeOperationId,\n} from \"../materializer-adapter\"\nimport { runRuntimeItemBatch } from \"../runtime-batch\"\nimport { assertCanWriteLink } 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 for (const item of items) {\n assertCanWriteLink(ctx, {\n sourceTypeId: item.objectType.id,\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 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",
67
+ "/**\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 { ResolvedObjectContext } from \"../context\"\nimport {\n commitRuntimeOperations,\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 assertCanEdit(ctx, ctx.objectType.id)\n await commitRuntimeOperations(ctx, [\n objectDeleteOperation({\n id: runtimeOperationId(0),\n ref: { objectTypeId: ctx.objectType.id, primaryId },\n }),\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 */\nexport async function restoreObject(ctx: ResolvedObjectContext, primaryId: string): Promise<void> {\n assertCanEdit(ctx, ctx.objectType.id)\n await commitRuntimeOperations(ctx, [\n objectRestoreOperation({\n id: runtimeOperationId(0),\n ref: { objectTypeId: ctx.objectType.id, primaryId },\n }),\n ])\n}\n",
68
+ "/**\n * Leaf operation: upsert a single object through the ontology Materializer.\n */\n\nimport { assertCanEdit } from \"../../authorization\"\nimport type { ObjectRow } from \"../../storage\"\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 assertCanEdit(ctx, ctx.objectType.id)\n const { objectType, primaryPropertyId, ontology } = ctx\n\n const normalized = normalizeRuntimeObject({\n objectType,\n primaryPropertyId,\n properties,\n valueTypesById: ontology.getValueTypesById(),\n })\n const ref = { objectTypeId: objectType.id, primaryId: normalized.primaryId }\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, [\n objectUpsertOperation({ id: runtimeOperationId(0), ref, properties: normalized.properties }),\n ])\n return ctx.objectReader.redactWrittenRow(\n toObjectRow(ctx.projectId, requireEffectiveObject(commit.outcomes[0]))\n )\n}\n",
69
+ "/**\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 { assertCanEdit } from \"../../authorization\"\nimport { stableJsonStringify } from \"../../json\"\nimport type { BatchItemResult } from \"../../runtime/types\"\nimport type { ObjectRow } from \"../../storage\"\nimport type { ResolvedObjectContext } from \"../context\"\nimport {\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 assertCanEdit(ctx, ctx.objectType.id)\n const { objectType, primaryPropertyId, ontology } = ctx\n const valueTypesById = ontology.getValueTypesById()\n\n return runRuntimeItemBatch({\n ctx,\n items,\n plan(item, index) {\n const normalized = normalizeRuntimeObject({\n objectType,\n primaryPropertyId,\n properties: item.properties,\n valueTypesById,\n })\n const ref = { objectTypeId: objectType.id, primaryId: normalized.primaryId }\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(normalized.properties),\n operations: [\n objectUpsertOperation({\n id: runtimeOperationId(index),\n ref,\n properties: normalized.properties,\n }),\n ],\n }\n },\n value: ([outcome]) =>\n ctx.objectReader.redactWrittenRow(\n toObjectRow(ctx.projectId, requireEffectiveObject(outcome))\n ),\n })\n}\n",
70
+ "import { randomUUID } from \"node:crypto\"\nimport { assertCanEdit } from \"../../authorization\"\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 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 assertCanEdit(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 assertCanEdit(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",
71
+ "/**\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",
72
+ "/**\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",
73
+ "/**\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",
74
+ "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",
75
+ "/**\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",
76
+ "/**\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",
77
+ "/**\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",
78
+ "/**\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",
79
+ "/**\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 } from \"../../ontology/tokens\"\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 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",
80
+ "/**\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",
81
+ "/**\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",
82
+ "/**\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",
83
+ "/**\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",
84
+ "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 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 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",
85
+ "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",
86
+ "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",
87
+ "import { isRuntimeAllowed } from \"../authorization\"\nimport { resolveRuntimeAuthorizationForProject } from \"../execution/authorization\"\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 const visible = (rule: RuleDefinition) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") return false\n return isRuntimeAllowed(runtime, {\n kind: \"object.view\",\n objectTypeId: rule.subject.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: (input = {}) => {\n if (authority.type === \"denied\" || authority.type === \"delegated\") {\n return Promise.resolve({ states: [], hasMore: false, total: 0 })\n }\n const storage = runtime.storage.rules\n if (!storage) return Promise.resolve({ states: [], hasMore: false, total: 0 })\n return storage.listActive({\n ...input,\n objectTypeIds:\n authority.type === \"principal\"\n ? [...authority.context.grants[\"view:object\"]]\n : undefined,\n projectId: runtime.projectId,\n })\n },\n },\n }\n}\n",
88
+ "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",
89
+ "import { createHash, randomBytes, randomUUID } from \"node:crypto\"\nimport { 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 { 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\n // This canonical read checks both the caller's current object authority and target existence.\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 = {\n version: 1 as const,\n access: compileShareAccessPlan({\n share: definition,\n target,\n ontology: runtime.ontology,\n actions: runtime.actionRegistry,\n }),\n }\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\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",
90
+ "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",
91
+ "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",
92
+ "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",
93
+ "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",
94
+ "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",
95
+ "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",
96
+ "import { isActionDefinition } from \"../actions\"\nimport type { AgentSkillCatalog, AgentToolCatalog } from \"../agents\"\nimport type { ModelCatalog } from \"../models\"\nimport { isModelReasoning, modelReasoningSupportIssue } from \"../models/language-model\"\nimport type { SchemaOrRef, ValueType } from \"../ontology\"\nimport { validateSchemaOrRefValue } from \"../ontology/refs\"\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 || 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 (step.model !== undefined && options.models !== undefined) {\n const ref = { provider: step.model.providerId, modelId: step.model.modelId }\n if (options.models.language?.getByRef(ref) == null) {\n throw new WorkflowDefinitionError(\n `Workflow \"${workflowId}\" agent step \"${step.id}\" uses unknown language model \"${ref.provider}/${ref.modelId}\". Add it to 'models.language' in createSixb().`\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 = step.model ?? options.models?.language?.default?.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 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\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",
97
+ "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",
98
+ "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 type { WorkflowDefinition, 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 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(options.input, `Workflow \"${workflow.id}\" 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",
99
+ "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",
100
+ "import { type ActionsRuntime, createActionsRuntime } from \"../actions/execution\"\nimport { type AgentRuntime, createAgentRuntime } from \"../agents/execution\"\nimport { type AiUsageRuntime, createAiUsageRuntime } from \"../ai-usage\"\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 type { LakeStorage } from \"../lake-storage/types\"\nimport { createLogsRuntime, type LogsRuntime } from \"../logging/execution\"\nimport type { LoggingService } from \"../logging/service\"\nimport { createModelsRuntime } from \"../models/execution\"\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 { createSharesRuntime, type SharesRuntime } from \"../shares/execution\"\nimport { createSyncsRuntime, type SyncsRuntime } from \"../syncs/execution\"\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 models: ModelsRuntime\n readonly aiUsage: AiUsageRuntime\n readonly events: EventsRuntime\n readonly logs: LogsRuntime\n readonly schedules: SchedulesRuntime\n readonly shares: SharesRuntime\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 connectorService: ConnectorService\n readonly connectorConnections?: ConnectorConnectionProcess\n readonly blobStorage: BlobStorage\n readonly apiPublicOrigin: () => string | undefined\n readonly lakeStorage: LakeStorage\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 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 return {\n objects: createObjectsRuntime(runtime, execution, dependencies.blobStorage),\n actions: createActionsRuntime(runtime, execution),\n datasets: createDatasetsRuntime(\n runtime,\n execution,\n dependencies.definitions.datasets,\n dependencies.lakeStorage,\n dependencies.blobStorage\n ),\n workflows: createWorkflowsRuntime(runtime, execution, dependencies.definitions.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: createAgentRuntime<TParams>(\n runtime,\n execution,\n dependencies.definitions.models,\n dependencies.sandbox\n ),\n models: createModelsRuntime(\n runtime,\n execution,\n dependencies.definitions.models,\n dependencies.blobStorage\n ),\n aiUsage: createAiUsageRuntime(runtime, dependencies.definitions.security),\n events: createEventsRuntime(runtime),\n logs: createLogsRuntime(runtime, dependencies.logging),\n schedules: createSchedulesRuntime(runtime, dependencies.definitions.schedules),\n shares: createSharesRuntime(runtime, execution, dependencies.definitions.shares),\n connector: createConnectorRuntime(runtime, execution, dependencies.connectorService),\n blobs: createBlobsRuntime(\n runtime,\n execution,\n dependencies.blobStorage,\n dependencies.apiPublicOrigin\n ),\n }\n}\n",
101
+ "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 * 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"
102
+ ],
103
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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