@sixb/core 0.1.6 → 0.1.8

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 (909) hide show
  1. package/dist/actions/delegated-admission.d.ts +24 -0
  2. package/dist/actions/delegated-admission.d.ts.map +1 -0
  3. package/dist/actions/descriptor.d.ts +29 -0
  4. package/dist/actions/descriptor.d.ts.map +1 -0
  5. package/dist/actions/execution.d.ts +5 -5
  6. package/dist/actions/execution.d.ts.map +1 -1
  7. package/dist/actions/index.js +50 -40
  8. package/dist/actions/index.js.map +1 -1
  9. package/dist/actions/request.d.ts.map +1 -1
  10. package/dist/actions/run-authorization.d.ts +20 -0
  11. package/dist/actions/run-authorization.d.ts.map +1 -0
  12. package/dist/actions/run-dispatch.d.ts +3 -1
  13. package/dist/actions/run-dispatch.d.ts.map +1 -1
  14. package/dist/actions/worker.js +5 -5
  15. package/dist/actions/worker.js.map +1 -1
  16. package/dist/agents/adapters.d.ts +6 -166
  17. package/dist/agents/adapters.d.ts.map +1 -1
  18. package/dist/agents/authority.d.ts +22 -6
  19. package/dist/agents/authority.d.ts.map +1 -1
  20. package/dist/agents/builders.d.ts +3 -11
  21. package/dist/agents/builders.d.ts.map +1 -1
  22. package/dist/agents/context-resolution.d.ts.map +1 -1
  23. package/dist/agents/context.js +2 -2
  24. package/dist/agents/dispatch.d.ts +9 -1
  25. package/dist/agents/dispatch.d.ts.map +1 -1
  26. package/dist/agents/errors.d.ts +1 -10
  27. package/dist/agents/errors.d.ts.map +1 -1
  28. package/dist/agents/execution.d.ts +9 -10
  29. package/dist/agents/execution.d.ts.map +1 -1
  30. package/dist/agents/identity.d.ts +3 -0
  31. package/dist/agents/identity.d.ts.map +1 -0
  32. package/dist/agents/ids.d.ts +4 -0
  33. package/dist/agents/ids.d.ts.map +1 -1
  34. package/dist/agents/index.d.ts +15 -11
  35. package/dist/agents/index.d.ts.map +1 -1
  36. package/dist/agents/index.js +90 -78
  37. package/dist/agents/index.js.map +1 -1
  38. package/dist/agents/message.d.ts +19 -13
  39. package/dist/agents/message.d.ts.map +1 -1
  40. package/dist/agents/model-loop.d.ts +58 -0
  41. package/dist/agents/model-loop.d.ts.map +1 -0
  42. package/dist/agents/reference.d.ts +4 -0
  43. package/dist/agents/reference.d.ts.map +1 -0
  44. package/dist/agents/request.d.ts +10 -8
  45. package/dist/agents/request.d.ts.map +1 -1
  46. package/dist/agents/retired-config.d.ts +4 -0
  47. package/dist/agents/retired-config.d.ts.map +1 -0
  48. package/dist/agents/streams.d.ts +13 -8
  49. package/dist/agents/streams.d.ts.map +1 -1
  50. package/dist/agents/streams.js +7 -5
  51. package/dist/agents/streams.js.map +1 -1
  52. package/dist/agents/tool-catalog.d.ts +9 -0
  53. package/dist/agents/tool-catalog.d.ts.map +1 -0
  54. package/dist/agents/tool-definition.d.ts +1 -1
  55. package/dist/agents/tool-definition.d.ts.map +1 -1
  56. package/dist/agents/types.d.ts +31 -68
  57. package/dist/agents/types.d.ts.map +1 -1
  58. package/dist/agents/validation.d.ts +3 -13
  59. package/dist/agents/validation.d.ts.map +1 -1
  60. package/dist/ai-usage/execution.d.ts +53 -0
  61. package/dist/ai-usage/execution.d.ts.map +1 -0
  62. package/dist/ai-usage/index.d.ts +3 -0
  63. package/dist/ai-usage/index.d.ts.map +1 -0
  64. package/dist/auth/index.js +12 -9
  65. package/dist/auth/index.js.map +1 -1
  66. package/dist/authorization/decision.d.ts +14 -3
  67. package/dist/authorization/decision.d.ts.map +1 -1
  68. package/dist/authorization/grant-kinds.d.ts +25 -8
  69. package/dist/authorization/grant-kinds.d.ts.map +1 -1
  70. package/dist/authorization/index.d.ts +1 -1
  71. package/dist/authorization/index.d.ts.map +1 -1
  72. package/dist/authorization/index.js +12 -7
  73. package/dist/authorization/index.js.map +1 -1
  74. package/dist/authorization/resolve.d.ts +3 -3
  75. package/dist/authorization/resolve.d.ts.map +1 -1
  76. package/dist/authorization/types.d.ts +7 -5
  77. package/dist/authorization/types.d.ts.map +1 -1
  78. package/dist/blob-storage/browser.js +2 -2
  79. package/dist/blob-storage/index.js +3 -3
  80. package/dist/bootstrap/discovery.d.ts +6 -6
  81. package/dist/bootstrap/discovery.d.ts.map +1 -1
  82. package/dist/bootstrap/index.js +62 -51
  83. package/dist/bootstrap/index.js.map +1 -1
  84. package/dist/bootstrap/ontology-type-manifest.d.ts.map +1 -1
  85. package/dist/broker/index.js +2 -2
  86. package/dist/{chunk-zqysyfjt.js → chunk-08m3b6w8.js} +1 -1
  87. package/dist/chunk-19jp6g9d.js +131 -0
  88. package/dist/chunk-19jp6g9d.js.map +11 -0
  89. package/dist/{chunk-3j7573mj.js → chunk-2dw777qw.js} +50 -5
  90. package/dist/{chunk-3j7573mj.js.map → chunk-2dw777qw.js.map} +4 -3
  91. package/dist/{chunk-0172wgm9.js → chunk-2xns679x.js} +10 -2
  92. package/dist/{chunk-0172wgm9.js.map → chunk-2xns679x.js.map} +3 -3
  93. package/dist/chunk-359jm1jw.js +147 -0
  94. package/dist/chunk-359jm1jw.js.map +10 -0
  95. package/dist/{chunk-dy311asx.js → chunk-3xep5cjx.js} +58 -23
  96. package/dist/chunk-3xep5cjx.js.map +15 -0
  97. package/dist/{chunk-n4spznws.js → chunk-3z1qec12.js} +83 -12
  98. package/dist/chunk-3z1qec12.js.map +12 -0
  99. package/dist/{chunk-z3zp0bj1.js → chunk-407j3msh.js} +1 -1
  100. package/dist/{chunk-rhrbz7d4.js → chunk-4a849fr1.js} +1 -1
  101. package/dist/{chunk-cy0n5dms.js → chunk-4jjp5k14.js} +1 -1
  102. package/dist/chunk-4qfkag59.js +1568 -0
  103. package/dist/chunk-4qfkag59.js.map +20 -0
  104. package/dist/{chunk-1e8m6yn3.js → chunk-4sm0aznx.js} +685 -86
  105. package/dist/chunk-4sm0aznx.js.map +43 -0
  106. package/dist/chunk-4yqmp43v.js +159 -0
  107. package/dist/chunk-4yqmp43v.js.map +11 -0
  108. package/dist/{chunk-rdeagz6b.js → chunk-5e3pq99w.js} +3 -7
  109. package/dist/{chunk-rdeagz6b.js.map → chunk-5e3pq99w.js.map} +3 -3
  110. package/dist/{chunk-ezake7g1.js → chunk-5ntny1qx.js} +1 -1
  111. package/dist/{chunk-dm72y8wt.js → chunk-7y0f6rf1.js} +29 -16
  112. package/dist/chunk-7y0f6rf1.js.map +10 -0
  113. package/dist/{chunk-72q2y8hn.js → chunk-8tsf6dmc.js} +2 -2
  114. package/dist/{chunk-qewtks41.js → chunk-9nbmsvn5.js} +123 -20
  115. package/dist/chunk-9nbmsvn5.js.map +11 -0
  116. package/dist/{chunk-5sxb1168.js → chunk-aa2pen2v.js} +256 -82
  117. package/dist/chunk-aa2pen2v.js.map +34 -0
  118. package/dist/{chunk-819wnjz8.js → chunk-ajnan18g.js} +13 -10
  119. package/dist/chunk-ajnan18g.js.map +12 -0
  120. package/dist/chunk-c15dr03f.js +43 -0
  121. package/dist/chunk-c15dr03f.js.map +10 -0
  122. package/dist/{chunk-t0jjkep3.js → chunk-d8qkxt2v.js} +4 -2
  123. package/dist/chunk-d8qkxt2v.js.map +10 -0
  124. package/dist/{chunk-vybf6pkp.js → chunk-dbc80ad7.js} +1 -1
  125. package/dist/{chunk-nkbfrt0c.js → chunk-f26bck4t.js} +7 -7
  126. package/dist/{chunk-x2yw73hy.js → chunk-fvt9rjsa.js} +23 -7
  127. package/dist/chunk-fvt9rjsa.js.map +10 -0
  128. package/dist/{chunk-znagycq7.js → chunk-gbejpkex.js} +5 -5
  129. package/dist/{chunk-znagycq7.js.map → chunk-gbejpkex.js.map} +1 -1
  130. package/dist/{chunk-e42bc6m3.js → chunk-gzasd5b6.js} +5 -5
  131. package/dist/{chunk-e42bc6m3.js.map → chunk-gzasd5b6.js.map} +3 -3
  132. package/dist/{chunk-rnshztfq.js → chunk-h0k55pc7.js} +6 -6
  133. package/dist/{chunk-rnshztfq.js.map → chunk-h0k55pc7.js.map} +1 -1
  134. package/dist/chunk-h5vqbfmd.js +1537 -0
  135. package/dist/chunk-h5vqbfmd.js.map +19 -0
  136. package/dist/chunk-j1sbhm7p.js +45 -0
  137. package/dist/chunk-j1sbhm7p.js.map +10 -0
  138. package/dist/chunk-jecn6t54.js +307 -0
  139. package/dist/chunk-jecn6t54.js.map +12 -0
  140. package/dist/{chunk-dsrkgtnh.js → chunk-jq43kdvk.js} +1 -1
  141. package/dist/{chunk-wtmzkcht.js → chunk-k34z5rvh.js} +1 -1
  142. package/dist/{chunk-f6erf2vv.js → chunk-k522z7v6.js} +10 -5
  143. package/dist/chunk-k522z7v6.js.map +10 -0
  144. package/dist/{chunk-htq0qh7z.js → chunk-ka3a2ft3.js} +2 -2
  145. package/dist/{chunk-ckxfnx7f.js → chunk-mth82m8t.js} +129 -95
  146. package/dist/chunk-mth82m8t.js.map +14 -0
  147. package/dist/{chunk-5gynx4xn.js → chunk-mwsxn98e.js} +79 -77
  148. package/dist/{chunk-5gynx4xn.js.map → chunk-mwsxn98e.js.map} +8 -8
  149. package/dist/{chunk-f2rt4vkh.js → chunk-n2w475r0.js} +3 -3
  150. package/dist/chunk-n4khvw9n.js +111 -0
  151. package/dist/chunk-n4khvw9n.js.map +11 -0
  152. package/dist/{chunk-t8t39h7v.js → chunk-n6jxh8sw.js} +10 -2
  153. package/dist/chunk-n6jxh8sw.js.map +10 -0
  154. package/dist/chunk-nn0tekr1.js +284 -0
  155. package/dist/chunk-nn0tekr1.js.map +12 -0
  156. package/dist/chunk-nx7k8tpr.js +436 -0
  157. package/dist/chunk-nx7k8tpr.js.map +12 -0
  158. package/dist/{chunk-drjqm1aa.js → chunk-p03r0h5s.js} +310 -28
  159. package/dist/chunk-p03r0h5s.js.map +16 -0
  160. package/dist/{chunk-1g8negke.js → chunk-p1rzczbt.js} +93 -8
  161. package/dist/chunk-p1rzczbt.js.map +12 -0
  162. package/dist/{chunk-f83ka50g.js → chunk-p1x242ad.js} +652 -77
  163. package/dist/chunk-p1x242ad.js.map +25 -0
  164. package/dist/chunk-p2vqaxkc.js +528 -0
  165. package/dist/chunk-p2vqaxkc.js.map +15 -0
  166. package/dist/{chunk-a31h57d5.js → chunk-pc7ys28c.js} +70 -7
  167. package/dist/chunk-pc7ys28c.js.map +14 -0
  168. package/dist/{chunk-md8k0r54.js → chunk-q0k9nc5a.js} +281 -89
  169. package/dist/chunk-q0k9nc5a.js.map +14 -0
  170. package/dist/{chunk-bhxaq2nn.js → chunk-qw9gvjv5.js} +1 -1
  171. package/dist/chunk-r8jrnexe.js +403 -0
  172. package/dist/chunk-r8jrnexe.js.map +10 -0
  173. package/dist/{chunk-h9kxd41f.js → chunk-rafagrwr.js} +48 -7
  174. package/dist/chunk-rafagrwr.js.map +11 -0
  175. package/dist/{chunk-dysw7nsm.js → chunk-rv2hkwwa.js} +2 -2
  176. package/dist/{chunk-ghteq96b.js → chunk-s5y30bc9.js} +2 -2
  177. package/dist/{chunk-t624af60.js → chunk-sbzzr4kx.js} +1848 -757
  178. package/dist/chunk-sbzzr4kx.js.map +63 -0
  179. package/dist/{chunk-6gjqgd3d.js → chunk-tpnd31c1.js} +2 -1
  180. package/dist/chunk-tpnd31c1.js.map +11 -0
  181. package/dist/chunk-trxxmgnf.js +68 -0
  182. package/dist/chunk-trxxmgnf.js.map +11 -0
  183. package/dist/{chunk-0hc5j867.js → chunk-v1xppd0y.js} +17 -13
  184. package/dist/{chunk-0hc5j867.js.map → chunk-v1xppd0y.js.map} +2 -2
  185. package/dist/chunk-v4en4jc2.js +252 -0
  186. package/dist/chunk-v4en4jc2.js.map +10 -0
  187. package/dist/{chunk-xkthy56g.js → chunk-w1tvjszy.js} +1 -1
  188. package/dist/{chunk-8b55ygje.js → chunk-w3e09qqk.js} +1 -1
  189. package/dist/{chunk-8gv5z0zm.js → chunk-w9tg6yyb.js} +13 -8
  190. package/dist/{chunk-8gv5z0zm.js.map → chunk-w9tg6yyb.js.map} +3 -3
  191. package/dist/{chunk-62c7t4jc.js → chunk-wdage1eb.js} +1 -1
  192. package/dist/{chunk-tg5mee00.js → chunk-wtf06et8.js} +11 -7
  193. package/dist/{chunk-tg5mee00.js.map → chunk-wtf06et8.js.map} +3 -3
  194. package/dist/{chunk-nva1xkjz.js → chunk-xajtptbw.js} +1237 -1434
  195. package/dist/chunk-xajtptbw.js.map +40 -0
  196. package/dist/{chunk-xc7hq65b.js → chunk-yp8ee62z.js} +49 -2
  197. package/dist/chunk-yp8ee62z.js.map +11 -0
  198. package/dist/chunk-z4ccwbkz.js +139 -0
  199. package/dist/chunk-z4ccwbkz.js.map +10 -0
  200. package/dist/datasets/builders.d.ts +11 -2
  201. package/dist/datasets/builders.d.ts.map +1 -1
  202. package/dist/datasets/changes.d.ts +14 -4
  203. package/dist/datasets/changes.d.ts.map +1 -1
  204. package/dist/datasets/execution.d.ts +15 -1
  205. package/dist/datasets/execution.d.ts.map +1 -1
  206. package/dist/datasets/index.d.ts +1 -0
  207. package/dist/datasets/index.d.ts.map +1 -1
  208. package/dist/datasets/sequence.d.ts +7 -0
  209. package/dist/datasets/sequence.d.ts.map +1 -0
  210. package/dist/datasets/types.d.ts +1 -0
  211. package/dist/datasets/types.d.ts.map +1 -1
  212. package/dist/datasets/validation.d.ts.map +1 -1
  213. package/dist/datasets/write.d.ts +37 -0
  214. package/dist/datasets/write.d.ts.map +1 -0
  215. package/dist/datasets/write.js +17 -0
  216. package/dist/datasets/write.js.map +9 -0
  217. package/dist/error-reporting/internal.js +4 -4
  218. package/dist/error-reporting/types.d.ts +7 -2
  219. package/dist/error-reporting/types.d.ts.map +1 -1
  220. package/dist/errors/catalog.d.ts +8 -0
  221. package/dist/errors/catalog.d.ts.map +1 -1
  222. package/dist/errors/internal.js +2 -2
  223. package/dist/events/execution.d.ts.map +1 -1
  224. package/dist/events/index.js +4 -4
  225. package/dist/events/types/datasets.d.ts +2 -6
  226. package/dist/events/types/datasets.d.ts.map +1 -1
  227. package/dist/execution/agent.d.ts +18 -9
  228. package/dist/execution/agent.d.ts.map +1 -1
  229. package/dist/execution/agent.js +62 -46
  230. package/dist/execution/agent.js.map +1 -1
  231. package/dist/execution/authorization.d.ts +68 -20
  232. package/dist/execution/authorization.d.ts.map +1 -1
  233. package/dist/execution/authorized-object-reader.d.ts +69 -0
  234. package/dist/execution/authorized-object-reader.d.ts.map +1 -0
  235. package/dist/execution/durable.d.ts.map +1 -1
  236. package/dist/execution/index.d.ts +1 -1
  237. package/dist/execution/index.d.ts.map +1 -1
  238. package/dist/execution/primitive.js +55 -46
  239. package/dist/execution/primitive.js.map +2 -2
  240. package/dist/execution/request.d.ts +14 -1
  241. package/dist/execution/request.d.ts.map +1 -1
  242. package/dist/execution/request.js +92 -54
  243. package/dist/execution/request.js.map +3 -3
  244. package/dist/execution/scopes.d.ts +16 -0
  245. package/dist/execution/scopes.d.ts.map +1 -1
  246. package/dist/execution/types.d.ts +10 -1
  247. package/dist/execution/types.d.ts.map +1 -1
  248. package/dist/http/api-routes.d.ts +2 -0
  249. package/dist/http/api-routes.d.ts.map +1 -1
  250. package/dist/http/index.js +1 -1
  251. package/dist/index.d.ts +15 -9
  252. package/dist/index.d.ts.map +1 -1
  253. package/dist/index.js +128 -109
  254. package/dist/index.js.map +1 -1
  255. package/dist/json.d.ts +2 -0
  256. package/dist/json.d.ts.map +1 -1
  257. package/dist/lake-storage/definition-updates.d.ts.map +1 -1
  258. package/dist/lake-storage/errors.d.ts +5 -1
  259. package/dist/lake-storage/errors.d.ts.map +1 -1
  260. package/dist/lake-storage/in-memory.d.ts +1 -0
  261. package/dist/lake-storage/in-memory.d.ts.map +1 -1
  262. package/dist/lake-storage/index.d.ts +6 -1
  263. package/dist/lake-storage/index.d.ts.map +1 -1
  264. package/dist/lake-storage/index.js +27 -10
  265. package/dist/lake-storage/index.js.map +1 -1
  266. package/dist/lake-storage/merge-validation.d.ts.map +1 -1
  267. package/dist/lake-storage/merge.d.ts +13 -2
  268. package/dist/lake-storage/merge.d.ts.map +1 -1
  269. package/dist/lake-storage/source-ordering.d.ts +19 -0
  270. package/dist/lake-storage/source-ordering.d.ts.map +1 -0
  271. package/dist/lake-storage/sql-transforms.d.ts +2 -1
  272. package/dist/lake-storage/sql-transforms.d.ts.map +1 -1
  273. package/dist/lake-storage/types.d.ts +10 -5
  274. package/dist/lake-storage/types.d.ts.map +1 -1
  275. package/dist/lake-storage/version-inputs.d.ts +4 -0
  276. package/dist/lake-storage/version-inputs.d.ts.map +1 -0
  277. package/dist/logging/index.js +3 -3
  278. package/dist/logging/types.js +2 -2
  279. package/dist/materialization/index.js +2 -2
  280. package/dist/materializer/index.js +38 -31
  281. package/dist/materializer/index.js.map +1 -1
  282. package/dist/models/catalog.d.ts +40 -0
  283. package/dist/models/catalog.d.ts.map +1 -0
  284. package/dist/models/definitions.d.ts +25 -0
  285. package/dist/models/definitions.d.ts.map +1 -0
  286. package/dist/models/errors.d.ts +52 -0
  287. package/dist/models/errors.d.ts.map +1 -0
  288. package/dist/models/events.d.ts +192 -0
  289. package/dist/models/events.d.ts.map +1 -0
  290. package/dist/models/index.d.ts +17 -39
  291. package/dist/models/index.d.ts.map +1 -1
  292. package/dist/models/index.js +50 -0
  293. package/dist/models/index.js.map +9 -0
  294. package/dist/models/language-model.d.ts +90 -0
  295. package/dist/models/language-model.d.ts.map +1 -0
  296. package/dist/models/messages.d.ts +74 -0
  297. package/dist/models/messages.d.ts.map +1 -0
  298. package/dist/models/pricing.d.ts +69 -0
  299. package/dist/models/pricing.d.ts.map +1 -0
  300. package/dist/models/rate-card.d.ts +24 -0
  301. package/dist/models/rate-card.d.ts.map +1 -0
  302. package/dist/models/tools.d.ts +24 -0
  303. package/dist/models/tools.d.ts.map +1 -0
  304. package/dist/objects/authorized-ontology-view.d.ts +25 -0
  305. package/dist/objects/authorized-ontology-view.d.ts.map +1 -0
  306. package/dist/objects/execution.d.ts +1 -1
  307. package/dist/objects/execution.d.ts.map +1 -1
  308. package/dist/objects/index.js +43 -36
  309. package/dist/objects/index.js.map +1 -1
  310. package/dist/objects/link/authorization.d.ts +2 -7
  311. package/dist/objects/link/authorization.d.ts.map +1 -1
  312. package/dist/objects/query/executor.d.ts +4 -2
  313. package/dist/objects/query/executor.d.ts.map +1 -1
  314. package/dist/objects/query/index.js +36 -29
  315. package/dist/objects/query/index.js.map +1 -1
  316. package/dist/objects/query/links.d.ts +22 -1
  317. package/dist/objects/query/links.d.ts.map +1 -1
  318. package/dist/objects/query/selected-read-admission.d.ts +27 -0
  319. package/dist/objects/query/selected-read-admission.d.ts.map +1 -0
  320. package/dist/objects/query/validate.d.ts +60 -2
  321. package/dist/objects/query/validate.d.ts.map +1 -1
  322. package/dist/objects/sdk/object-handle.d.ts.map +1 -1
  323. package/dist/objects/sdk/object-set.d.ts.map +1 -1
  324. package/dist/objects/sdk/runtime-query-executor.d.ts +2 -7
  325. package/dist/objects/sdk/runtime-query-executor.d.ts.map +1 -1
  326. package/dist/objects/sdk/telemetry-channel.d.ts.map +1 -1
  327. package/dist/objects/service/list-service.d.ts +2 -3
  328. package/dist/objects/service/list-service.d.ts.map +1 -1
  329. package/dist/objects/telemetry/history.d.ts +8 -6
  330. package/dist/objects/telemetry/history.d.ts.map +1 -1
  331. package/dist/objects/telemetry/index.d.ts +2 -2
  332. package/dist/objects/telemetry/index.d.ts.map +1 -1
  333. package/dist/objects/telemetry/workload.d.ts +11 -0
  334. package/dist/objects/telemetry/workload.d.ts.map +1 -0
  335. package/dist/ontology/index.d.ts +2 -1
  336. package/dist/ontology/index.d.ts.map +1 -1
  337. package/dist/ontology/index.js +15 -14
  338. package/dist/ontology/index.js.map +1 -1
  339. package/dist/ontology/inference/index.d.ts +2 -1
  340. package/dist/ontology/inference/index.d.ts.map +1 -1
  341. package/dist/ontology/internal.d.ts +0 -1
  342. package/dist/ontology/internal.d.ts.map +1 -1
  343. package/dist/ontology/internal.js +5 -10
  344. package/dist/ontology/internal.js.map +3 -3
  345. package/dist/ontology/json-schema.d.ts +10 -6
  346. package/dist/ontology/json-schema.d.ts.map +1 -1
  347. package/dist/ontology/link-path-selection.d.ts +35 -0
  348. package/dist/ontology/link-path-selection.d.ts.map +1 -0
  349. package/dist/ontology/refs.d.ts +2 -0
  350. package/dist/ontology/refs.d.ts.map +1 -1
  351. package/dist/ontology/tokens.d.ts +2 -1
  352. package/dist/ontology/tokens.d.ts.map +1 -1
  353. package/dist/pipelines/execution.d.ts.map +1 -1
  354. package/dist/pipelines/index.js +41 -36
  355. package/dist/pipelines/index.js.map +1 -1
  356. package/dist/pipelines/request.d.ts.map +1 -1
  357. package/dist/projections/execution.d.ts.map +1 -1
  358. package/dist/projections/internal.js +39 -32
  359. package/dist/projections/internal.js.map +1 -1
  360. package/dist/projections/run-dispatch.d.ts.map +1 -1
  361. package/dist/queues/in-memory.d.ts +3 -2
  362. package/dist/queues/in-memory.d.ts.map +1 -1
  363. package/dist/queues/index.d.ts +3 -1
  364. package/dist/queues/index.d.ts.map +1 -1
  365. package/dist/queues/index.js +1 -1
  366. package/dist/queues/types.d.ts +15 -3
  367. package/dist/queues/types.d.ts.map +1 -1
  368. package/dist/rules/execution.d.ts.map +1 -1
  369. package/dist/runtime/create.d.ts +7 -4
  370. package/dist/runtime/create.d.ts.map +1 -1
  371. package/dist/runtime/definitions.d.ts +4 -2
  372. package/dist/runtime/definitions.d.ts.map +1 -1
  373. package/dist/runtime/host.d.ts +5 -2
  374. package/dist/runtime/host.d.ts.map +1 -1
  375. package/dist/runtime/internal.d.ts +1 -0
  376. package/dist/runtime/internal.d.ts.map +1 -1
  377. package/dist/runtime/resolve-definitions.d.ts +4 -2
  378. package/dist/runtime/resolve-definitions.d.ts.map +1 -1
  379. package/dist/runtime/sixb.d.ts +8 -2
  380. package/dist/runtime/sixb.d.ts.map +1 -1
  381. package/dist/runtime/types.d.ts +3 -0
  382. package/dist/runtime/types.d.ts.map +1 -1
  383. package/dist/schedules/execution.d.ts +2 -1
  384. package/dist/schedules/execution.d.ts.map +1 -1
  385. package/dist/security/every.d.ts +4 -4
  386. package/dist/security/every.d.ts.map +1 -1
  387. package/dist/security/grants.d.ts +12 -6
  388. package/dist/security/grants.d.ts.map +1 -1
  389. package/dist/security/index.d.ts +1 -1
  390. package/dist/security/index.d.ts.map +1 -1
  391. package/dist/security/registry.d.ts +2 -1
  392. package/dist/security/registry.d.ts.map +1 -1
  393. package/dist/security/types.d.ts +19 -5
  394. package/dist/security/types.d.ts.map +1 -1
  395. package/dist/security/validation.d.ts +6 -2
  396. package/dist/security/validation.d.ts.map +1 -1
  397. package/dist/shares/access-plan.d.ts +22 -0
  398. package/dist/shares/access-plan.d.ts.map +1 -0
  399. package/dist/shares/builders.d.ts +14 -0
  400. package/dist/shares/builders.d.ts.map +1 -0
  401. package/dist/shares/compiler.d.ts +14 -0
  402. package/dist/shares/compiler.d.ts.map +1 -0
  403. package/dist/shares/errors.d.ts +4 -0
  404. package/dist/shares/errors.d.ts.map +1 -0
  405. package/dist/shares/execution.d.ts +57 -0
  406. package/dist/shares/execution.d.ts.map +1 -0
  407. package/dist/shares/index.d.ts +10 -0
  408. package/dist/shares/index.d.ts.map +1 -0
  409. package/dist/shares/internal.d.ts +3 -0
  410. package/dist/shares/internal.d.ts.map +1 -0
  411. package/dist/shares/internal.js +239 -0
  412. package/dist/shares/internal.js.map +10 -0
  413. package/dist/shares/intersection.d.ts +9 -0
  414. package/dist/shares/intersection.d.ts.map +1 -0
  415. package/dist/shares/session-protocol.d.ts +41 -0
  416. package/dist/shares/session-protocol.d.ts.map +1 -0
  417. package/dist/shares/types.d.ts +51 -0
  418. package/dist/shares/types.d.ts.map +1 -0
  419. package/dist/shares/validation.d.ts +11 -0
  420. package/dist/shares/validation.d.ts.map +1 -0
  421. package/dist/storage/action-runs/failure.js +3 -3
  422. package/dist/storage/action-runs/provider.js +2 -2
  423. package/dist/storage/agents/errors.d.ts +1 -1
  424. package/dist/storage/agents/errors.d.ts.map +1 -1
  425. package/dist/storage/agents/in-memory.d.ts +3 -2
  426. package/dist/storage/agents/in-memory.d.ts.map +1 -1
  427. package/dist/storage/agents/index.d.ts +1 -1
  428. package/dist/storage/agents/index.d.ts.map +1 -1
  429. package/dist/storage/agents/provider.d.ts +11 -4
  430. package/dist/storage/agents/provider.d.ts.map +1 -1
  431. package/dist/storage/agents/provider.js +18 -15
  432. package/dist/storage/agents/provider.js.map +1 -1
  433. package/dist/storage/agents/types.d.ts +65 -17
  434. package/dist/storage/agents/types.d.ts.map +1 -1
  435. package/dist/storage/ai-cost/analytics.d.ts +2 -1
  436. package/dist/storage/ai-cost/analytics.d.ts.map +1 -1
  437. package/dist/storage/ai-cost/codec.d.ts +3 -2
  438. package/dist/storage/ai-cost/codec.d.ts.map +1 -1
  439. package/dist/storage/ai-cost/groups.d.ts +51 -0
  440. package/dist/storage/ai-cost/groups.d.ts.map +1 -0
  441. package/dist/storage/ai-cost/in-memory.d.ts +11 -1
  442. package/dist/storage/ai-cost/in-memory.d.ts.map +1 -1
  443. package/dist/storage/ai-cost/index.d.ts +1 -1
  444. package/dist/storage/ai-cost/index.d.ts.map +1 -1
  445. package/dist/storage/ai-cost/provider.d.ts +2 -0
  446. package/dist/storage/ai-cost/provider.d.ts.map +1 -1
  447. package/dist/storage/ai-cost/provider.js +29 -13
  448. package/dist/storage/ai-cost/provider.js.map +3 -3
  449. package/dist/storage/ai-cost/types.d.ts +64 -15
  450. package/dist/storage/ai-cost/types.d.ts.map +1 -1
  451. package/dist/storage/ai-cost/validation.d.ts +2 -1
  452. package/dist/storage/ai-cost/validation.d.ts.map +1 -1
  453. package/dist/storage/ai-limits/enforcement.d.ts +14 -0
  454. package/dist/storage/ai-limits/enforcement.d.ts.map +1 -0
  455. package/dist/storage/ai-limits/enforcement.js +21 -0
  456. package/dist/storage/ai-limits/enforcement.js.map +9 -0
  457. package/dist/storage/ai-limits/errors.d.ts +8 -0
  458. package/dist/storage/ai-limits/errors.d.ts.map +1 -0
  459. package/dist/storage/ai-limits/in-memory.d.ts +78 -0
  460. package/dist/storage/ai-limits/in-memory.d.ts.map +1 -0
  461. package/dist/storage/ai-limits/index.d.ts +7 -0
  462. package/dist/storage/ai-limits/index.d.ts.map +1 -0
  463. package/dist/storage/ai-limits/period.d.ts +4 -0
  464. package/dist/storage/ai-limits/period.d.ts.map +1 -0
  465. package/dist/storage/ai-limits/provider.d.ts +85 -0
  466. package/dist/storage/ai-limits/provider.d.ts.map +1 -0
  467. package/dist/storage/ai-limits/provider.js +62 -0
  468. package/dist/storage/ai-limits/provider.js.map +9 -0
  469. package/dist/storage/ai-limits/types.d.ts +175 -0
  470. package/dist/storage/ai-limits/types.d.ts.map +1 -0
  471. package/dist/storage/ai-usage/in-memory.d.ts +4 -0
  472. package/dist/storage/ai-usage/in-memory.d.ts.map +1 -1
  473. package/dist/storage/ai-usage/record.d.ts.map +1 -1
  474. package/dist/storage/ai-usage/types.d.ts +6 -2
  475. package/dist/storage/ai-usage/types.d.ts.map +1 -1
  476. package/dist/storage/auth/errors.d.ts +1 -1
  477. package/dist/storage/auth/errors.d.ts.map +1 -1
  478. package/dist/storage/auth/in-memory/auth-storage.d.ts +4 -1
  479. package/dist/storage/auth/in-memory/auth-storage.d.ts.map +1 -1
  480. package/dist/storage/auth/in-memory/device-authorizations.d.ts +29 -0
  481. package/dist/storage/auth/in-memory/device-authorizations.d.ts.map +1 -0
  482. package/dist/storage/auth/in-memory/shared.d.ts +3 -1
  483. package/dist/storage/auth/in-memory/shared.d.ts.map +1 -1
  484. package/dist/storage/auth/index.d.ts +2 -1
  485. package/dist/storage/auth/index.d.ts.map +1 -1
  486. package/dist/storage/auth/types.d.ts +66 -0
  487. package/dist/storage/auth/types.d.ts.map +1 -1
  488. package/dist/storage/connector-connections/provider.js +2 -2
  489. package/dist/storage/executions/in-memory.d.ts +3 -0
  490. package/dist/storage/executions/in-memory.d.ts.map +1 -1
  491. package/dist/storage/executions/provider.d.ts +4 -1
  492. package/dist/storage/executions/provider.d.ts.map +1 -1
  493. package/dist/storage/executions/provider.js +23 -3
  494. package/dist/storage/executions/provider.js.map +3 -3
  495. package/dist/storage/executions/run-link.d.ts +14 -2
  496. package/dist/storage/executions/run-link.d.ts.map +1 -1
  497. package/dist/storage/executions/validation.d.ts +6 -0
  498. package/dist/storage/executions/validation.d.ts.map +1 -1
  499. package/dist/storage/in-memory/index.d.ts +12 -0
  500. package/dist/storage/in-memory/index.d.ts.map +1 -1
  501. package/dist/storage/index.d.ts +15 -6
  502. package/dist/storage/index.d.ts.map +1 -1
  503. package/dist/storage/index.js +78 -36
  504. package/dist/storage/index.js.map +1 -1
  505. package/dist/storage/objects/execution-limits.d.ts +25 -0
  506. package/dist/storage/objects/execution-limits.d.ts.map +1 -0
  507. package/dist/storage/objects/guard.d.ts +16 -0
  508. package/dist/storage/objects/guard.d.ts.map +1 -0
  509. package/dist/storage/objects/in-memory/index.d.ts +3 -0
  510. package/dist/storage/objects/in-memory/index.d.ts.map +1 -0
  511. package/dist/storage/objects/in-memory/keys.d.ts +10 -0
  512. package/dist/storage/objects/in-memory/keys.d.ts.map +1 -0
  513. package/dist/storage/objects/in-memory/query.d.ts +31 -0
  514. package/dist/storage/objects/in-memory/query.d.ts.map +1 -0
  515. package/dist/storage/objects/in-memory/read-scope.d.ts +18 -0
  516. package/dist/storage/objects/in-memory/read-scope.d.ts.map +1 -0
  517. package/dist/storage/objects/in-memory/read-source.d.ts +10 -0
  518. package/dist/storage/objects/in-memory/read-source.d.ts.map +1 -0
  519. package/dist/storage/objects/in-memory/selected-reader.d.ts +9 -0
  520. package/dist/storage/objects/in-memory/selected-reader.d.ts.map +1 -0
  521. package/dist/storage/objects/{in-memory.d.ts → in-memory/storage.d.ts} +13 -10
  522. package/dist/storage/objects/in-memory/storage.d.ts.map +1 -0
  523. package/dist/storage/objects/index.d.ts +4 -1
  524. package/dist/storage/objects/index.d.ts.map +1 -1
  525. package/dist/storage/objects/keys.d.ts +1 -1
  526. package/dist/storage/objects/keys.d.ts.map +1 -1
  527. package/dist/storage/objects/read-scope.d.ts +25 -0
  528. package/dist/storage/objects/read-scope.d.ts.map +1 -0
  529. package/dist/storage/objects/types.d.ts +114 -22
  530. package/dist/storage/objects/types.d.ts.map +1 -1
  531. package/dist/storage/ontology/provider.js +3 -3
  532. package/dist/storage/operation-scope.d.ts +3 -0
  533. package/dist/storage/operation-scope.d.ts.map +1 -1
  534. package/dist/storage/operation-scope.js +4 -2
  535. package/dist/storage/operation-scope.js.map +1 -1
  536. package/dist/storage/pipeline-runs/provider.js +2 -2
  537. package/dist/storage/projection-runs/provider.js +4 -4
  538. package/dist/storage/share-grants/errors.d.ts +8 -0
  539. package/dist/storage/share-grants/errors.d.ts.map +1 -0
  540. package/dist/storage/share-grants/in-memory.d.ts +11 -0
  541. package/dist/storage/share-grants/in-memory.d.ts.map +1 -0
  542. package/dist/storage/share-grants/index.d.ts +5 -0
  543. package/dist/storage/share-grants/index.d.ts.map +1 -0
  544. package/dist/storage/share-grants/provider.d.ts +4 -0
  545. package/dist/storage/share-grants/provider.d.ts.map +1 -0
  546. package/dist/storage/share-grants/provider.js +24 -0
  547. package/dist/storage/share-grants/provider.js.map +9 -0
  548. package/dist/storage/share-grants/record.d.ts +11 -0
  549. package/dist/storage/share-grants/record.d.ts.map +1 -0
  550. package/dist/storage/share-grants/types.d.ts +97 -0
  551. package/dist/storage/share-grants/types.d.ts.map +1 -0
  552. package/dist/storage/share-sessions/errors.d.ts +8 -0
  553. package/dist/storage/share-sessions/errors.d.ts.map +1 -0
  554. package/dist/storage/share-sessions/in-memory.d.ts +14 -0
  555. package/dist/storage/share-sessions/in-memory.d.ts.map +1 -0
  556. package/dist/storage/share-sessions/index.d.ts +5 -0
  557. package/dist/storage/share-sessions/index.d.ts.map +1 -0
  558. package/dist/storage/share-sessions/provider.d.ts +3 -0
  559. package/dist/storage/share-sessions/provider.d.ts.map +1 -0
  560. package/dist/storage/share-sessions/provider.js +20 -0
  561. package/dist/storage/share-sessions/provider.js.map +9 -0
  562. package/dist/storage/share-sessions/record.d.ts +8 -0
  563. package/dist/storage/share-sessions/record.d.ts.map +1 -0
  564. package/dist/storage/share-sessions/types.d.ts +50 -0
  565. package/dist/storage/share-sessions/types.d.ts.map +1 -0
  566. package/dist/storage/sync-runs/provider.js +2 -2
  567. package/dist/storage/transaction.d.ts +2 -1
  568. package/dist/storage/transaction.d.ts.map +1 -1
  569. package/dist/storage/types.d.ts +13 -1
  570. package/dist/storage/types.d.ts.map +1 -1
  571. package/dist/storage/webhook-runs/provider.js +2 -2
  572. package/dist/storage/workflow-runs/provider.d.ts +1 -1
  573. package/dist/storage/workflow-runs/provider.js +14 -12
  574. package/dist/storage/workflow-runs/provider.js.map +1 -1
  575. package/dist/storage/workflow-runs/types.d.ts +5 -4
  576. package/dist/storage/workflow-runs/types.d.ts.map +1 -1
  577. package/dist/syncs/execution.d.ts.map +1 -1
  578. package/dist/syncs/index.js +41 -36
  579. package/dist/syncs/index.js.map +1 -1
  580. package/dist/syncs/request.d.ts.map +1 -1
  581. package/dist/testing/agent-execution.d.ts +3 -1
  582. package/dist/testing/agent-execution.d.ts.map +1 -1
  583. package/dist/testing/agent-storage-contract.d.ts.map +1 -1
  584. package/dist/testing/ai-cost-storage-contract.d.ts.map +1 -1
  585. package/dist/testing/ai-limit-storage-contract.d.ts +18 -0
  586. package/dist/testing/ai-limit-storage-contract.d.ts.map +1 -0
  587. package/dist/testing/ai-model-call-groups-contract.d.ts +6 -0
  588. package/dist/testing/ai-model-call-groups-contract.d.ts.map +1 -0
  589. package/dist/testing/ai-usage-storage-contract.d.ts.map +1 -1
  590. package/dist/testing/auth-storage-contract.d.ts.map +1 -1
  591. package/dist/testing/dataset-sequence-contract.d.ts +4 -0
  592. package/dist/testing/dataset-sequence-contract.d.ts.map +1 -0
  593. package/dist/testing/effective-storage-contract.d.ts.map +1 -1
  594. package/dist/testing/execution-storage-contract.d.ts +4 -0
  595. package/dist/testing/execution-storage-contract.d.ts.map +1 -1
  596. package/dist/testing/index.d.ts +5 -0
  597. package/dist/testing/index.d.ts.map +1 -1
  598. package/dist/testing/index.js +5392 -2070
  599. package/dist/testing/index.js.map +21 -15
  600. package/dist/testing/lake-merge-storage-contract.d.ts +1 -0
  601. package/dist/testing/lake-merge-storage-contract.d.ts.map +1 -1
  602. package/dist/testing/lake-storage-contract.d.ts.map +1 -1
  603. package/dist/testing/object-read-scope-contract.d.ts +22 -0
  604. package/dist/testing/object-read-scope-contract.d.ts.map +1 -0
  605. package/dist/testing/queues-contract.d.ts.map +1 -1
  606. package/dist/testing/share-grant-storage-contract.d.ts +10 -0
  607. package/dist/testing/share-grant-storage-contract.d.ts.map +1 -0
  608. package/dist/testing/share-session-storage-contract.d.ts +9 -0
  609. package/dist/testing/share-session-storage-contract.d.ts.map +1 -0
  610. package/dist/webhooks/internal.js +36 -29
  611. package/dist/webhooks/internal.js.map +2 -2
  612. package/dist/workers/index.js +2 -2
  613. package/dist/workflows/agent-step-identity.d.ts +3 -0
  614. package/dist/workflows/agent-step-identity.d.ts.map +1 -0
  615. package/dist/workflows/builders.d.ts +2 -3
  616. package/dist/workflows/builders.d.ts.map +1 -1
  617. package/dist/workflows/execution.d.ts +1 -1
  618. package/dist/workflows/execution.d.ts.map +1 -1
  619. package/dist/workflows/failure.d.ts +1 -1
  620. package/dist/workflows/failure.d.ts.map +1 -1
  621. package/dist/workflows/index.d.ts +3 -2
  622. package/dist/workflows/index.d.ts.map +1 -1
  623. package/dist/workflows/index.js +63 -48
  624. package/dist/workflows/index.js.map +1 -1
  625. package/dist/workflows/request.d.ts.map +1 -1
  626. package/dist/workflows/types.d.ts +26 -11
  627. package/dist/workflows/types.d.ts.map +1 -1
  628. package/dist/workflows/validation.d.ts +7 -1
  629. package/dist/workflows/validation.d.ts.map +1 -1
  630. package/package.json +43 -4
  631. package/src/actions/delegated-admission.ts +72 -0
  632. package/src/actions/descriptor.ts +58 -0
  633. package/src/actions/execution.ts +99 -24
  634. package/src/actions/request.ts +136 -19
  635. package/src/actions/run-authorization.ts +53 -0
  636. package/src/actions/run-dispatch.ts +8 -1
  637. package/src/agents/adapters.ts +60 -456
  638. package/src/agents/authority.ts +215 -34
  639. package/src/agents/builders.ts +3 -50
  640. package/src/agents/context-compaction.ts +4 -0
  641. package/src/agents/context-resolution.ts +1 -4
  642. package/src/agents/dispatch.ts +59 -2
  643. package/src/agents/errors.ts +4 -11
  644. package/src/agents/execution.ts +65 -56
  645. package/src/agents/identity.ts +4 -0
  646. package/src/agents/ids.ts +16 -1
  647. package/src/agents/index.ts +23 -30
  648. package/src/agents/message.ts +20 -12
  649. package/src/agents/model-loop.ts +1071 -0
  650. package/src/agents/reference.ts +7 -0
  651. package/src/agents/request.ts +157 -77
  652. package/src/agents/retired-config.ts +20 -0
  653. package/src/agents/streams.ts +45 -19
  654. package/src/agents/tool-catalog.ts +21 -0
  655. package/src/agents/tool-definition.ts +9 -5
  656. package/src/agents/types.ts +39 -81
  657. package/src/agents/validation.ts +11 -216
  658. package/src/ai-usage/execution.ts +189 -0
  659. package/src/ai-usage/index.ts +15 -0
  660. package/src/authorization/decision.ts +54 -22
  661. package/src/authorization/grant-kinds.ts +72 -15
  662. package/src/authorization/index.ts +2 -0
  663. package/src/authorization/resolve.ts +12 -5
  664. package/src/authorization/types.ts +7 -5
  665. package/src/bootstrap/discovery.ts +3 -3
  666. package/src/bootstrap/ontology-type-manifest.ts +12 -6
  667. package/src/datasets/builders.ts +23 -2
  668. package/src/datasets/changes.ts +16 -4
  669. package/src/datasets/execution.ts +76 -5
  670. package/src/datasets/index.ts +1 -0
  671. package/src/datasets/sequence.ts +77 -0
  672. package/src/datasets/types.ts +1 -0
  673. package/src/datasets/validation.ts +26 -0
  674. package/src/datasets/write.ts +240 -0
  675. package/src/error-reporting/types.ts +4 -2
  676. package/src/errors/catalog.ts +8 -0
  677. package/src/events/execution.ts +57 -7
  678. package/src/events/types/datasets.ts +2 -6
  679. package/src/execution/agent.ts +129 -25
  680. package/src/execution/authorization.ts +493 -83
  681. package/src/execution/authorized-object-reader.ts +695 -0
  682. package/src/execution/durable.ts +10 -2
  683. package/src/execution/index.ts +1 -0
  684. package/src/execution/request.ts +67 -14
  685. package/src/execution/scopes.ts +36 -6
  686. package/src/execution/types.ts +9 -1
  687. package/src/http/api-routes.ts +108 -0
  688. package/src/index.ts +72 -22
  689. package/src/json.ts +9 -0
  690. package/src/lake-storage/definition-updates.ts +9 -0
  691. package/src/lake-storage/errors.ts +6 -1
  692. package/src/lake-storage/in-memory.ts +53 -17
  693. package/src/lake-storage/index.ts +10 -1
  694. package/src/lake-storage/merge-validation.ts +12 -2
  695. package/src/lake-storage/merge.ts +40 -2
  696. package/src/lake-storage/source-ordering.ts +95 -0
  697. package/src/lake-storage/sql-transforms.ts +2 -1
  698. package/src/lake-storage/types.ts +10 -5
  699. package/src/lake-storage/version-inputs.ts +14 -0
  700. package/src/models/catalog.ts +137 -0
  701. package/src/models/definitions.ts +202 -0
  702. package/src/models/errors.ts +83 -0
  703. package/src/models/events.ts +198 -0
  704. package/src/models/index.ts +89 -71
  705. package/src/models/language-model.ts +143 -0
  706. package/src/models/messages.ts +78 -0
  707. package/src/models/pricing.ts +390 -0
  708. package/src/models/rate-card.ts +101 -0
  709. package/src/models/tools.ts +29 -0
  710. package/src/objects/authorized-ontology-view.ts +512 -0
  711. package/src/objects/execution.ts +98 -143
  712. package/src/objects/link/authorization.ts +3 -2
  713. package/src/objects/query/executor.ts +45 -34
  714. package/src/objects/query/links.ts +84 -25
  715. package/src/objects/query/selected-read-admission.ts +310 -0
  716. package/src/objects/query/validate.ts +353 -36
  717. package/src/objects/sdk/object-handle.ts +2 -8
  718. package/src/objects/sdk/object-set.ts +10 -11
  719. package/src/objects/sdk/runtime-query-executor.ts +8 -28
  720. package/src/objects/sdk/telemetry-channel.ts +11 -7
  721. package/src/objects/service/list-service.ts +15 -29
  722. package/src/objects/telemetry/history.ts +297 -17
  723. package/src/objects/telemetry/index.ts +2 -2
  724. package/src/objects/telemetry/workload.ts +79 -0
  725. package/src/ontology/index.ts +7 -1
  726. package/src/ontology/inference/index.ts +4 -1
  727. package/src/ontology/internal.ts +0 -1
  728. package/src/ontology/json-schema.ts +13 -12
  729. package/src/ontology/link-path-selection.ts +193 -0
  730. package/src/ontology/refs.ts +19 -0
  731. package/src/ontology/tokens.ts +15 -8
  732. package/src/pipelines/execution.ts +30 -7
  733. package/src/pipelines/request.ts +5 -0
  734. package/src/projections/execution.ts +72 -11
  735. package/src/projections/run-dispatch.ts +6 -12
  736. package/src/queues/in-memory.ts +5 -0
  737. package/src/queues/index.ts +11 -0
  738. package/src/queues/types.ts +20 -3
  739. package/src/rules/execution.ts +20 -8
  740. package/src/runtime/create.ts +11 -5
  741. package/src/runtime/definitions.ts +4 -2
  742. package/src/runtime/host.ts +28 -8
  743. package/src/runtime/internal.ts +1 -0
  744. package/src/runtime/resolve-definitions.ts +22 -36
  745. package/src/runtime/sixb.ts +29 -10
  746. package/src/runtime/types.ts +3 -0
  747. package/src/schedules/execution.ts +24 -2
  748. package/src/security/every.ts +4 -4
  749. package/src/security/grants.ts +100 -14
  750. package/src/security/index.ts +3 -0
  751. package/src/security/registry.ts +9 -5
  752. package/src/security/types.ts +23 -4
  753. package/src/security/validation.ts +33 -9
  754. package/src/shares/access-plan.ts +225 -0
  755. package/src/shares/builders.ts +381 -0
  756. package/src/shares/compiler.ts +359 -0
  757. package/src/shares/errors.ts +3 -0
  758. package/src/shares/execution.ts +394 -0
  759. package/src/shares/index.ts +28 -0
  760. package/src/shares/internal.ts +9 -0
  761. package/src/shares/intersection.ts +178 -0
  762. package/src/shares/session-protocol.ts +258 -0
  763. package/src/shares/types.ts +76 -0
  764. package/src/shares/validation.ts +40 -0
  765. package/src/storage/agents/errors.ts +1 -0
  766. package/src/storage/agents/in-memory.ts +121 -11
  767. package/src/storage/agents/index.ts +7 -0
  768. package/src/storage/agents/provider.ts +150 -6
  769. package/src/storage/agents/types.ts +73 -16
  770. package/src/storage/ai-cost/analytics.ts +63 -6
  771. package/src/storage/ai-cost/codec.ts +37 -12
  772. package/src/storage/ai-cost/groups.ts +248 -0
  773. package/src/storage/ai-cost/in-memory.ts +42 -0
  774. package/src/storage/ai-cost/index.ts +6 -0
  775. package/src/storage/ai-cost/provider.ts +7 -0
  776. package/src/storage/ai-cost/types.ts +76 -14
  777. package/src/storage/ai-cost/validation.ts +147 -17
  778. package/src/storage/ai-limits/enforcement.ts +68 -0
  779. package/src/storage/ai-limits/errors.ts +23 -0
  780. package/src/storage/ai-limits/in-memory.ts +671 -0
  781. package/src/storage/ai-limits/index.ts +31 -0
  782. package/src/storage/ai-limits/period.ts +11 -0
  783. package/src/storage/ai-limits/provider.ts +430 -0
  784. package/src/storage/ai-limits/types.ts +195 -0
  785. package/src/storage/ai-usage/in-memory.ts +13 -0
  786. package/src/storage/ai-usage/record.ts +17 -0
  787. package/src/storage/ai-usage/types.ts +6 -2
  788. package/src/storage/auth/errors.ts +6 -0
  789. package/src/storage/auth/in-memory/auth-storage.ts +69 -0
  790. package/src/storage/auth/in-memory/device-authorizations.ts +145 -0
  791. package/src/storage/auth/in-memory/shared.ts +7 -0
  792. package/src/storage/auth/index.ts +7 -0
  793. package/src/storage/auth/types.ts +73 -0
  794. package/src/storage/executions/in-memory.ts +9 -1
  795. package/src/storage/executions/provider.ts +30 -1
  796. package/src/storage/executions/run-link.ts +45 -6
  797. package/src/storage/executions/validation.ts +82 -7
  798. package/src/storage/in-memory/index.ts +69 -6
  799. package/src/storage/index.ts +102 -1
  800. package/src/storage/objects/execution-limits.ts +283 -0
  801. package/src/storage/objects/guard.ts +55 -0
  802. package/src/storage/objects/in-memory/index.ts +2 -0
  803. package/src/storage/objects/in-memory/keys.ts +46 -0
  804. package/src/storage/objects/in-memory/query.ts +754 -0
  805. package/src/storage/objects/in-memory/read-scope.ts +211 -0
  806. package/src/storage/objects/in-memory/read-source.ts +10 -0
  807. package/src/storage/objects/in-memory/selected-reader.ts +252 -0
  808. package/src/storage/objects/in-memory/storage.ts +589 -0
  809. package/src/storage/objects/index.ts +21 -0
  810. package/src/storage/objects/keys.ts +1 -1
  811. package/src/storage/objects/read-scope.ts +672 -0
  812. package/src/storage/objects/types.ts +123 -19
  813. package/src/storage/operation-scope.ts +16 -0
  814. package/src/storage/share-grants/errors.ts +14 -0
  815. package/src/storage/share-grants/in-memory.ts +107 -0
  816. package/src/storage/share-grants/index.ts +14 -0
  817. package/src/storage/share-grants/provider.ts +11 -0
  818. package/src/storage/share-grants/record.ts +347 -0
  819. package/src/storage/share-grants/types.ts +112 -0
  820. package/src/storage/share-sessions/errors.ts +14 -0
  821. package/src/storage/share-sessions/in-memory.ts +105 -0
  822. package/src/storage/share-sessions/index.ts +11 -0
  823. package/src/storage/share-sessions/provider.ts +9 -0
  824. package/src/storage/share-sessions/record.ts +176 -0
  825. package/src/storage/share-sessions/types.ts +57 -0
  826. package/src/storage/transaction.ts +14 -2
  827. package/src/storage/types.ts +64 -0
  828. package/src/storage/workflow-runs/in-memory.ts +3 -3
  829. package/src/storage/workflow-runs/provider.ts +2 -2
  830. package/src/storage/workflow-runs/types.ts +6 -3
  831. package/src/syncs/execution.ts +25 -5
  832. package/src/syncs/request.ts +5 -0
  833. package/src/testing/agent-execution.ts +40 -28
  834. package/src/testing/agent-storage-contract.ts +249 -28
  835. package/src/testing/ai-cost-storage-contract.ts +96 -8
  836. package/src/testing/ai-limit-storage-contract.ts +1134 -0
  837. package/src/testing/ai-model-call-groups-contract.ts +353 -0
  838. package/src/testing/ai-usage-storage-contract.ts +31 -0
  839. package/src/testing/auth-storage-contract.ts +85 -0
  840. package/src/testing/dataset-sequence-contract.ts +373 -0
  841. package/src/testing/effective-storage-contract.ts +34 -0
  842. package/src/testing/execution-storage-contract.ts +81 -2
  843. package/src/testing/index.ts +26 -0
  844. package/src/testing/lake-merge-storage-contract.ts +3 -0
  845. package/src/testing/lake-storage-contract.ts +58 -0
  846. package/src/testing/object-read-scope-contract.ts +939 -0
  847. package/src/testing/queues-contract.ts +36 -1
  848. package/src/testing/share-grant-storage-contract.ts +325 -0
  849. package/src/testing/share-session-storage-contract.ts +235 -0
  850. package/src/workflows/agent-step-identity.ts +4 -0
  851. package/src/workflows/builders.ts +95 -9
  852. package/src/workflows/execution.ts +55 -16
  853. package/src/workflows/failure.ts +2 -2
  854. package/src/workflows/index.ts +3 -0
  855. package/src/workflows/request.ts +5 -0
  856. package/src/workflows/types.ts +23 -11
  857. package/src/workflows/validation.ts +100 -7
  858. package/dist/chunk-1e8m6yn3.js.map +0 -37
  859. package/dist/chunk-1g8negke.js.map +0 -11
  860. package/dist/chunk-4gz41why.js +0 -72
  861. package/dist/chunk-4gz41why.js.map +0 -11
  862. package/dist/chunk-5sxb1168.js.map +0 -34
  863. package/dist/chunk-6gjqgd3d.js.map +0 -11
  864. package/dist/chunk-819wnjz8.js.map +0 -12
  865. package/dist/chunk-a31h57d5.js.map +0 -13
  866. package/dist/chunk-a44d5zgd.js +0 -556
  867. package/dist/chunk-a44d5zgd.js.map +0 -16
  868. package/dist/chunk-ckxfnx7f.js.map +0 -13
  869. package/dist/chunk-dm72y8wt.js.map +0 -10
  870. package/dist/chunk-drjqm1aa.js.map +0 -15
  871. package/dist/chunk-dy311asx.js.map +0 -14
  872. package/dist/chunk-f6erf2vv.js.map +0 -10
  873. package/dist/chunk-f83ka50g.js.map +0 -23
  874. package/dist/chunk-fe5ev6mr.js +0 -55
  875. package/dist/chunk-fe5ev6mr.js.map +0 -11
  876. package/dist/chunk-h9kxd41f.js.map +0 -11
  877. package/dist/chunk-hceck7dq.js +0 -137
  878. package/dist/chunk-hceck7dq.js.map +0 -10
  879. package/dist/chunk-md8k0r54.js.map +0 -14
  880. package/dist/chunk-n4spznws.js.map +0 -11
  881. package/dist/chunk-nva1xkjz.js.map +0 -46
  882. package/dist/chunk-qewtks41.js.map +0 -11
  883. package/dist/chunk-t0jjkep3.js.map +0 -10
  884. package/dist/chunk-t624af60.js.map +0 -56
  885. package/dist/chunk-t8t39h7v.js.map +0 -10
  886. package/dist/chunk-t9xghkva.js +0 -28
  887. package/dist/chunk-t9xghkva.js.map +0 -10
  888. package/dist/chunk-x2yw73hy.js.map +0 -10
  889. package/dist/chunk-xc7hq65b.js.map +0 -10
  890. package/dist/storage/objects/in-memory.d.ts.map +0 -1
  891. package/src/storage/objects/in-memory.ts +0 -1241
  892. /package/dist/{chunk-zqysyfjt.js.map → chunk-08m3b6w8.js.map} +0 -0
  893. /package/dist/{chunk-z3zp0bj1.js.map → chunk-407j3msh.js.map} +0 -0
  894. /package/dist/{chunk-rhrbz7d4.js.map → chunk-4a849fr1.js.map} +0 -0
  895. /package/dist/{chunk-cy0n5dms.js.map → chunk-4jjp5k14.js.map} +0 -0
  896. /package/dist/{chunk-ezake7g1.js.map → chunk-5ntny1qx.js.map} +0 -0
  897. /package/dist/{chunk-72q2y8hn.js.map → chunk-8tsf6dmc.js.map} +0 -0
  898. /package/dist/{chunk-vybf6pkp.js.map → chunk-dbc80ad7.js.map} +0 -0
  899. /package/dist/{chunk-nkbfrt0c.js.map → chunk-f26bck4t.js.map} +0 -0
  900. /package/dist/{chunk-dsrkgtnh.js.map → chunk-jq43kdvk.js.map} +0 -0
  901. /package/dist/{chunk-wtmzkcht.js.map → chunk-k34z5rvh.js.map} +0 -0
  902. /package/dist/{chunk-htq0qh7z.js.map → chunk-ka3a2ft3.js.map} +0 -0
  903. /package/dist/{chunk-f2rt4vkh.js.map → chunk-n2w475r0.js.map} +0 -0
  904. /package/dist/{chunk-bhxaq2nn.js.map → chunk-qw9gvjv5.js.map} +0 -0
  905. /package/dist/{chunk-dysw7nsm.js.map → chunk-rv2hkwwa.js.map} +0 -0
  906. /package/dist/{chunk-ghteq96b.js.map → chunk-s5y30bc9.js.map} +0 -0
  907. /package/dist/{chunk-xkthy56g.js.map → chunk-w1tvjszy.js.map} +0 -0
  908. /package/dist/{chunk-8b55ygje.js.map → chunk-w3e09qqk.js.map} +0 -0
  909. /package/dist/{chunk-62c7t4jc.js.map → chunk-wdage1eb.js.map} +0 -0
@@ -3,14 +3,24 @@ import {
3
3
  SyncValidationError,
4
4
  createConnectorRuntime,
5
5
  requestSyncRun
6
- } from "./chunk-tg5mee00.js";
6
+ } from "./chunk-wtf06et8.js";
7
+ import {
8
+ aiLimitSubjectsFromAttribution,
9
+ aiUsageLimitExceededError,
10
+ aiUsageLimitUnavailableError,
11
+ applicableAiLimitPolicyStatuses
12
+ } from "./chunk-c15dr03f.js";
13
+ import {
14
+ compileShareAccessPlan
15
+ } from "./chunk-v4en4jc2.js";
7
16
  import {
8
17
  PipelineError,
9
18
  requestPipelineRun
10
- } from "./chunk-8gv5z0zm.js";
19
+ } from "./chunk-w9tg6yyb.js";
11
20
  import {
12
21
  appendTelemetry,
13
22
  createObjectSet,
23
+ getLatestTelemetryPoint,
14
24
  getTelemetryHistoryBatch,
15
25
  listObjects,
16
26
  removeLink1 as removeLink,
@@ -18,80 +28,83 @@ import {
18
28
  upsertLinkBatch1 as upsertLinkBatch,
19
29
  upsertObject1 as upsertObject,
20
30
  upsertObjectBatch1 as upsertObjectBatch
21
- } from "./chunk-5sxb1168.js";
31
+ } from "./chunk-aa2pen2v.js";
22
32
  import {
23
33
  shareOntologyMutationRuntime
24
34
  } from "./chunk-xhy826cz.js";
25
- import {
26
- countObjects,
27
- executeObjectQuery,
28
- executeObjectQueryLinks,
29
- existsObjects,
30
- facetObjects
31
- } from "./chunk-md8k0r54.js";
32
- import {
33
- SIXB_API_ROUTES,
34
- matchesPathPattern,
35
- normalizeRoutePath
36
- } from "./chunk-qewtks41.js";
37
35
  import {
38
36
  registerConnectorConnectionsRuntime
39
37
  } from "./chunk-nf4r78r4.js";
40
38
  import {
41
- isActionDefinition,
39
+ writeDataset
40
+ } from "./chunk-359jm1jw.js";
41
+ import {
42
+ getDatasetPrimaryKeyColumns
43
+ } from "./chunk-n4khvw9n.js";
44
+ import {
45
+ assertAuthorizedObjectReaderBinding,
46
+ canDelegationAccessActionRun,
47
+ getAuthorizedOntologyView,
42
48
  requestAction,
43
49
  requestActionAndWait
44
- } from "./chunk-a44d5zgd.js";
50
+ } from "./chunk-h5vqbfmd.js";
45
51
  import {
46
52
  createPrimitiveExecutionRecord,
47
53
  ensureExecutionRecord,
48
54
  executionRecordInputFromRuntime
49
- } from "./chunk-f6erf2vv.js";
55
+ } from "./chunk-k522z7v6.js";
50
56
  import {
57
+ ObjectNotFoundError,
51
58
  WORKFLOW_RUN_FAILURE_CODES
52
- } from "./chunk-t624af60.js";
59
+ } from "./chunk-sbzzr4kx.js";
60
+ import {
61
+ ShareGrantStorageError
62
+ } from "./chunk-nx7k8tpr.js";
53
63
  import {
54
64
  WorkflowRunError
55
- } from "./chunk-fe5ev6mr.js";
65
+ } from "./chunk-nn0tekr1.js";
56
66
  import {
67
+ ExecutionStorageError
68
+ } from "./chunk-rafagrwr.js";
69
+ import {
70
+ AGENT_REASONING_LEVELS,
57
71
  AgentStorageError
58
- } from "./chunk-1g8negke.js";
72
+ } from "./chunk-p1rzczbt.js";
59
73
  import {
60
- agentServiceAccountId,
61
- ensureAgentExecutionIdentity,
62
- resolveAgentExecutionAuthorization
63
- } from "./chunk-hceck7dq.js";
74
+ RuntimeError
75
+ } from "./chunk-p2vqaxkc.js";
64
76
  import {
65
- ExecutionStorageError
66
- } from "./chunk-h9kxd41f.js";
67
- import {
68
- isObjectRefSchema,
69
- validateSchemaOrRefValue
70
- } from "./chunk-4gz41why.js";
77
+ isModelReasoning
78
+ } from "./chunk-trxxmgnf.js";
71
79
  import {
72
- reportRunFailure
73
- } from "./chunk-dsrkgtnh.js";
80
+ reportRunFailure,
81
+ shareSixbErrorReporter
82
+ } from "./chunk-jq43kdvk.js";
74
83
  import {
75
- AgentDefinitionError,
76
- AgentMessageAdapterError,
77
84
  AgentRequestError,
78
- AgentToolResultValidationError,
79
85
  normalizeAgentContextEntries
80
- } from "./chunk-rdeagz6b.js";
86
+ } from "./chunk-5e3pq99w.js";
81
87
  import {
82
88
  publishAgentRunActivity
83
- } from "./chunk-dm72y8wt.js";
89
+ } from "./chunk-7y0f6rf1.js";
84
90
  import {
85
91
  SYSTEM_PRINCIPAL,
92
+ isActionDefinition,
86
93
  principalsEqual
87
- } from "./chunk-1e8m6yn3.js";
94
+ } from "./chunk-4sm0aznx.js";
88
95
  import {
89
96
  snapshotRequesterGroupIds
90
- } from "./chunk-rhrbz7d4.js";
97
+ } from "./chunk-4a849fr1.js";
98
+ import {
99
+ isObjectRefSchema,
100
+ validateSchemaOrRefValue
101
+ } from "./chunk-2dw777qw.js";
91
102
  import {
92
103
  AuthorizationError,
104
+ agentServiceAccountId,
93
105
  assertAuthorized,
94
106
  assertCanManageConnector,
107
+ assertObjectReadOutputWithinLimit,
95
108
  assertPrivileged,
96
109
  assertProviderAccess,
97
110
  canViewActionRun,
@@ -102,65 +115,125 @@ import {
102
115
  canViewWorkflowIntervention,
103
116
  canViewWorkflowRun,
104
117
  createAgentRuntimeAuthorization,
118
+ getAuthorizationRef,
105
119
  isAllowed,
106
- resolveExecutionScopeAuthorization
107
- } from "./chunk-f83ka50g.js";
108
- import {
109
- assertObjectTypeRegistered,
110
- normalizeSchemaValue,
111
- validateSchemaValue
112
- } from "./chunk-rnshztfq.js";
120
+ isRuntimeAllowed,
121
+ resolveExecutionScopeAuthorization,
122
+ resolveRuntimeAuthorizationForProject
123
+ } from "./chunk-p1x242ad.js";
113
124
  import {
114
- OntologyValidationError
115
- } from "./chunk-dktq02ne.js";
125
+ assertObjectTypeRegistered
126
+ } from "./chunk-h0k55pc7.js";
116
127
  import {
117
- isFileRef,
118
128
  supportsDirectUpload,
119
129
  supportsRangeRead
120
- } from "./chunk-zqysyfjt.js";
130
+ } from "./chunk-08m3b6w8.js";
121
131
  import {
122
132
  captureSixbFailure
123
- } from "./chunk-0172wgm9.js";
133
+ } from "./chunk-2xns679x.js";
124
134
  import {
125
- cloneJsonValue,
126
- getInvalidJsonValueReason,
127
- isPlainRecord,
128
- stableJsonStringify
129
- } from "./chunk-t8t39h7v.js";
135
+ isPlainRecord
136
+ } from "./chunk-n6jxh8sw.js";
137
+
138
+ // src/actions/descriptor.ts
139
+ function snapshotActionDescriptor(action) {
140
+ const params = Object.fromEntries(Object.entries(action.params).map(([id, config]) => [id, structuredClone(config)]));
141
+ return deepFreeze({
142
+ id: action.id,
143
+ ...action.description === undefined ? {} : { description: action.description },
144
+ binding: action.binding.kind === "global" ? { kind: "global" } : { kind: "object", objectTypeId: action.binding.objectType.id },
145
+ params,
146
+ phases: {
147
+ validate: action.phases.validate.length > 0,
148
+ writeback: action.phases.writeback !== undefined,
149
+ edits: action.phases.edits !== undefined,
150
+ effects: action.phases.effects !== undefined
151
+ }
152
+ });
153
+ }
154
+ function deepFreeze(value, seen = new Set) {
155
+ if (typeof value !== "object" || value === null || seen.has(value))
156
+ return value;
157
+ seen.add(value);
158
+ for (const key of Reflect.ownKeys(value)) {
159
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
160
+ if (descriptor && "value" in descriptor)
161
+ deepFreeze(descriptor.value, seen);
162
+ }
163
+ return Object.freeze(value);
164
+ }
130
165
 
131
166
  // src/actions/execution.ts
132
167
  function createActionsRuntime(runtime, execution) {
133
- const canList = (action) => isAllowed(runtime.authorization, { kind: "action.apply", actionId: action.id }) && (action.binding.kind === "global" || isAllowed(runtime.authorization, {
134
- kind: "object.view",
135
- objectTypeId: action.binding.objectType.id
136
- }));
168
+ const projectId = runtime.projectId;
169
+ const runtimeAuthorization = runtime.runtimeAuthorization;
170
+ const objectReader = runtime.objectReader;
171
+ assertAuthorizedObjectReaderBinding({
172
+ reader: objectReader,
173
+ scope: { execution, authorization: runtimeAuthorization }
174
+ });
175
+ const authorization = resolveRuntimeAuthorizationForProject({
176
+ projectId,
177
+ runtimeAuthorization
178
+ });
179
+ const canList = (action) => {
180
+ if (authorization.type === "denied")
181
+ return false;
182
+ if (authorization.type === "delegated") {
183
+ const binding = action.binding;
184
+ return binding.kind === "object" && authorization.actionApply.some((target) => target.actionId === action.id && target.subject.objectTypeId === binding.objectType.id) && getAuthorizedOntologyView(objectReader).getObjectTypeById(binding.objectType.id) !== null;
185
+ }
186
+ if (authorization.type === "unrestricted")
187
+ return true;
188
+ return isAllowed(authorization.context, { kind: "action.apply", actionId: action.id }) && (action.binding.kind === "global" || isAllowed(authorization.context, {
189
+ kind: "object.view",
190
+ objectTypeId: action.binding.objectType.id
191
+ }));
192
+ };
193
+ const release = (value) => {
194
+ if (authorization.type === "delegated") {
195
+ assertObjectReadOutputWithinLimit(value, authorization.objectRead.limits);
196
+ }
197
+ return value;
198
+ };
199
+ const describeAll = (actions) => release(actions.filter(canList).map(snapshotActionDescriptor));
137
200
  return {
138
- list: () => runtime.actionRegistry.list().filter(canList),
201
+ list: () => describeAll(runtime.actionRegistry.list()),
139
202
  getById: (actionId) => {
140
203
  const action = runtime.actionRegistry.getById(actionId);
141
- return action && canList(action) ? action : null;
204
+ return release(action && canList(action) ? snapshotActionDescriptor(action) : null);
142
205
  },
143
- listGlobal: () => runtime.actionRegistry.listGlobal().filter(canList),
144
- listForType: (objectType) => runtime.actionRegistry.listForType(objectType).filter(canList),
206
+ listGlobal: () => describeAll(runtime.actionRegistry.listGlobal()),
207
+ listForType: (objectType) => describeAll(runtime.actionRegistry.listForType(objectType).filter((action) => authorization.type !== "delegated" || action.binding.kind === "object" && action.binding.objectType.id === objectType.id)),
145
208
  request: (input) => requestAction(runtime, execution, input),
146
209
  requestAndWait: (input) => requestActionAndWait(runtime, execution, input),
147
210
  runs: {
148
211
  getById: async (runId) => {
212
+ if (authorization.type === "denied" || authorization.type === "delegated" && (!authorization.delegation || authorization.actionApply.length === 0))
213
+ return null;
149
214
  const run = await runtime.storage.actionRuns?.getById({
150
- projectId: runtime.projectId,
215
+ projectId,
151
216
  id: runId
152
217
  }) ?? null;
153
- return run && canViewActionRun(runtime.authorization, run) ? run : null;
218
+ return run && (authorization.type === "unrestricted" || authorization.type === "principal" && canViewActionRun(authorization.context, run) || authorization.type === "delegated" && await canDelegationAccessActionRun({
219
+ storage: runtime.storage,
220
+ projectId,
221
+ authority: authorization,
222
+ run
223
+ })) ? release(run) : null;
154
224
  },
155
225
  list: (input = {}) => {
226
+ if (authorization.type === "denied" || authorization.type === "delegated") {
227
+ return Promise.resolve({ runs: [], hasMore: false, total: 0 });
228
+ }
156
229
  const storage = runtime.storage.actionRuns;
157
230
  if (!storage)
158
231
  return Promise.resolve({ runs: [], hasMore: false, total: 0 });
159
232
  return storage.list({
160
- projectId: runtime.projectId,
161
233
  ...input,
162
- actionIds: runtime.authorization ? [...runtime.authorization.grants["apply:action"]] : undefined,
163
- objectTypeIds: runtime.authorization ? [...runtime.authorization.grants["view:object"]] : undefined
234
+ projectId,
235
+ actionIds: authorization.type === "principal" ? [...authorization.context.grants["apply:action"]] : undefined,
236
+ objectTypeIds: authorization.type === "principal" ? [...authorization.context.grants["view:object"]] : undefined
164
237
  });
165
238
  }
166
239
  }
@@ -197,13 +270,20 @@ async function resolveExecutionUsage(input) {
197
270
  }
198
271
 
199
272
  // src/agents/ids.ts
200
- import { randomUUID } from "crypto";
273
+ import { createHash, randomUUID } from "crypto";
201
274
  function createAgentThreadId() {
202
275
  return `agt_thr_${randomUUID()}`;
203
276
  }
204
277
  function createAgentRunId() {
205
278
  return `agt_run_${randomUUID()}`;
206
279
  }
280
+ function createSubagentRunId(parentRunId, spawnKey) {
281
+ const digest = createHash("sha256").update(parentRunId).update("\x00").update(spawnKey).digest("hex");
282
+ return `agt_run_child_${digest}`;
283
+ }
284
+ function createSubagentExecutionId(runId) {
285
+ return `exec_${runId}`;
286
+ }
207
287
  function createAgentMessageId() {
208
288
  return `agt_msg_${randomUUID()}`;
209
289
  }
@@ -229,9 +309,7 @@ async function resolveAgentContextParts(runtime, input) {
229
309
  } catch {
230
310
  invalidContext(`context references an unknown object type '${objectTypeId}'`);
231
311
  }
232
- assertAuthorized(runtime, { kind: "object.view", objectTypeId });
233
- const object = await runtime.storage.objects.getByPrimaryId({
234
- projectId: runtime.projectId,
312
+ const object = await runtime.objectReader.getByPrimaryId({
235
313
  objectTypeId,
236
314
  primaryId
237
315
  });
@@ -249,6 +327,9 @@ function invalidContext(message) {
249
327
  function agentRunQueueJobId(runId) {
250
328
  return `agt_job_${runId}`;
251
329
  }
330
+ function subagentRunQueueJobId(runId) {
331
+ return `agt_child_job_${runId}`;
332
+ }
252
333
  function workflowAgentNodeQueueJobId(nodeRunId) {
253
334
  return `wfa_job_${nodeRunId}`;
254
335
  }
@@ -259,11 +340,12 @@ async function dispatchQueuedAgentRuns(input) {
259
340
  ids: [...new Set(input.runIds)].slice(0, limit)
260
341
  }) : (await input.storage.runs.list({
261
342
  projectId: input.projectId,
343
+ kinds: ["conversation"],
262
344
  statuses: ["queued"],
263
345
  order: "asc",
264
346
  limit
265
347
  })).runs;
266
- const queued = runs.filter((run) => run.status === "queued");
348
+ const queued = runs.filter((run) => run.kind === "conversation" && run.status === "queued");
267
349
  if (queued.length === 0) {
268
350
  return { scanned: 0, dispatched: [], failures: [] };
269
351
  }
@@ -293,6 +375,47 @@ async function dispatchQueuedAgentRuns(input) {
293
375
  };
294
376
  }
295
377
  }
378
+ async function dispatchQueuedSubagentRuns(input) {
379
+ const limit = normalizeLimit(input.limit);
380
+ const runs = input.runIds ? await input.storage.runs.getByIds({
381
+ projectId: input.projectId,
382
+ ids: [...new Set(input.runIds)].slice(0, limit)
383
+ }) : (await input.storage.runs.list({
384
+ projectId: input.projectId,
385
+ kinds: ["subagent"],
386
+ statuses: ["queued"],
387
+ order: "asc",
388
+ limit
389
+ })).runs;
390
+ const queued = runs.filter((run) => run.kind === "subagent" && run.status === "queued");
391
+ if (queued.length === 0)
392
+ return { scanned: 0, dispatched: [], failures: [] };
393
+ try {
394
+ const jobs = await input.queue.enqueue({
395
+ projectId: input.projectId,
396
+ jobs: queued.map((run) => ({
397
+ id: subagentRunQueueJobId(run.id),
398
+ type: "agent.subagent-run.requested",
399
+ payload: { runId: run.id }
400
+ }))
401
+ });
402
+ const jobsById = new Set(jobs.map((job) => job.id));
403
+ const dispatched = queued.map((run) => {
404
+ const jobId = subagentRunQueueJobId(run.id);
405
+ if (!jobsById.has(jobId)) {
406
+ throw new Error(`[Sixb] Subagent queue did not return job '${jobId}'.`);
407
+ }
408
+ return { runId: run.id, jobId };
409
+ });
410
+ return { scanned: queued.length, dispatched, failures: [] };
411
+ } catch (error) {
412
+ return {
413
+ scanned: queued.length,
414
+ dispatched: [],
415
+ failures: queued.map((run) => ({ runId: run.id, error }))
416
+ };
417
+ }
418
+ }
296
419
  function normalizeLimit(value) {
297
420
  if (value === undefined)
298
421
  return 100;
@@ -302,16 +425,42 @@ function normalizeLimit(value) {
302
425
  return Math.floor(value);
303
426
  }
304
427
 
428
+ // src/agents/retired-config.ts
429
+ function assertNoAgentDefinitions(input) {
430
+ if ("agents" in input) {
431
+ throw new RuntimeError("[Sixb] Agent definitions are no longer supported. Configure 'models' and 'tools' on createSixb() instead.");
432
+ }
433
+ }
434
+ function assertNoAgentSelector(input) {
435
+ if ("agentId" in input || "agentIds" in input) {
436
+ throw new AgentRequestError("agent_selector_removed", "[Sixb] There is one project Agent. Remove the agentId selector and use sixb.agent.");
437
+ }
438
+ }
439
+
305
440
  // src/agents/request.ts
306
- async function requestAgentRun(runtime, execution, security, agent, input) {
307
- assertAuthorized(runtime, { kind: "agent.run", agentId: agent.id });
441
+ async function requestAgentRun(runtime, execution, models, input) {
442
+ const authority = resolveExecutionScopeAuthorization(runtime.projectId, {
443
+ execution,
444
+ authorization: runtime.runtimeAuthorization
445
+ });
446
+ assertNoAgentSelector(input);
447
+ assertAuthorized(runtime, { kind: "agent.run" });
448
+ assertRequestAuthorityCanRunAgent(runtime);
449
+ const spec = resolveConversationRunSpec({ models, input });
308
450
  const contextParts = await resolveAgentContextParts(runtime, input.context);
309
451
  const agents = requireAgentStorage(runtime);
310
452
  const projectId = runtime.projectId;
311
- const principal = runtime.authorization?.principal ?? input.principal ?? SYSTEM_PRINCIPAL;
453
+ const principal = authority.type === "principal" ? authority.context.principal : input.principal ?? SYSTEM_PRINCIPAL;
454
+ const runId = createAgentRunId();
455
+ const durableExecution = await prepareDurableAgentExecution(runtime, execution, runId);
456
+ const requesterGroupIds = durableExecution.requestedBy ? await snapshotRequesterGroupIds({
457
+ auth: runtime.storage.auth,
458
+ projectId,
459
+ principal: durableExecution.requestedBy
460
+ }) : [];
461
+ await assertAiLimitPreflight(runtime, durableExecution, requesterGroupIds);
312
462
  const { thread, createdThread } = await resolveThread(agents, {
313
463
  projectId,
314
- agentId: agent.id,
315
464
  threadId: input.threadId,
316
465
  title: input.title,
317
466
  principal
@@ -319,13 +468,6 @@ async function requestAgentRun(runtime, execution, security, agent, input) {
319
468
  if (thread.activeRunId !== null) {
320
469
  throw new AgentRequestError("active_run_exists", `[Sixb] Agent thread '${thread.id}' already has an active run '${thread.activeRunId}'.`);
321
470
  }
322
- const runId = createAgentRunId();
323
- const durableExecution = await prepareDurableAgentExecution(runtime, execution, security, agent, runId);
324
- const requesterGroupIds = durableExecution.requestedBy ? await snapshotRequesterGroupIds({
325
- auth: runtime.storage.auth,
326
- projectId,
327
- principal: durableExecution.requestedBy
328
- }) : [];
329
471
  const triggerMessageId = input.messageId ?? createAgentMessageId();
330
472
  let run;
331
473
  try {
@@ -353,8 +495,8 @@ async function requestAgentRun(runtime, execution, security, agent, input) {
353
495
  projectId,
354
496
  executionId: durableExecution.id,
355
497
  threadId: thread.id,
356
- agentId: agent.id,
357
498
  triggerMessageId,
499
+ spec,
358
500
  requesterGroupIds
359
501
  });
360
502
  });
@@ -372,22 +514,32 @@ async function requestAgentRun(runtime, execution, security, agent, input) {
372
514
  createdThread
373
515
  };
374
516
  }
375
- async function retryAgentRun(runtime, execution, security, agent, failedRun) {
376
- assertAuthorized(runtime, { kind: "agent.run", agentId: agent.id });
377
- if (failedRun.agentId !== agent.id) {
378
- throw new AgentRequestError("agent_not_found", `[Sixb] Agent run '${failedRun.id}' does not belong to agent '${agent.id}'.`);
379
- }
517
+ async function retryAgentRun(runtime, execution, models, failedRun) {
518
+ resolveExecutionScopeAuthorization(runtime.projectId, {
519
+ execution,
520
+ authorization: runtime.runtimeAuthorization
521
+ });
522
+ assertAuthorized(runtime, { kind: "agent.run" });
523
+ assertRequestAuthorityCanRunAgent(runtime);
380
524
  if (failedRun.status !== "failed") {
381
525
  throw new AgentRequestError("run_not_retryable", `[Sixb] Only failed Agent runs can be retried.`);
382
526
  }
383
527
  const agents = requireAgentStorage(runtime);
528
+ const thread = await agents.threads.getById({
529
+ projectId: runtime.projectId,
530
+ id: failedRun.threadId
531
+ });
532
+ if (!thread) {
533
+ throw new AgentRequestError("thread_not_found", `[Sixb] Agent thread '${failedRun.threadId}' was not found.`);
534
+ }
384
535
  const runId = createAgentRunId();
385
- const durableExecution = await prepareDurableAgentExecution(runtime, execution, security, agent, runId);
536
+ const durableExecution = await prepareDurableAgentExecution(runtime, execution, runId);
386
537
  const requesterGroupIds = durableExecution.requestedBy ? await snapshotRequesterGroupIds({
387
538
  auth: runtime.storage.auth,
388
539
  projectId: runtime.projectId,
389
540
  principal: durableExecution.requestedBy
390
541
  }) : [];
542
+ await assertAiLimitPreflight(runtime, durableExecution, requesterGroupIds);
391
543
  const run = await runtime.storage.transaction(async (tx) => {
392
544
  const agents2 = tx.agents;
393
545
  if (!agents2) {
@@ -404,8 +556,11 @@ async function retryAgentRun(runtime, execution, security, agent, failedRun) {
404
556
  projectId: runtime.projectId,
405
557
  executionId: durableExecution.id,
406
558
  threadId: failedRun.threadId,
407
- agentId: agent.id,
408
559
  triggerMessageId: failedRun.triggerMessageId,
560
+ spec: failedRun.spec ?? resolveConversationRunSpec({
561
+ models,
562
+ input: {}
563
+ }),
409
564
  requesterGroupIds
410
565
  });
411
566
  });
@@ -413,31 +568,61 @@ async function retryAgentRun(runtime, execution, security, agent, failedRun) {
413
568
  const jobId = await dispatchAgentRun(runtime, agents, runId);
414
569
  return { run, ...jobId ? { jobId } : {}, createdThread: false };
415
570
  }
416
- async function prepareDurableAgentExecution(runtime, execution, security, agent, runId) {
417
- const identity = await ensureAgentExecutionIdentity({
418
- auth: runtime.storage.auth,
419
- projectId: runtime.projectId,
420
- agent
421
- });
422
- const resolved = await resolveAgentExecutionAuthorization({
423
- auth: runtime.storage.auth,
424
- projectId: runtime.projectId,
425
- agentId: agent.id,
426
- authorizationRef: { type: "principal", principal: identity.principal },
427
- security
571
+ async function assertAiLimitPreflight(runtime, execution, requesterGroupIds) {
572
+ const limits = runtime.storage.aiLimits;
573
+ if (!limits)
574
+ throw aiUsageLimitUnavailableError(["limitStorageUnavailable"]);
575
+ const subjects = aiLimitSubjectsFromAttribution(execution.requestedBy, requesterGroupIds);
576
+ let applicable;
577
+ try {
578
+ applicable = applicableAiLimitPolicyStatuses(await limits.listPolicyStatuses({ projectId: runtime.projectId }), subjects);
579
+ } catch {
580
+ throw aiUsageLimitUnavailableError(["limitStorageUnavailable"]);
581
+ }
582
+ const unavailable = applicable.filter((status) => status.accountingStatus === "unavailable");
583
+ if (unavailable.length > 0) {
584
+ throw aiUsageLimitUnavailableError(["incompleteAccounting"]);
585
+ }
586
+ const exhausted = applicable.filter((status) => status.exhausted);
587
+ if (exhausted.length > 0) {
588
+ const resetAt = new Date(Math.min(...exhausted.map((status) => status.period.resetAt.getTime())));
589
+ throw aiUsageLimitExceededError(resetAt);
590
+ }
591
+ }
592
+ function resolveConversationRunSpec(input) {
593
+ if (!input.models) {
594
+ throw new AgentRequestError("model_not_found", "[Sixb] Configure models.language before starting the Agent.");
595
+ }
596
+ const selected = input.input.model ?? input.models.default;
597
+ const model = input.models.getByRef(selected);
598
+ if (model === null) {
599
+ throw new AgentRequestError("model_not_found", `[Sixb] Language model '${selected.provider}/${selected.modelId}' is not in the project model catalog.`);
600
+ }
601
+ const reasoning = input.input.reasoning;
602
+ if (reasoning !== undefined && !isModelReasoning(reasoning)) {
603
+ throw new AgentRequestError("invalid_model_selection", `[Sixb] Agent reasoning must be one of: ${AGENT_REASONING_LEVELS.join(", ")}, or a nonnegative budgetTokens object.`);
604
+ }
605
+ return Object.freeze({
606
+ model: Object.freeze({ provider: selected.provider, modelId: selected.modelId }),
607
+ ...reasoning === undefined ? {} : { reasoning }
428
608
  });
609
+ }
610
+ async function prepareDurableAgentExecution(runtime, execution, runId) {
429
611
  const parent = await ensureExecutionRecord(runtime.storage.executions, executionRecordInputFromRuntime({
430
612
  execution,
431
613
  runtimeAuthorization: runtime.runtimeAuthorization
432
614
  }));
433
- return createAgentExecutionRecord({
615
+ return createInheritedAgentExecutionRecord({
434
616
  id: `exec_${randomUUID2()}`,
435
617
  parent,
436
- agentId: agent.id,
437
- runId,
438
- principal: resolved.identity.principal
618
+ runId
439
619
  });
440
620
  }
621
+ function assertRequestAuthorityCanRunAgent(runtime) {
622
+ if (!canInheritAgentRequestAuthorization(runtime.runtimeAuthorization)) {
623
+ throw new AgentRequestError("authority_not_inheritable", "[Sixb] The Agent requires an authenticated user request or disabled authorization.");
624
+ }
625
+ }
441
626
  async function dispatchAgentRun(runtime, agents, runId) {
442
627
  try {
443
628
  const dispatch = await dispatchQueuedAgentRuns({
@@ -470,16 +655,12 @@ async function resolveThread(agents, params) {
470
655
  id: params.threadId
471
656
  });
472
657
  if (existing) {
473
- if (existing.agentId !== params.agentId) {
474
- throw new AgentRequestError("thread_agent_mismatch", `[Sixb] Agent thread '${existing.id}' belongs to agent '${existing.agentId}', not '${params.agentId}'.`);
475
- }
476
658
  return { thread: existing, createdThread: false };
477
659
  }
478
660
  }
479
661
  const thread = await agents.threads.create({
480
662
  id: params.threadId ?? createAgentThreadId(),
481
663
  projectId: params.projectId,
482
- agentId: params.agentId,
483
664
  ownerPrincipal: params.principal,
484
665
  ...params.title === undefined ? {} : { title: params.title }
485
666
  });
@@ -494,44 +675,56 @@ function requireAgentStorage(runtime) {
494
675
  }
495
676
 
496
677
  // src/agents/execution.ts
497
- function createAgentsRuntime(runtime, execution, source, security) {
498
- const principal = runtime.authorization?.principal ?? SYSTEM_PRINCIPAL;
499
- const allowed = (agentId) => isAllowed(runtime.authorization, { kind: "agent.run", agentId });
500
- const getThread = async (threadId) => {
678
+ function createAgentRuntime(runtime, execution, models) {
679
+ const authority = resolveRuntimeAuthorizationForProject(runtime);
680
+ const principal = authority.type === "principal" ? authority.context.principal : SYSTEM_PRINCIPAL;
681
+ const allowed = () => isRuntimeAllowed(runtime, { kind: "agent.run" });
682
+ const getVisibleThreadRecord = async (threadId) => {
683
+ if (authority.type === "denied" || authority.type === "delegated")
684
+ return null;
501
685
  const thread = await runtime.storage.agents?.threads.getById({
502
686
  projectId: runtime.projectId,
503
687
  id: threadId
504
688
  }) ?? null;
505
- if (!thread || !allowed(thread.agentId))
689
+ if (!thread || !allowed())
506
690
  return null;
507
- return runtime.authorization && !principalsEqual(principal, thread.ownerPrincipal) ? null : thread;
691
+ return authority.type === "principal" && !principalsEqual(principal, thread.ownerPrincipal) ? null : thread;
508
692
  };
509
- const getAgent = (agentId) => {
510
- const agent = source.getById(agentId);
511
- return agent && allowed(agentId) ? agent : null;
693
+ const getAgent = () => {
694
+ if (authority.type === "denied" || authority.type === "delegated")
695
+ return null;
696
+ const model = models?.language.default;
697
+ if (!model || !allowed())
698
+ return null;
699
+ return {
700
+ name: "Sixb",
701
+ model: { provider: model.provider, modelId: model.modelId }
702
+ };
512
703
  };
513
704
  const getVisibleRunRecord = async (runId) => {
705
+ if (authority.type === "denied" || authority.type === "delegated")
706
+ return null;
514
707
  const run = await runtime.storage.agents?.runs.getById({
515
708
  projectId: runtime.projectId,
516
709
  id: runId
517
710
  }) ?? null;
518
- if (!run)
711
+ if (!run || run.kind !== "conversation")
519
712
  return null;
520
- const thread = await getThread(run.threadId);
521
- return thread?.agentId === run.agentId ? run : null;
713
+ const thread = await getVisibleThreadRecord(run.threadId);
714
+ return thread ? run : null;
522
715
  };
523
716
  const getRun = async (runId) => {
524
717
  const run = await getVisibleRunRecord(runId);
525
718
  return run ? attachRunView(runtime, run) : null;
526
719
  };
527
720
  return {
528
- list: () => source.list().filter((agent) => allowed(agent.id)),
529
- getById: getAgent,
721
+ get: getAgent,
530
722
  threads: {
531
723
  create: async (input) => {
532
- const agent = getAgent(input.agentId);
724
+ assertNoAgentSelector(input);
725
+ const agent = getAgent();
533
726
  if (!agent) {
534
- throw new AgentRequestError("agent_not_found", `[Sixb] Unknown agent '${input.agentId}'.`);
727
+ throw new AgentRequestError("agent_not_found", "[Sixb] The project Agent is unavailable.");
535
728
  }
536
729
  const storage = runtime.storage.agents;
537
730
  if (!storage) {
@@ -540,35 +733,38 @@ function createAgentsRuntime(runtime, execution, source, security) {
540
733
  return storage.threads.create({
541
734
  id: input.id ?? createAgentThreadId(),
542
735
  projectId: runtime.projectId,
543
- agentId: agent.id,
544
736
  ownerPrincipal: principal,
545
737
  ...input.title === undefined ? {} : { title: input.title }
546
738
  });
547
739
  },
548
- getById: getThread,
549
- list: (input = {}) => {
740
+ getById: getVisibleThreadRecord,
741
+ list: async (input = {}) => {
742
+ assertNoAgentSelector(input);
743
+ if (authority.type === "denied" || authority.type === "delegated") {
744
+ return { threads: [], hasMore: false, total: 0 };
745
+ }
550
746
  const storage = runtime.storage.agents;
551
- if (!storage)
552
- return Promise.resolve({ threads: [], hasMore: false, total: 0 });
747
+ if (!storage || !allowed())
748
+ return { threads: [], hasMore: false, total: 0 };
553
749
  return storage.threads.list({
554
- projectId: runtime.projectId,
555
750
  ...input,
556
- agentIds: runtime.authorization ? [...runtime.authorization.grants["run:agent"]] : undefined,
557
- ownerPrincipal: runtime.authorization ? principal : undefined
751
+ projectId: runtime.projectId,
752
+ ownerPrincipal: authority.type === "principal" ? principal : undefined
558
753
  });
559
754
  }
560
755
  },
561
756
  runs: {
562
757
  request: async (input) => {
563
- const agent = source.getById(input.agentId);
758
+ assertNoAgentSelector(input);
759
+ const agent = getAgent();
564
760
  if (!agent) {
565
- throw new AgentRequestError("agent_not_found", `[Sixb] Unknown agent '${input.agentId}'.`);
761
+ throw new AgentRequestError("agent_not_found", "[Sixb] The project Agent is unavailable.");
566
762
  }
567
- assertAuthorized(runtime, { kind: "agent.run", agentId: agent.id });
568
- if (input.threadId && !await getThread(input.threadId)) {
763
+ assertAuthorized(runtime, { kind: "agent.run" });
764
+ if (input.threadId && !await getVisibleThreadRecord(input.threadId)) {
569
765
  throw new AgentRequestError("thread_not_found", `[Sixb] Agent thread '${input.threadId}' not found.`);
570
766
  }
571
- const result = await requestAgentRun(runtime, execution, security, agent, {
767
+ const result = await requestAgentRun(runtime, execution, models?.language, {
572
768
  ...input,
573
769
  principal
574
770
  });
@@ -579,26 +775,27 @@ function createAgentsRuntime(runtime, execution, source, security) {
579
775
  if (!failedRun) {
580
776
  throw new AgentRequestError("run_not_found", `[Sixb] Agent run '${runId}' was not found.`);
581
777
  }
582
- const agent = getAgent(failedRun.agentId);
778
+ const agent = getAgent();
583
779
  if (!agent) {
584
- throw new AgentRequestError("agent_not_found", `[Sixb] Unknown agent '${failedRun.agentId}'.`);
780
+ throw new AgentRequestError("agent_not_found", "[Sixb] The project Agent is unavailable.");
585
781
  }
586
- const result = await retryAgentRun(runtime, execution, security, agent, failedRun);
782
+ const result = await retryAgentRun(runtime, execution, models?.language, failedRun);
587
783
  return { ...result, run: await attachRunView(runtime, result.run) };
588
784
  },
589
785
  getById: getRun,
590
786
  listForThread: async (threadId, input = {}) => {
787
+ assertNoAgentSelector(input);
591
788
  const storage = runtime.storage.agents;
592
- if (!storage || !await getThread(threadId))
789
+ if (!storage || !await getVisibleThreadRecord(threadId))
593
790
  return null;
594
791
  const result = await storage.runs.list({
595
- projectId: runtime.projectId,
596
792
  ...input,
793
+ projectId: runtime.projectId,
597
794
  threadId
598
795
  });
599
796
  return {
600
797
  ...result,
601
- runs: await attachRunViews(runtime, result.runs)
798
+ runs: await attachRunViews(runtime, result.runs.filter((run) => run.kind === "conversation"))
602
799
  };
603
800
  }
604
801
  }
@@ -644,6 +841,106 @@ async function attachRunViews(runtime, runs) {
644
841
  });
645
842
  }
646
843
 
844
+ // src/ai-usage/execution.ts
845
+ import { randomUUID as randomUUID3 } from "crypto";
846
+ function createAiUsageRuntime(runtime, security) {
847
+ const assertObservable = () => assertAuthorized(runtime, { kind: "aiUsage.observe" });
848
+ const assertManageable = () => assertAuthorized(runtime, { kind: "aiUsage.manage" });
849
+ const assertPolicyReadable = () => {
850
+ if (!isRuntimeAllowed(runtime, { kind: "aiUsage.observe" }) && !isRuntimeAllowed(runtime, { kind: "aiUsage.manage" })) {
851
+ assertObservable();
852
+ }
853
+ };
854
+ const requireCosts = () => {
855
+ if (!runtime.storage.aiCosts) {
856
+ throw new Error("[Sixb] AI cost storage is not configured.");
857
+ }
858
+ return runtime.storage.aiCosts;
859
+ };
860
+ const requireLimits = () => {
861
+ if (!runtime.storage.aiLimits) {
862
+ throw new Error("[Sixb] AI limit storage is not configured.");
863
+ }
864
+ return runtime.storage.aiLimits;
865
+ };
866
+ return {
867
+ accountingConfigured: runtime.storage.aiCosts !== undefined,
868
+ limitsConfigured: runtime.storage.aiLimits !== undefined,
869
+ assertObservable,
870
+ assertManageable,
871
+ canManageLimits: () => isRuntimeAllowed(runtime, { kind: "aiUsage.manage" }),
872
+ queryOverview: (input) => {
873
+ assertObservable();
874
+ return requireCosts().queryProjectOverview({ ...input, projectId: runtime.projectId });
875
+ },
876
+ listModelCalls: (input) => {
877
+ assertObservable();
878
+ return requireCosts().listModelCalls({ ...input, projectId: runtime.projectId });
879
+ },
880
+ listModelCallGroups: (input) => {
881
+ assertObservable();
882
+ return requireCosts().listModelCallGroups({ ...input, projectId: runtime.projectId });
883
+ },
884
+ listLimitPolicies: (input = {}) => {
885
+ assertPolicyReadable();
886
+ return requireLimits().listPolicies({ ...input, projectId: runtime.projectId });
887
+ },
888
+ listLimitStatuses: (input = {}) => {
889
+ assertObservable();
890
+ return requireLimits().listPolicyStatuses({
891
+ ...input.includeDisabled === undefined ? {} : { includeDisabled: input.includeDisabled },
892
+ projectId: runtime.projectId,
893
+ existingGroupIds: security.listGroups().map((group) => group.id)
894
+ });
895
+ },
896
+ listLimitSubjectOptions: async () => {
897
+ assertManageable();
898
+ const groups = security.listGroups().map((group) => ({
899
+ id: group.id,
900
+ ...group.label === undefined ? {} : { label: group.label },
901
+ ...group.description === undefined ? {} : { description: group.description }
902
+ }));
903
+ const auth = runtime.storage.auth;
904
+ if (!auth)
905
+ return { groups, users: [], serviceAccounts: [] };
906
+ const [users, serviceAccounts] = await Promise.all([
907
+ auth.users.list({ projectId: runtime.projectId, order: "asc" }),
908
+ auth.serviceAccounts.list({ projectId: runtime.projectId, order: "asc" })
909
+ ]);
910
+ return {
911
+ groups,
912
+ users: users.users.map((user) => ({
913
+ id: user.id,
914
+ email: user.email,
915
+ ...user.displayName === undefined ? {} : { displayName: user.displayName },
916
+ status: user.status
917
+ })),
918
+ serviceAccounts: serviceAccounts.serviceAccounts.map((serviceAccount) => ({
919
+ id: serviceAccount.id,
920
+ name: serviceAccount.name,
921
+ ...serviceAccount.description === undefined ? {} : { description: serviceAccount.description },
922
+ status: serviceAccount.status
923
+ }))
924
+ };
925
+ },
926
+ createLimitPolicy: (input) => {
927
+ assertManageable();
928
+ return requireLimits().createPolicy({
929
+ ...input,
930
+ id: input.id ?? `ailim_${randomUUID3()}`,
931
+ projectId: runtime.projectId
932
+ });
933
+ },
934
+ updateLimitPolicy: (input) => {
935
+ assertManageable();
936
+ return requireLimits().updatePolicy({ ...input, projectId: runtime.projectId });
937
+ },
938
+ deleteLimitPolicy: (id) => {
939
+ assertManageable();
940
+ return requireLimits().deletePolicy({ id, projectId: runtime.projectId });
941
+ }
942
+ };
943
+ }
647
944
  // src/blob-storage/execution.ts
648
945
  function createBlobsRuntime(runtime, execution, blobStorage) {
649
946
  const assertAccess = () => assertProviderAccess(runtime, execution, "blobs.access");
@@ -728,21 +1025,88 @@ function commandContext(runtime, execution, connectorId) {
728
1025
  }
729
1026
 
730
1027
  // src/datasets/execution.ts
731
- function createDatasetsRuntime(runtime, source) {
732
- const allowed = (datasetId) => isAllowed(runtime.authorization, { kind: "dataset.view", datasetId });
1028
+ function createDatasetsRuntime(runtime, execution, source, lakeStorage, blobStorage) {
1029
+ const authority = resolveRuntimeAuthorizationForProject(runtime);
1030
+ const allowed = (datasetId) => isRuntimeAllowed(runtime, { kind: "dataset.view", datasetId });
733
1031
  return {
734
- list: () => source.list().filter((dataset) => allowed(dataset.id)),
1032
+ list: () => authority.type === "denied" || authority.type === "delegated" ? [] : source.list().filter((dataset) => allowed(dataset.id)),
735
1033
  getById: (datasetId) => {
1034
+ if (authority.type === "denied" || authority.type === "delegated")
1035
+ return null;
736
1036
  const dataset = source.getById(datasetId);
737
1037
  return dataset && allowed(datasetId) ? dataset : null;
1038
+ },
1039
+ async ingest(dataset, input) {
1040
+ assertPrivileged(runtime, "datasets.ingest");
1041
+ const registered = source.getById(dataset.id);
1042
+ if (!registered)
1043
+ throw new Error(`[Sixb] Dataset '${dataset.id}' is not registered.`);
1044
+ if (getDatasetPrimaryKeyColumns(registered) === null) {
1045
+ throw new Error(`[Sixb] Dataset '${dataset.id}' must define a primaryKey before ingestion.`);
1046
+ }
1047
+ if (typeof lakeStorage.beginMerge !== "function") {
1048
+ throw new Error("[Sixb] Dataset ingestion requires a lake provider with merge support.");
1049
+ }
1050
+ const producer = { kind: "ingest", id: execution.id };
1051
+ const result = await writeDataset({
1052
+ lakeStorage,
1053
+ blobStorage,
1054
+ dataset: registered,
1055
+ mode: "merge",
1056
+ signal: input.signal ?? new AbortController().signal,
1057
+ producer,
1058
+ readValues: async () => async function* () {
1059
+ for await (const value of input.changes)
1060
+ yield { value };
1061
+ }()
1062
+ });
1063
+ if (result.outcome === "created") {
1064
+ await runtime.events.emit({
1065
+ events: [
1066
+ {
1067
+ type: "dataset.version.committed",
1068
+ payload: {
1069
+ datasetId: registered.id,
1070
+ versionId: result.version.versionId,
1071
+ createdAt: result.version.createdAt.toISOString(),
1072
+ producer
1073
+ }
1074
+ }
1075
+ ],
1076
+ correlationId: execution.correlationId
1077
+ }, { source: "SixbDatasets" });
1078
+ }
1079
+ return result;
738
1080
  }
739
1081
  };
740
1082
  }
741
1083
 
742
1084
  // src/events/execution.ts
743
1085
  function createEventsRuntime(runtime) {
1086
+ const authority = resolveRuntimeAuthorizationForProject(runtime);
1087
+ const visibleEvents = (events) => {
1088
+ switch (authority.type) {
1089
+ case "denied":
1090
+ case "delegated":
1091
+ return [];
1092
+ case "principal":
1093
+ return events.filter((event) => canViewEvent(authority.context, event));
1094
+ case "unrestricted":
1095
+ return [...events];
1096
+ }
1097
+ };
744
1098
  return {
745
- canRead: (event) => canViewEvent(runtime.authorization, event),
1099
+ canRead: (event) => {
1100
+ switch (authority.type) {
1101
+ case "denied":
1102
+ case "delegated":
1103
+ return false;
1104
+ case "principal":
1105
+ return canViewEvent(authority.context, event);
1106
+ case "unrestricted":
1107
+ return true;
1108
+ }
1109
+ },
746
1110
  append: (input) => {
747
1111
  assertPrivileged(runtime, "events.append");
748
1112
  return runtime.events.append(input);
@@ -752,15 +1116,42 @@ function createEventsRuntime(runtime) {
752
1116
  return runtime.events.emit(input, options);
753
1117
  },
754
1118
  read: async (input) => {
1119
+ switch (authority.type) {
1120
+ case "denied":
1121
+ case "delegated":
1122
+ return [];
1123
+ case "principal":
1124
+ case "unrestricted":
1125
+ break;
1126
+ }
755
1127
  const events = await runtime.events.read(input);
756
- return events.filter((event) => canViewEvent(runtime.authorization, event));
1128
+ return visibleEvents(events);
757
1129
  },
758
- latestCursor: () => runtime.events.latestCursor(),
759
- subscribe: (input, handler) => runtime.events.subscribe(input, (events) => {
760
- const visible = events.filter((event) => canViewEvent(runtime.authorization, event));
761
- if (visible.length > 0)
762
- handler(visible);
763
- })
1130
+ latestCursor: () => {
1131
+ switch (authority.type) {
1132
+ case "denied":
1133
+ case "delegated":
1134
+ return Promise.resolve(undefined);
1135
+ case "principal":
1136
+ case "unrestricted":
1137
+ return runtime.events.latestCursor();
1138
+ }
1139
+ },
1140
+ subscribe: (input, handler) => {
1141
+ switch (authority.type) {
1142
+ case "denied":
1143
+ case "delegated":
1144
+ return Promise.resolve(() => {});
1145
+ case "principal":
1146
+ case "unrestricted":
1147
+ break;
1148
+ }
1149
+ return runtime.events.subscribe(input, (events) => {
1150
+ const visible = visibleEvents(events);
1151
+ if (visible.length > 0)
1152
+ handler(visible);
1153
+ });
1154
+ }
764
1155
  };
765
1156
  }
766
1157
 
@@ -782,129 +1173,118 @@ function createLogsRuntime(runtime, source) {
782
1173
 
783
1174
  // src/objects/execution.ts
784
1175
  function createObjectsRuntime(runtime, execution) {
1176
+ const runtimeAuthorization = runtime.runtimeAuthorization;
1177
+ const objectReader = runtime.objectReader;
1178
+ assertAuthorizedObjectReaderBinding({
1179
+ reader: objectReader,
1180
+ scope: { execution, authorization: runtimeAuthorization }
1181
+ });
1182
+ const authorization = runtime.authorization;
1183
+ const capturedRuntime = {
1184
+ projectId: runtime.projectId,
1185
+ broker: runtime.broker,
1186
+ ontology: runtime.ontology,
1187
+ actionRegistry: runtime.actionRegistry,
1188
+ events: runtime.events,
1189
+ storage: runtime.storage,
1190
+ queues: runtime.queues,
1191
+ runtimeAuthorization,
1192
+ objectReader,
1193
+ ...authorization === undefined ? {} : { authorization }
1194
+ };
1195
+ shareOntologyMutationRuntime(runtime, capturedRuntime);
1196
+ shareSixbErrorReporter(runtime, capturedRuntime);
1197
+ Object.freeze(capturedRuntime);
1198
+ const ontologyView = () => getAuthorizedOntologyView(objectReader);
785
1199
  const objects = Object.assign((objectType) => {
786
- assertObjectTypeRegistered(runtime.ontology.getObjectTypesById(), objectType);
787
- return createObjectSet({ ...runtime, execution, objectType });
1200
+ assertObjectTypeRegistered(capturedRuntime.ontology.getObjectTypesById(), objectType);
1201
+ return createObjectSet({ ...capturedRuntime, execution, objectType });
788
1202
  }, {
789
- listTypes: () => runtime.ontology.listObjectTypes().filter((objectType) => isAllowed(runtime.authorization, {
790
- kind: "object.view",
791
- objectTypeId: objectType.id
792
- })),
793
- getTypeById: (objectTypeId) => {
794
- const objectType = runtime.ontology.getObjectTypeById(objectTypeId);
795
- return objectType && isAllowed(runtime.authorization, { kind: "object.view", objectTypeId }) ? objectType : null;
796
- },
797
- resolveType: (objectTypeId) => {
798
- assertAuthorized(runtime, { kind: "object.view", objectTypeId });
799
- return runtime.ontology.resolveObjectType(objectTypeId);
800
- },
801
- getValueTypesById: () => runtime.ontology.getValueTypesById(),
802
- listSubTypes: (objectTypeId) => runtime.ontology.listSubTypes(objectTypeId),
803
- isValidLinkTarget: (expected, actual) => runtime.ontology.isValidLinkTarget(expected, actual),
804
- executeQuery: (input) => executeObjectQuery({ projectId: runtime.projectId, ...input }, {
805
- ontology: runtime.ontology,
806
- storage: runtime.storage.objects,
807
- runtimeAuthorization: runtime.runtimeAuthorization,
808
- authorization: runtime.authorization
809
- }),
810
- queryLinks: (input) => executeObjectQueryLinks({ projectId: runtime.projectId, ...input }, {
811
- ontology: runtime.ontology,
812
- storage: runtime.storage.objects,
813
- runtimeAuthorization: runtime.runtimeAuthorization,
814
- authorization: runtime.authorization
815
- }),
816
- count: (input) => countObjects({ projectId: runtime.projectId, ...input }, {
817
- ontology: runtime.ontology,
818
- storage: runtime.storage.objects,
819
- runtimeAuthorization: runtime.runtimeAuthorization,
820
- authorization: runtime.authorization
821
- }),
822
- exists: (input) => existsObjects({ projectId: runtime.projectId, ...input }, {
823
- ontology: runtime.ontology,
824
- storage: runtime.storage.objects,
825
- runtimeAuthorization: runtime.runtimeAuthorization,
826
- authorization: runtime.authorization
827
- }),
828
- facet: (input) => facetObjects({ projectId: runtime.projectId, ...input }, {
829
- ontology: runtime.ontology,
830
- storage: runtime.storage.objects,
831
- runtimeAuthorization: runtime.runtimeAuthorization,
832
- authorization: runtime.authorization
833
- }),
1203
+ listTypes: () => ontologyView().listObjectTypes(),
1204
+ getTypeById: (objectTypeId) => ontologyView().getObjectTypeById(objectTypeId),
1205
+ resolveType: (objectTypeId) => ontologyView().resolveObjectType(objectTypeId),
1206
+ getValueTypesById: () => ontologyView().getValueTypesById(),
1207
+ listSubTypes: (objectTypeId) => ontologyView().listSubTypes(objectTypeId),
1208
+ isValidLinkTarget: (expected, actual) => ontologyView().isValidLinkTarget(expected, actual),
1209
+ executeQuery: (input) => objectReader.executeQuery(input),
1210
+ queryLinks: (input) => objectReader.queryLinks(input),
1211
+ count: (input) => objectReader.count(input),
1212
+ exists: (input) => objectReader.exists(input),
1213
+ facet: (input) => objectReader.facet(input),
834
1214
  listLinks: async (input) => {
835
- assertAuthorized(runtime, { kind: "object.view", objectTypeId: input.objectTypeId });
836
- const links = await runtime.storage.objects.listLinks({
837
- projectId: runtime.projectId,
838
- ...input
839
- });
840
- return links.filter((link) => isAllowed(runtime.authorization, {
841
- kind: "object.view",
842
- objectTypeId: link.sourceTypeId
843
- }) && isAllowed(runtime.authorization, {
844
- kind: "object.view",
845
- objectTypeId: link.targetTypeId
846
- }));
1215
+ return objectReader.listLinks(input);
847
1216
  },
848
- getTelemetryHistoryBatch: (input) => getTelemetryHistoryBatch({ projectId: runtime.projectId, ...input }, {
849
- storage: runtime.storage.timeseries,
850
- runtimeAuthorization: runtime.runtimeAuthorization,
851
- authorization: runtime.authorization
852
- }),
853
- getTelemetryHistory: (input) => {
854
- assertAuthorized(runtime, { kind: "object.view", objectTypeId: input.objectTypeId });
855
- return runtime.storage.timeseries.getHistory({
856
- projectId: runtime.projectId,
857
- ...input
858
- });
1217
+ getTelemetryHistoryBatch: (input) => {
1218
+ const timeseries = capturedRuntime.storage.timeseries;
1219
+ return getTelemetryHistoryBatch(input, { storage: timeseries, objectReader });
859
1220
  },
860
- getLatestTelemetry: (input) => {
861
- assertAuthorized(runtime, { kind: "object.view", objectTypeId: input.objectTypeId });
862
- return runtime.storage.timeseries.getLatest({
863
- projectId: runtime.projectId,
864
- ...input
865
- });
1221
+ getTelemetryHistory: async (input) => {
1222
+ const timeseries = capturedRuntime.storage.timeseries;
1223
+ const objectTypeId = input.objectTypeId;
1224
+ const objectId = input.objectId;
1225
+ const propertyId = input.propertyId;
1226
+ const from = input.from;
1227
+ const to = input.to;
1228
+ const limit = input.limit;
1229
+ const order = input.order;
1230
+ const [result] = await getTelemetryHistoryBatch({
1231
+ series: [{ objectTypeId, objectId, propertyId }],
1232
+ ...from === undefined ? {} : { from },
1233
+ ...to === undefined ? {} : { to },
1234
+ ...limit === undefined ? {} : { limitPerSeries: limit },
1235
+ ...order === undefined ? {} : { order }
1236
+ }, { storage: timeseries, objectReader });
1237
+ return result?.points ?? [];
866
1238
  },
867
- list: (params) => listObjects(runtime, params),
868
- get: async (objectTypeId, primaryId) => {
869
- assertAuthorized(runtime, { kind: "object.view", objectTypeId });
870
- return runtime.storage.objects.getByPrimaryId({
871
- projectId: runtime.projectId,
872
- objectTypeId,
873
- primaryId
874
- });
1239
+ getLatestTelemetry: async (input) => {
1240
+ const timeseries = capturedRuntime.storage.timeseries;
1241
+ const objectTypeId = input.objectTypeId;
1242
+ const objectId = input.objectId;
1243
+ const propertyId = input.propertyId;
1244
+ return getLatestTelemetryPoint({ objectTypeId, objectId, propertyId }, { storage: timeseries, objectReader });
875
1245
  },
1246
+ list: (params) => listObjects(capturedRuntime, params),
1247
+ get: (objectTypeId, primaryId) => objectReader.getByPrimaryId({ objectTypeId, primaryId }),
876
1248
  getPrimaryPropertyId: (objectTypeId) => {
877
- assertAuthorized(runtime, { kind: "object.view", objectTypeId });
878
- return runtime.ontology.getPrimaryPropertyId(objectTypeId);
1249
+ return ontologyView().getPrimaryPropertyId(objectTypeId);
879
1250
  },
880
- upsert: (objectTypeId, properties) => upsertObject(runtime, objectTypeId, properties),
881
- upsertBatch: (objectTypeId, items) => upsertObjectBatch(runtime, objectTypeId, items),
882
- upsertLink: (objectTypeId, sourceId, linkId, target) => upsertLink(runtime, objectTypeId, sourceId, linkId, target),
883
- upsertLinkBatch: (items) => upsertLinkBatch(runtime, items),
884
- removeLink: (objectTypeId, sourceId, linkId, target) => removeLink(runtime, objectTypeId, sourceId, linkId, target),
885
- appendTelemetry: (objectTypeId, items) => appendTelemetry(runtime, objectTypeId, items)
1251
+ upsert: (objectTypeId, properties) => upsertObject(capturedRuntime, objectTypeId, properties),
1252
+ upsertBatch: (objectTypeId, items) => upsertObjectBatch(capturedRuntime, objectTypeId, items),
1253
+ upsertLink: (objectTypeId, sourceId, linkId, target) => upsertLink(capturedRuntime, objectTypeId, sourceId, linkId, target),
1254
+ upsertLinkBatch: (items) => upsertLinkBatch(capturedRuntime, items),
1255
+ removeLink: (objectTypeId, sourceId, linkId, target) => removeLink(capturedRuntime, objectTypeId, sourceId, linkId, target),
1256
+ appendTelemetry: (objectTypeId, items) => appendTelemetry(capturedRuntime, objectTypeId, items)
886
1257
  });
887
1258
  return objects;
888
1259
  }
889
1260
 
890
1261
  // src/pipelines/execution.ts
891
1262
  function createPipelinesRuntime(runtime, execution, source) {
892
- const allowed = (pipelineId) => isAllowed(runtime.authorization, { kind: "pipeline.run", pipelineId });
1263
+ const authority = resolveRuntimeAuthorizationForProject(runtime);
1264
+ const allowed = (pipelineId) => isRuntimeAllowed(runtime, { kind: "pipeline.run", pipelineId });
893
1265
  const visibleIds = () => source.list().filter((pipeline) => allowed(pipeline.id)).map((pipeline) => pipeline.id);
1266
+ const historyFilterIds = () => authority.type === "unrestricted" ? undefined : authority.type === "principal" ? visibleIds() : [];
894
1267
  const getRun = async (runId) => {
1268
+ if (authority.type === "denied" || authority.type === "delegated")
1269
+ return null;
895
1270
  const run = await runtime.storage.pipelineRuns?.getById({
896
1271
  projectId: runtime.projectId,
897
1272
  id: runId
898
1273
  }) ?? null;
899
- return run && canViewPipelineRun(runtime.authorization, run) ? run : null;
1274
+ if (!run)
1275
+ return null;
1276
+ return authority.type === "unrestricted" || canViewPipelineRun(authority.context, run) ? run : null;
900
1277
  };
901
1278
  return {
902
- list: () => source.list().filter((pipeline) => allowed(pipeline.id)),
1279
+ list: () => authority.type === "denied" || authority.type === "delegated" ? [] : source.list().filter((pipeline) => allowed(pipeline.id)),
903
1280
  getById: (pipelineId) => {
1281
+ if (authority.type === "denied" || authority.type === "delegated")
1282
+ return null;
904
1283
  const pipeline = source.getById(pipelineId);
905
1284
  return pipeline && allowed(pipelineId) ? pipeline : null;
906
1285
  },
907
1286
  request: async (input) => {
1287
+ assertAuthorized(runtime, { kind: "pipeline.run", pipelineId: input.pipelineId });
908
1288
  const pipeline = source.getById(input.pipelineId);
909
1289
  if (!pipeline)
910
1290
  throw new PipelineError(`[Sixb] Unknown pipeline '${input.pipelineId}'`);
@@ -913,16 +1293,22 @@ function createPipelinesRuntime(runtime, execution, source) {
913
1293
  runs: {
914
1294
  getById: getRun,
915
1295
  list: (input = {}) => {
1296
+ if (authority.type === "denied" || authority.type === "delegated") {
1297
+ return Promise.resolve({ runs: [], hasMore: false, total: 0 });
1298
+ }
916
1299
  const storage = runtime.storage.pipelineRuns;
917
1300
  if (!storage)
918
1301
  return Promise.resolve({ runs: [], hasMore: false, total: 0 });
919
1302
  return storage.list({
920
- projectId: runtime.projectId,
921
1303
  ...input,
922
- pipelineIds: runtime.authorization ? visibleIds() : undefined
1304
+ pipelineIds: historyFilterIds(),
1305
+ projectId: runtime.projectId
923
1306
  });
924
1307
  },
925
1308
  listLatest: (pipelineIds) => {
1309
+ if (authority.type === "denied" || authority.type === "delegated") {
1310
+ return Promise.resolve({ runs: [] });
1311
+ }
926
1312
  const storage = runtime.storage.pipelineRuns;
927
1313
  if (!storage || pipelineIds.length === 0)
928
1314
  return Promise.resolve({ runs: [] });
@@ -937,9 +1323,9 @@ function createPipelinesRuntime(runtime, execution, source) {
937
1323
  if (!storage || !await getRun(runId))
938
1324
  return null;
939
1325
  return storage.listSteps({
940
- projectId: runtime.projectId,
941
1326
  ...input,
942
- pipelineRunId: runId
1327
+ pipelineRunId: runId,
1328
+ projectId: runtime.projectId
943
1329
  });
944
1330
  }
945
1331
  }
@@ -948,39 +1334,95 @@ function createPipelinesRuntime(runtime, execution, source) {
948
1334
 
949
1335
  // src/projections/execution.ts
950
1336
  function createProjectionsRuntime(runtime, source) {
951
- const visible = (projection) => canViewProjection(runtime.authorization, projection);
1337
+ const authority = resolveRuntimeAuthorizationForProject(runtime);
1338
+ const listVisible = (list) => {
1339
+ switch (authority.type) {
1340
+ case "denied":
1341
+ case "delegated":
1342
+ return [];
1343
+ case "principal":
1344
+ return list().filter((projection) => canViewProjection(authority.context, projection));
1345
+ case "unrestricted":
1346
+ return [...list()];
1347
+ }
1348
+ };
1349
+ const visible = (projection) => {
1350
+ switch (authority.type) {
1351
+ case "denied":
1352
+ case "delegated":
1353
+ return false;
1354
+ case "principal":
1355
+ return canViewProjection(authority.context, projection);
1356
+ case "unrestricted":
1357
+ return true;
1358
+ }
1359
+ };
952
1360
  const visibleIds = (projectionIds) => projectionIds.filter((projectionId) => {
953
1361
  const projection = source.getById(projectionId);
954
1362
  return projection !== null && visible(projection);
955
1363
  });
956
1364
  return {
957
- list: () => source.list().filter(visible),
958
- listObjects: () => source.listObjects().filter(visible),
959
- listLinks: () => source.listLinks().filter(visible),
960
- listTelemetry: () => source.listTelemetry().filter(visible),
1365
+ list: () => listVisible(() => source.list()),
1366
+ listObjects: () => listVisible(() => source.listObjects()),
1367
+ listLinks: () => listVisible(() => source.listLinks()),
1368
+ listTelemetry: () => listVisible(() => source.listTelemetry()),
961
1369
  getById: (projectionId) => {
1370
+ switch (authority.type) {
1371
+ case "denied":
1372
+ case "delegated":
1373
+ return null;
1374
+ case "principal":
1375
+ case "unrestricted":
1376
+ break;
1377
+ }
962
1378
  const projection = source.getById(projectionId);
963
1379
  return projection && visible(projection) ? projection : null;
964
1380
  },
965
1381
  runs: {
966
1382
  getById: async (runId) => {
1383
+ switch (authority.type) {
1384
+ case "denied":
1385
+ case "delegated":
1386
+ return null;
1387
+ case "principal":
1388
+ case "unrestricted":
1389
+ break;
1390
+ }
967
1391
  const run = await runtime.storage.projectionRuns?.getById({
968
1392
  projectId: runtime.projectId,
969
1393
  id: runId
970
1394
  }) ?? null;
971
- return run && canViewProjectionRun(runtime.authorization, run.target) ? run : null;
1395
+ if (!run)
1396
+ return null;
1397
+ return authority.type === "unrestricted" || canViewProjectionRun(authority.context, run.target) ? run : null;
972
1398
  },
973
1399
  list: (input = {}) => {
1400
+ switch (authority.type) {
1401
+ case "denied":
1402
+ case "delegated":
1403
+ return Promise.resolve({ runs: [], hasMore: false, total: 0 });
1404
+ case "principal":
1405
+ case "unrestricted":
1406
+ break;
1407
+ }
974
1408
  const storage = runtime.storage.projectionRuns;
975
1409
  if (!storage)
976
1410
  return Promise.resolve({ runs: [], hasMore: false, total: 0 });
977
1411
  return storage.list({
978
- projectId: runtime.projectId,
979
1412
  ...input,
980
- objectTypeIds: runtime.authorization ? [...runtime.authorization.grants["view:object"]] : undefined
1413
+ objectTypeIds: authority.type === "principal" ? [...authority.context.grants["view:object"]] : undefined,
1414
+ projectId: runtime.projectId
981
1415
  });
982
1416
  },
983
1417
  listLatest: (projectionIds) => {
1418
+ switch (authority.type) {
1419
+ case "denied":
1420
+ case "delegated":
1421
+ return Promise.resolve({ runs: [] });
1422
+ case "principal":
1423
+ case "unrestricted":
1424
+ break;
1425
+ }
984
1426
  const storage = runtime.storage.projectionRuns;
985
1427
  if (!storage || projectionIds.length === 0)
986
1428
  return Promise.resolve({ runs: [] });
@@ -993,25 +1435,35 @@ function createProjectionsRuntime(runtime, source) {
993
1435
 
994
1436
  // src/rules/execution.ts
995
1437
  function createRulesRuntime(runtime, source) {
996
- const visible = (rule) => isAllowed(runtime.authorization, {
997
- kind: "object.view",
998
- objectTypeId: rule.subject.objectTypeId
999
- });
1438
+ const authority = resolveRuntimeAuthorizationForProject(runtime);
1439
+ const visible = (rule) => {
1440
+ if (authority.type === "denied" || authority.type === "delegated")
1441
+ return false;
1442
+ return isRuntimeAllowed(runtime, {
1443
+ kind: "object.view",
1444
+ objectTypeId: rule.subject.objectTypeId
1445
+ });
1446
+ };
1000
1447
  return {
1001
- list: () => source.list().filter(visible),
1448
+ list: () => authority.type === "denied" || authority.type === "delegated" ? [] : source.list().filter(visible),
1002
1449
  getById: (ruleId) => {
1450
+ if (authority.type === "denied" || authority.type === "delegated")
1451
+ return null;
1003
1452
  const rule = source.getById(ruleId);
1004
1453
  return rule && visible(rule) ? rule : null;
1005
1454
  },
1006
1455
  states: {
1007
1456
  list: (input = {}) => {
1457
+ if (authority.type === "denied" || authority.type === "delegated") {
1458
+ return Promise.resolve({ states: [], hasMore: false, total: 0 });
1459
+ }
1008
1460
  const storage = runtime.storage.rules;
1009
1461
  if (!storage)
1010
1462
  return Promise.resolve({ states: [], hasMore: false, total: 0 });
1011
1463
  return storage.listActive({
1012
- projectId: runtime.projectId,
1013
1464
  ...input,
1014
- objectTypeIds: runtime.authorization ? [...runtime.authorization.grants["view:object"]] : undefined
1465
+ objectTypeIds: authority.type === "principal" ? [...authority.context.grants["view:object"]] : undefined,
1466
+ projectId: runtime.projectId
1015
1467
  });
1016
1468
  }
1017
1469
  }
@@ -1019,1179 +1471,382 @@ function createRulesRuntime(runtime, source) {
1019
1471
  }
1020
1472
 
1021
1473
  // src/schedules/execution.ts
1022
- function createSchedulesRuntime(schedules) {
1023
- return {
1024
- list: () => schedules.list(),
1025
- getById: (scheduleId) => schedules.getById(scheduleId)
1026
- };
1027
- }
1028
-
1029
- // src/syncs/execution.ts
1030
- function createSyncsRuntime(runtime, execution, source) {
1031
- const allowed = (syncId) => isAllowed(runtime.authorization, { kind: "sync.run", syncId });
1032
- const visibleIds = () => source.list().filter((sync) => allowed(sync.id)).map((sync) => sync.id);
1033
- return {
1034
- list: () => source.list().filter((sync) => allowed(sync.id)),
1035
- getById: (syncId) => {
1036
- const sync = source.getById(syncId);
1037
- return sync && allowed(syncId) ? sync : null;
1038
- },
1039
- request: async (input) => {
1040
- const sync = source.getById(input.syncId);
1041
- if (!sync)
1042
- throw new SyncValidationError(`[Sixb] Unknown sync '${input.syncId}'`);
1043
- return requestSyncRun(runtime, execution, sync, input);
1044
- },
1045
- runs: {
1046
- getById: async (runId) => {
1047
- const run = await runtime.storage.syncRuns?.getById({
1048
- projectId: runtime.projectId,
1049
- id: runId
1050
- }) ?? null;
1051
- return run && allowed(run.syncId) ? run : null;
1052
- },
1053
- list: (input = {}) => {
1054
- const storage = runtime.storage.syncRuns;
1055
- if (!storage)
1056
- return Promise.resolve({ runs: [], hasMore: false, total: 0 });
1057
- return storage.list({
1058
- projectId: runtime.projectId,
1059
- ...input,
1060
- syncIds: runtime.authorization ? visibleIds() : undefined
1061
- });
1062
- },
1063
- listLatest: (syncIds) => {
1064
- const storage = runtime.storage.syncRuns;
1065
- if (!storage || syncIds.length === 0)
1066
- return Promise.resolve({ runs: [] });
1067
- const allowedIds = syncIds.filter(allowed);
1068
- return allowedIds.length === 0 ? Promise.resolve({ runs: [] }) : storage.listLatestBySyncIds({ projectId: runtime.projectId, syncIds: allowedIds });
1069
- }
1070
- }
1071
- };
1072
- }
1073
-
1074
- // src/workflows/errors.ts
1075
- class WorkflowDefinitionError extends Error {
1076
- name = "WorkflowDefinitionError";
1077
- }
1078
-
1079
- class WorkflowValidationError extends Error {
1080
- name = "WorkflowValidationError";
1081
- cause;
1082
- constructor(message, options) {
1083
- super(message);
1084
- this.cause = options?.cause;
1085
- }
1086
- }
1087
-
1088
- // src/workflows/run-dispatch.ts
1089
- import { randomUUID as randomUUID3 } from "crypto";
1090
- import { isDeepStrictEqual } from "util";
1091
-
1092
- // src/agents/context-model.ts
1093
- function serializeAgentContextForModel(parts) {
1094
- if (parts.length === 0)
1095
- return;
1096
- const lines = ["<sixb_user_context>"];
1097
- for (const part of parts) {
1098
- if (part.context.kind === "object") {
1099
- lines.push(" <object_context>", ` <object_type_id>${escapeXml(part.context.ref.objectTypeId)}</object_type_id>`, ` <primary_id>${escapeXml(part.context.ref.primaryId)}</primary_id>`, " </object_context>");
1100
- continue;
1101
- }
1102
- lines.push(" <app_state_context>", ` <id>${escapeXml(part.context.id)}</id>`, ` <description>${escapeXml(part.context.description)}</description>`, ` <value format="json">${escapeXml(stableJsonStringify(part.context.value))}</value>`, " </app_state_context>");
1103
- }
1104
- lines.push("</sixb_user_context>");
1105
- return lines.join(`
1106
- `);
1107
- }
1108
- function escapeXml(value) {
1109
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
1110
- }
1111
-
1112
- // src/agents/tool-result.ts
1113
- function isAgentToolResult(value) {
1114
- return isPlainRecord(value) && value.kind === "agentToolResult" && getInvalidAgentToolResultReason(value) === undefined;
1115
- }
1116
- function getInvalidAgentToolResultReason(value) {
1117
- if (!isPlainRecord(value) || value.kind !== "agentToolResult") {
1118
- return;
1119
- }
1120
- if (!Array.isArray(value.content)) {
1121
- return "result.content must be an array";
1122
- }
1123
- const unsupportedKey = Object.keys(value).find((key) => key !== "kind" && key !== "content");
1124
- if (unsupportedKey) {
1125
- return `result.${unsupportedKey} is not supported`;
1126
- }
1127
- if (value.content.length === 0) {
1128
- return "result.content must contain at least one content part";
1129
- }
1130
- for (let index = 0;index < value.content.length; index += 1) {
1131
- const part = value.content[index];
1132
- const path = `result.content[${index}]`;
1133
- if (!isPlainRecord(part)) {
1134
- return `${path} must be a text or file content part`;
1135
- }
1136
- if (part.type === "text") {
1137
- if (typeof part.text !== "string") {
1138
- return `${path}.text must be a string`;
1139
- }
1140
- const unsupportedKey2 = Object.keys(part).find((key) => key !== "type" && key !== "text");
1141
- if (unsupportedKey2) {
1142
- return `${path}.${unsupportedKey2} is not supported`;
1143
- }
1144
- continue;
1145
- }
1146
- if (part.type === "file") {
1147
- if (!isFileRef(part.fileRef)) {
1148
- return `${path}.fileRef must be a valid FileRef`;
1149
- }
1150
- const unsupportedKey2 = Object.keys(part).find((key) => key !== "type" && key !== "fileRef");
1151
- if (unsupportedKey2) {
1152
- return `${path}.${unsupportedKey2} is not supported`;
1153
- }
1154
- continue;
1155
- }
1156
- return `${path}.type must be 'text' or 'file'`;
1157
- }
1158
- return;
1159
- }
1160
-
1161
- // src/agents/adapters.ts
1162
- var TOOL_TYPE_PREFIX = "tool-";
1163
- function assertAdapter(condition, message) {
1164
- if (!condition) {
1165
- throw new AgentMessageAdapterError(`[Sixb] ${message}`);
1166
- }
1167
- }
1168
- function requireJson(value, label) {
1169
- const reason = getInvalidJsonValueReason(value, label);
1170
- assertAdapter(reason === undefined, `agent message ${label} must be a JSON value; ${reason}`);
1171
- return value;
1172
- }
1173
- function optionalJson(value, label) {
1174
- if (value === undefined)
1175
- return;
1176
- return requireJson(omitUndefinedObjectProperties(value), label);
1177
- }
1178
- function omitUndefinedObjectProperties(value) {
1179
- return omitUndefinedObjectPropertiesInternal(value, new Set);
1180
- }
1181
- function omitUndefinedObjectPropertiesInternal(value, seen) {
1182
- if (typeof value !== "object" || value === null)
1183
- return value;
1184
- if (seen.has(value))
1185
- return value;
1186
- seen.add(value);
1187
- try {
1188
- if (Array.isArray(value)) {
1189
- return value.map((entry) => omitUndefinedObjectPropertiesInternal(entry, seen));
1190
- }
1191
- if (!isPlainRecord(value))
1192
- return value;
1193
- return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined).map(([key, entry]) => [key, omitUndefinedObjectPropertiesInternal(entry, seen)]));
1194
- } finally {
1195
- seen.delete(value);
1196
- }
1197
- }
1198
- function isToolType(type) {
1199
- return type === "dynamic-tool" || type.startsWith(TOOL_TYPE_PREFIX);
1200
- }
1201
- function toolNameFromInbound(part) {
1202
- if (part.type === "dynamic-tool") {
1203
- assertAdapter(typeof part.toolName === "string" && part.toolName.length > 0, "dynamic-tool part is missing a tool name");
1204
- return part.toolName;
1205
- }
1206
- const name = part.type.slice(TOOL_TYPE_PREFIX.length);
1207
- assertAdapter(name.length > 0, `tool part type '${part.type}' is missing a tool name`);
1208
- return name;
1209
- }
1210
- function fromAiSdk(message) {
1211
- const { role } = message;
1212
- assertAdapter(role === "system" || role === "user" || role === "assistant", `unsupported message role '${role}'`);
1213
- const parts = message.parts.map((part) => fromAiSdkPart(part));
1214
- assertAdapter(role === "user" || !parts.some((part) => part.type === "context"), "context parts are only valid on user messages");
1215
- const metadata = optionalJson(message.metadata, "metadata");
1216
- return {
1217
- role,
1218
- parts,
1219
- ...metadata === undefined ? {} : { metadata }
1220
- };
1221
- }
1222
- function fromAiSdkPart(part) {
1223
- switch (part.type) {
1224
- case "text":
1225
- case "reasoning": {
1226
- assertAdapter(typeof part.text === "string", `${part.type} part is missing text`);
1227
- assertAdapter(part.state !== "streaming", `cannot persist a streaming ${part.type} part; messages are written only once finalized`);
1228
- const providerMetadata = optionalJson(part.providerMetadata, `${part.type}.providerMetadata`);
1229
- return {
1230
- type: part.type,
1231
- text: part.text,
1232
- ...providerMetadata === undefined ? {} : { providerMetadata }
1233
- };
1234
- }
1235
- case "step-start":
1236
- return { type: "step-start" };
1237
- case "file": {
1238
- assertAdapter(isFileRef(part.fileRef), "file part is missing a valid fileRef");
1239
- const providerMetadata = optionalJson(part.providerMetadata, "file.providerMetadata");
1240
- return {
1241
- type: "file",
1242
- fileRef: part.fileRef,
1243
- ...providerMetadata === undefined ? {} : { providerMetadata }
1244
- };
1245
- }
1246
- case "context":
1247
- return fromUiContextPart(part);
1248
- default: {
1249
- assertAdapter(isToolType(part.type), `unsupported message part type '${part.type}'; extend the Sixb message part union to support it`);
1250
- return fromAiSdkToolPart(part);
1251
- }
1252
- }
1253
- }
1254
- function fromUiContextPart(part) {
1255
- try {
1256
- const [entry] = normalizeAgentContextEntries([
1257
- { context: part.context, origin: part.origin }
1258
- ]);
1259
- return { type: "context", ...entry };
1260
- } catch (error) {
1261
- throw new AgentMessageAdapterError(error instanceof Error ? error.message : "[Sixb] Invalid agent context part.");
1262
- }
1263
- }
1264
- function fromAiSdkToolPart(part) {
1265
- const dynamic = part.type === "dynamic-tool";
1266
- const toolName = toolNameFromInbound(part);
1267
- assertAdapter(typeof part.toolCallId === "string" && part.toolCallId.length > 0, `tool part '${part.type}' is missing a toolCallId`);
1268
- assertAdapter(part.state === "output-available" || part.state === "output-error", `cannot persist tool part '${part.toolCallId}' in transient state '${part.state}'; only terminal states are stored`);
1269
- const input = part.input === undefined ? null : requireJson(part.input, "tool input");
1270
- const providerMetadata = optionalJson(part.callProviderMetadata, "tool callProviderMetadata");
1271
- const base = {
1272
- type: "tool-call",
1273
- toolCallId: part.toolCallId,
1274
- toolName,
1275
- input,
1276
- ...dynamic ? { dynamic: true } : {},
1277
- ...part.providerExecuted === undefined ? {} : { providerExecuted: part.providerExecuted },
1278
- ...providerMetadata === undefined ? {} : { providerMetadata }
1279
- };
1280
- if (part.state === "output-available") {
1281
- return { ...base, state: "output-available", output: requireJson(part.output, "tool output") };
1282
- }
1283
- assertAdapter(typeof part.errorText === "string", `tool part '${part.toolCallId}' is missing errorText`);
1284
- return { ...base, state: "output-error", errorText: part.errorText };
1285
- }
1286
- function toUiMessage(message) {
1287
- return {
1288
- role: message.role,
1289
- parts: message.parts.map((part) => toUiPart(part)),
1290
- ...message.metadata === undefined ? {} : { metadata: message.metadata }
1291
- };
1292
- }
1293
- function toUiPart(part) {
1294
- switch (part.type) {
1295
- case "text":
1296
- case "reasoning":
1297
- return {
1298
- type: part.type,
1299
- text: part.text,
1300
- ...part.providerMetadata === undefined ? {} : { providerMetadata: part.providerMetadata }
1301
- };
1302
- case "step-start":
1303
- return { type: "step-start" };
1304
- case "file":
1305
- return {
1306
- type: "file",
1307
- fileRef: part.fileRef,
1308
- ...part.providerMetadata === undefined ? {} : { providerMetadata: part.providerMetadata }
1309
- };
1310
- case "context":
1311
- return { type: "context", context: part.context, origin: part.origin };
1312
- case "tool-call":
1313
- return toUiToolPart(part);
1314
- }
1315
- }
1316
- function toUiToolPart(part) {
1317
- const body = {
1318
- toolCallId: part.toolCallId,
1319
- ...part.providerExecuted === undefined ? {} : { providerExecuted: part.providerExecuted },
1320
- ...part.providerMetadata === undefined ? {} : { callProviderMetadata: part.providerMetadata }
1321
- };
1322
- const state = part.state === "output-available" ? { state: "output-available", input: part.input, output: part.output } : { state: "output-error", input: part.input, errorText: part.errorText };
1323
- if (part.dynamic) {
1324
- return { type: "dynamic-tool", toolName: part.toolName, ...body, ...state };
1325
- }
1326
- return { type: `tool-${part.toolName}`, ...body, ...state };
1327
- }
1328
- function toModelMessages(messages, options = {}) {
1329
- const result = [];
1330
- for (const message of messages) {
1331
- switch (message.role) {
1332
- case "system":
1333
- result.push(systemModelMessage(message));
1334
- break;
1335
- case "user":
1336
- result.push(userModelMessage(message, options));
1337
- break;
1338
- case "assistant":
1339
- appendAssistantModelMessages(result, message, options);
1340
- break;
1341
- }
1342
- }
1343
- return result;
1344
- }
1345
- function systemModelMessage(message) {
1346
- const textParts = message.parts.filter(isTextPart);
1347
- const providerOptions = mergeProviderMetadata(textParts);
1474
+ function createSchedulesRuntime(runtime, schedules) {
1475
+ const authority = resolveRuntimeAuthorizationForProject(runtime);
1348
1476
  return {
1349
- role: "system",
1350
- content: textParts.map((part) => part.text).join(""),
1351
- ...providerOptions === undefined ? {} : { providerOptions }
1352
- };
1353
- }
1354
- function mergeProviderMetadata(parts) {
1355
- let merged;
1356
- for (const part of parts) {
1357
- const meta = part.providerMetadata;
1358
- if (meta !== undefined && typeof meta === "object" && meta !== null && !Array.isArray(meta)) {
1359
- merged = { ...merged ?? {}, ...meta };
1360
- }
1361
- }
1362
- return merged;
1363
- }
1364
- function userModelMessage(message, options) {
1365
- const content = [];
1366
- const serializedContext = serializeAgentContextForModel(message.parts.filter((part) => part.type === "context"));
1367
- if (serializedContext) {
1368
- content.push({ type: "text", text: `${serializedContext}
1369
-
1370
- ` });
1371
- }
1372
- message.parts.forEach((part, partIndex) => {
1373
- if (part.type === "text") {
1374
- content.push({
1375
- type: "text",
1376
- text: part.text,
1377
- ...part.providerMetadata === undefined ? {} : { providerOptions: part.providerMetadata }
1378
- });
1379
- return;
1380
- }
1381
- if (part.type === "file") {
1382
- const fileContext = options.fileText?.({ message, part, partIndex });
1383
- if (fileContext) {
1384
- content.push({ type: "text", text: fileContext });
1477
+ list: () => {
1478
+ switch (authority.type) {
1479
+ case "denied":
1480
+ case "delegated":
1481
+ return [];
1482
+ case "principal":
1483
+ case "unrestricted":
1484
+ return schedules.list();
1385
1485
  }
1386
- const resolved = options.fileData?.({ message, part, partIndex });
1387
- if (resolved) {
1388
- const projection = resolved instanceof URL ? { data: resolved } : resolved;
1389
- content.push({
1390
- type: "file",
1391
- data: projection.data,
1392
- mediaType: projection.mediaType ?? part.fileRef.mediaType ?? "application/octet-stream",
1393
- ...projection.filename !== undefined ? { filename: projection.filename } : part.fileRef.fileName === undefined ? {} : { filename: part.fileRef.fileName },
1394
- ...part.providerMetadata === undefined ? {} : { providerOptions: part.providerMetadata }
1395
- });
1396
- }
1397
- }
1398
- });
1399
- return { role: "user", content };
1400
- }
1401
- function appendAssistantModelMessages(result, message, options) {
1402
- let block = [];
1403
- const flush = () => {
1404
- if (block.length === 0) {
1405
- return;
1406
- }
1407
- const current = block;
1408
- block = [];
1409
- const content = [];
1410
- for (const { part, partIndex } of current) {
1411
- if (part.type === "text") {
1412
- content.push({
1413
- type: "text",
1414
- text: part.text,
1415
- ...part.providerMetadata === undefined ? {} : { providerOptions: part.providerMetadata }
1416
- });
1417
- } else if (part.type === "reasoning") {
1418
- content.push({
1419
- type: "reasoning",
1420
- text: part.text,
1421
- ...part.providerMetadata === undefined ? {} : { providerOptions: part.providerMetadata }
1422
- });
1423
- } else if (part.type === "file") {
1424
- const fileContext = options.fileText?.({ message, part, partIndex });
1425
- if (fileContext) {
1426
- content.push({ type: "text", text: fileContext });
1427
- }
1428
- } else if (part.type === "tool-call") {
1429
- content.push(toolCallModelPart(part));
1430
- if (part.providerExecuted === true) {
1431
- content.push(toolResultModelPart(message, part, partIndex, "json", options));
1432
- }
1433
- }
1434
- }
1435
- result.push({ role: "assistant", content });
1436
- const toolResults = current.flatMap(({ part, partIndex }) => part.type === "tool-call" && part.providerExecuted !== true ? [toolResultModelPart(message, part, partIndex, "text", options)] : []);
1437
- if (toolResults.length > 0) {
1438
- result.push({ role: "tool", content: toolResults });
1439
- }
1440
- };
1441
- message.parts.forEach((part, partIndex) => {
1442
- if (part.type === "step-start") {
1443
- flush();
1444
- } else {
1445
- block.push({ part, partIndex });
1446
- }
1447
- });
1448
- flush();
1449
- }
1450
- function toolCallModelPart(part) {
1451
- return {
1452
- type: "tool-call",
1453
- toolCallId: part.toolCallId,
1454
- toolName: part.toolName,
1455
- input: part.input,
1456
- ...part.providerExecuted === undefined ? {} : { providerExecuted: part.providerExecuted },
1457
- ...part.providerMetadata === undefined ? {} : { providerOptions: part.providerMetadata }
1458
- };
1459
- }
1460
- function toolResultModelPart(message, part, partIndex, errorMode, options) {
1461
- return {
1462
- type: "tool-result",
1463
- toolCallId: part.toolCallId,
1464
- toolName: part.toolName,
1465
- output: toolResultOutput(message, part, partIndex, errorMode, options),
1466
- ...part.providerMetadata === undefined ? {} : { providerOptions: part.providerMetadata }
1467
- };
1468
- }
1469
- function toolResultOutput(message, part, partIndex, errorMode, options) {
1470
- if (part.state === "output-error") {
1471
- return errorMode === "json" ? { type: "error-json", value: part.errorText } : { type: "error-text", value: part.errorText };
1472
- }
1473
- if (isAgentToolResult(part.output)) {
1474
- const value = [];
1475
- part.output.content.forEach((contentPart, contentIndex) => {
1476
- if (contentPart.type === "text") {
1477
- value.push(contentPart.text);
1478
- return;
1479
- }
1480
- const resolverInput = { message, part, partIndex, contentPart, contentIndex };
1481
- const fileContext = options.toolResultFileText?.(resolverInput);
1482
- if (fileContext) {
1483
- value.push(fileContext);
1484
- } else {
1485
- value.push(toolResultFileFallbackText(contentPart));
1486
- }
1487
- });
1488
- return { type: "text", value: value.join(`
1489
- `) };
1490
- }
1491
- return typeof part.output === "string" ? { type: "text", value: part.output } : { type: "json", value: part.output };
1492
- }
1493
- function toolResultFileFallbackText(part) {
1494
- const attributes = [
1495
- part.fileRef.fileName ? `name=${JSON.stringify(part.fileRef.fileName)}` : undefined,
1496
- part.fileRef.mediaType ? `mediaType=${JSON.stringify(part.fileRef.mediaType)}` : undefined,
1497
- `sizeBytes=${part.fileRef.sizeBytes}`
1498
- ].filter((value) => value !== undefined);
1499
- return `[Tool-created file: ${attributes.join(" ")}. Contents are not available inline.]`;
1500
- }
1501
- function isTextPart(part) {
1502
- return part.type === "text";
1503
- }
1504
- // src/agents/api-gateway.ts
1505
- import { createHmac, timingSafeEqual } from "crypto";
1506
- var AGENT_API_GATEWAY_PREFIX = "/__sixb/agent-api";
1507
- var AGENT_API_GATEWAY_CAPABILITY_PREFIX = "sixb_agw_v1_";
1508
- var AGENT_API_ROUTES = SIXB_API_ROUTES.filter((route) => route.agentApi).map((route) => ({ method: route.method, path: route.path }));
1509
- function createAgentApiGatewayCapability(input) {
1510
- return `${AGENT_API_GATEWAY_CAPABILITY_PREFIX}${capabilityDigest(input)}`;
1511
- }
1512
- function isValidAgentApiGatewayCapability(input) {
1513
- const expected = createAgentApiGatewayCapability(input);
1514
- const actual = input.capability;
1515
- const expectedBuffer = Buffer.from(expected);
1516
- const actualBuffer = Buffer.from(actual);
1517
- return expectedBuffer.byteLength === actualBuffer.byteLength && timingSafeEqual(expectedBuffer, actualBuffer);
1518
- }
1519
- function isAllowedAgentApiRequest(method, pathname) {
1520
- const normalizedMethod = method.toUpperCase();
1521
- const normalizedPath = normalizeRoutePath(pathname);
1522
- return AGENT_API_ROUTES.some((route) => route.method === normalizedMethod && matchesPathPattern(normalizedPath, route.path));
1523
- }
1524
- function capabilityDigest(input) {
1525
- return createHmac("sha256", input.executionToken).update(`agent-api-gateway:${input.projectId}:${input.runId}`).digest("base64url");
1526
- }
1527
- // src/agents/types.ts
1528
- var AGENT_REASONING_LEVELS = [
1529
- "provider-default",
1530
- "none",
1531
- "minimal",
1532
- "low",
1533
- "medium",
1534
- "high",
1535
- "xhigh"
1536
- ];
1537
-
1538
- // src/agents/validation.ts
1539
- var AGENT_TOOL_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
1540
- var AGENT_TOOL_PRIMITIVE_SCHEMAS = new Set([
1541
- "string",
1542
- "integer",
1543
- "double",
1544
- "decimal",
1545
- "boolean",
1546
- "date",
1547
- "timestamp",
1548
- "uuid",
1549
- "fileRef"
1550
- ]);
1551
- var AGENT_RESERVED_TOOL_NAMES = ["bash", "read", "view_file"];
1552
- function assertNonEmpty(value, field) {
1553
- if (!value.trim()) {
1554
- throw new AgentDefinitionError(`[Sixb] Agent ${field} must not be empty.`);
1555
- }
1556
- }
1557
- function isAgentDefinition(value) {
1558
- return isRecord(value) && value.kind === "agent" && typeof value.id === "string" && typeof value.name === "string" && typeof value.instructions === "string" && (value.reasoning === undefined || isAgentReasoningLevel(value.reasoning)) && (value.providerOptions === undefined || isProviderOptions(value.providerOptions)) && Array.isArray(value.groupIds) && isAgentToolDefinitionArray(value.tools);
1559
- }
1560
- function isAgentToolDefinition(value) {
1561
- return isRecord(value) && value.kind === "agentTool" && typeof value.name === "string" && typeof value.description === "string" && isPlainRecord(value.input) && typeof value.handler === "function";
1562
- }
1563
- function assertValidAgentToolName(name) {
1564
- if (typeof name !== "string" || !AGENT_TOOL_NAME_PATTERN.test(name)) {
1565
- throw new AgentDefinitionError("[Sixb] Agent tool name must be 1-64 characters, start with a letter or underscore, and contain only letters, numbers, underscores, or hyphens.");
1566
- }
1567
- if (AGENT_RESERVED_TOOL_NAMES.includes(name)) {
1568
- throw new AgentDefinitionError(`[Sixb] Agent tool name '${name}' is reserved by the framework.`);
1569
- }
1570
- }
1571
- function assertValidAgentToolDescription(name, description) {
1572
- if (typeof description !== "string" || !description.trim()) {
1573
- throw new AgentDefinitionError(`[Sixb] Agent tool '${name}' description must not be empty.`);
1574
- }
1575
- }
1576
- function assertValidAgentToolInput(name, input) {
1577
- if (!isPlainRecord(input)) {
1578
- throw new AgentDefinitionError(`[Sixb] Agent tool '${name}' input must be a schema object.`);
1579
- }
1580
- for (const [field, schema] of Object.entries(input)) {
1581
- if (!field.trim()) {
1582
- throw new AgentDefinitionError(`[Sixb] Agent tool '${name}' input field names must not be empty.`);
1583
- }
1584
- assertValidAgentToolSchema(name, schema, `input.${field}`, new Set);
1585
- }
1586
- }
1587
- function validateAndSnapshotAgentToolInput(toolName, input) {
1588
- assertValidAgentToolInput(toolName, input);
1589
- try {
1590
- return deepFreeze(structuredClone(input));
1591
- } catch {
1592
- throw new AgentDefinitionError(`[Sixb] Agent tool '${toolName}' input must be safely snapshot-compatible.`);
1593
- }
1594
- }
1595
- function validateAndNormalizeAgentToolInput(toolName, shape, value, valueTypesById) {
1596
- const label = `Agent tool '${toolName}' input`;
1597
- if (!isPlainRecord(value)) {
1598
- throw new OntologyValidationError(`[Sixb] ${label} must be a JSON object.`);
1599
- }
1600
- const reason = getInvalidJsonValueReason(value, label);
1601
- if (reason) {
1602
- throw new OntologyValidationError(`[Sixb] ${label} must be JSON-compatible; ${reason}.`);
1603
- }
1604
- const schema = {
1605
- type: "object",
1606
- properties: Object.fromEntries(Object.entries(shape).map(([field, fieldSchema]) => [
1607
- field,
1608
- { schema: fieldSchema, required: true }
1609
- ]))
1610
- };
1611
- validateSchemaValue(schema, value, label, valueTypesById);
1612
- return deepFreeze(normalizeSchemaValue(schema, value, label, valueTypesById));
1613
- }
1614
- function validateAgentToolsAtStartup(agents) {
1615
- for (const agent of agents) {
1616
- if (!isAgentDefinition(agent)) {
1617
- throw new AgentDefinitionError("[Sixb] Agents must contain only valid agent definitions.");
1618
- }
1619
- assertValidAgentToolDefinitions(agent.id, agent.tools);
1620
- for (const tool of agent.tools) {
1621
- deepFreeze(tool.input);
1622
- Object.freeze(tool);
1623
- }
1624
- Object.freeze(agent.tools);
1625
- Object.freeze(agent);
1626
- }
1627
- }
1628
- function resolveAgentLoopConfig(loop) {
1629
- if (loop === undefined)
1630
- return;
1631
- const maxSteps = loop?.stopWhen?.maxSteps;
1632
- if (maxSteps !== undefined && (!Number.isSafeInteger(maxSteps) || maxSteps <= 0)) {
1633
- throw new AgentDefinitionError("[Sixb] Agent loop.stopWhen.maxSteps must be a positive safe integer.");
1634
- }
1635
- if (loop.caching !== undefined && loop.caching !== "auto" && loop.caching !== "off") {
1636
- throw new AgentDefinitionError("[Sixb] Agent loop.caching must be 'auto' or 'off'.");
1637
- }
1638
- const context = loop.context ? snapshotAgentContextConfig(loop.context) : undefined;
1639
- return Object.freeze({
1640
- ...loop.stopWhen === undefined ? {} : { stopWhen: Object.freeze({ ...maxSteps === undefined ? {} : { maxSteps } }) },
1641
- ...context === undefined ? {} : { context },
1642
- ...loop.caching === undefined ? {} : { caching: loop.caching }
1643
- });
1644
- }
1645
- function snapshotAgentContextConfig(context) {
1646
- const snapshot = {};
1647
- for (const field of ["windowTokens", "reserveTokens", "keepRecentTokens"]) {
1648
- const value = context[field];
1649
- if (value === undefined)
1650
- continue;
1651
- assertPositiveSafeInteger(value, field);
1652
- snapshot[field] = value;
1653
- }
1654
- return Object.freeze(snapshot);
1655
- }
1656
- function assertPositiveSafeInteger(value, field) {
1657
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
1658
- throw new AgentDefinitionError(`[Sixb] Agent loop.context.${field} must be a positive safe integer.`);
1659
- }
1660
- }
1661
- function assertValidReasoningLevel(reasoning) {
1662
- if (reasoning === undefined) {
1663
- return;
1664
- }
1665
- if (!isAgentReasoningLevel(reasoning)) {
1666
- throw new AgentDefinitionError(`[Sixb] Agent reasoning must be one of: ${AGENT_REASONING_LEVELS.join(", ")}.`);
1667
- }
1668
- }
1669
- function assertValidProviderOptions(providerOptions) {
1670
- if (providerOptions === undefined) {
1671
- return;
1672
- }
1673
- const reason = getInvalidJsonValueReason(providerOptions, "providerOptions");
1674
- if (!isRecord(providerOptions) || reason) {
1675
- throw new AgentDefinitionError(`[Sixb] Agent providerOptions must be a provider-keyed JSON object${reason ? `; ${reason}` : "."}`);
1676
- }
1677
- for (const [provider, options] of Object.entries(providerOptions)) {
1678
- if (!provider.trim()) {
1679
- throw new AgentDefinitionError("[Sixb] Agent providerOptions provider names must not be empty.");
1680
- }
1681
- const optionsReason = getInvalidJsonValueReason(options, `providerOptions.${provider}`);
1682
- if (!isRecord(options) || optionsReason) {
1683
- throw new AgentDefinitionError(`[Sixb] Agent providerOptions.${provider} must be a JSON object${optionsReason ? `; ${optionsReason}` : "."}`);
1684
- }
1685
- }
1686
- }
1687
- function groupIdsFromDefinitions(agentId, groups) {
1688
- const groupIds = (groups ?? []).map((group) => {
1689
- if (!isRecord(group) || group.kind !== "group") {
1690
- throw new AgentDefinitionError(`[Sixb] Agent '${agentId}' groups must contain only group definitions.`);
1691
- }
1692
- assertNonEmpty(group.id, `Agent '${agentId}' group id`);
1693
- return group.id;
1694
- });
1695
- assertNoDuplicateGroupIds(agentId, groupIds);
1696
- return Object.freeze(groupIds);
1697
- }
1698
- function validateAgentGroupReferences(agents, security) {
1699
- for (const agent of agents) {
1700
- assertNoDuplicateGroupIds(agent.id, agent.groupIds);
1701
- for (const groupId of agent.groupIds) {
1702
- if (!security.getGroupById(groupId)) {
1703
- throw new AgentDefinitionError(`[Sixb] Agent '${agent.id}' groups references unknown group '${groupId}'. Add it to 'security/groups/' or pass it to createSixb({ groups }).`);
1486
+ },
1487
+ getById: (scheduleId) => {
1488
+ switch (authority.type) {
1489
+ case "denied":
1490
+ case "delegated":
1491
+ return null;
1492
+ case "principal":
1493
+ case "unrestricted":
1494
+ return schedules.getById(scheduleId);
1704
1495
  }
1705
1496
  }
1706
- }
1707
- }
1708
- function assertNoDuplicateGroupIds(agentId, groupIds) {
1709
- const seen = new Set;
1710
- for (const groupId of groupIds) {
1711
- assertNonEmpty(groupId, `Agent '${agentId}' group id`);
1712
- if (seen.has(groupId)) {
1713
- throw new AgentDefinitionError(`[Sixb] Agent '${agentId}' groups contains duplicate group id '${groupId}'.`);
1714
- }
1715
- seen.add(groupId);
1716
- }
1717
- }
1718
- function isAgentReasoningLevel(value) {
1719
- return typeof value === "string" && AGENT_REASONING_LEVELS.includes(value);
1497
+ };
1720
1498
  }
1721
- function isProviderOptions(value) {
1722
- if (!isRecord(value) || getInvalidJsonValueReason(value) !== undefined) {
1723
- return false;
1499
+
1500
+ // src/shares/execution.ts
1501
+ import { createHash as createHash2, randomBytes, randomUUID as randomUUID4 } from "crypto";
1502
+ var MAX_CREATE_ATTEMPTS = 5;
1503
+
1504
+ class ShareError extends Error {
1505
+ reason;
1506
+ name = "ShareError";
1507
+ constructor(reason, message, options) {
1508
+ super(message, options);
1509
+ this.reason = reason;
1724
1510
  }
1725
- return Object.entries(value).every(([provider, options]) => provider.trim().length > 0 && isRecord(options) && getInvalidJsonValueReason(options) === undefined);
1726
1511
  }
1727
- function assertValidAgentToolSchema(toolName, schema, path, visiting) {
1728
- if (typeof schema === "string") {
1729
- if (AGENT_TOOL_PRIMITIVE_SCHEMAS.has(schema)) {
1730
- return;
1512
+ function createSharesRuntime(runtime, execution, definitions) {
1513
+ const managementPrincipal = () => {
1514
+ const authority = resolveExecutionScopeAuthorization(runtime.projectId, {
1515
+ execution,
1516
+ authorization: runtime.runtimeAuthorization
1517
+ });
1518
+ if (authority.type !== "principal" || authority.context.principal.type === "system") {
1519
+ throw new ShareError("unauthenticated", "[Sixb] Shared access grants require user or service-account authority.");
1731
1520
  }
1732
- throw invalidAgentToolSchema(toolName, path);
1733
- }
1734
- if (!isPlainRecord(schema) || typeof schema.type !== "string" || visiting.has(schema)) {
1735
- throw invalidAgentToolSchema(toolName, path);
1736
- }
1737
- visiting.add(schema);
1738
- switch (schema.type) {
1739
- case "enum": {
1740
- const values = schema.values;
1741
- const validValues = isValidAgentToolEnumValues(values, schema.valueType);
1742
- if (!validValues || new Set(values).size !== values.length) {
1743
- throw invalidAgentToolSchema(toolName, path);
1744
- }
1745
- break;
1746
- }
1747
- case "array":
1748
- assertValidAgentToolSchema(toolName, schema.items, `${path}.items`, visiting);
1749
- break;
1750
- case "map":
1751
- if (schema.keySchema !== "string") {
1752
- throw invalidAgentToolSchema(toolName, path);
1753
- }
1754
- assertValidAgentToolSchema(toolName, schema.valueSchema, `${path}.valueSchema`, visiting);
1755
- break;
1756
- case "object": {
1757
- if (!isPlainRecord(schema.properties)) {
1758
- throw invalidAgentToolSchema(toolName, path);
1759
- }
1760
- for (const [fieldId, field] of Object.entries(schema.properties)) {
1761
- if (!fieldId.trim() || !isPlainRecord(field) || !("schema" in field)) {
1762
- throw invalidAgentToolSchema(toolName, `${path}.properties.${fieldId}`);
1521
+ return {
1522
+ type: authority.context.principal.type,
1523
+ id: authority.context.principal.id
1524
+ };
1525
+ };
1526
+ const canManage = (shareId) => {
1527
+ try {
1528
+ managementPrincipal();
1529
+ return isRuntimeAllowed(runtime, { kind: "share.manage", shareId });
1530
+ } catch {
1531
+ return false;
1532
+ }
1533
+ };
1534
+ const resolveManageableDefinition = (definitionId) => {
1535
+ const id = validDefinitionId(definitionId);
1536
+ managementPrincipal();
1537
+ assertCanManage(runtime, id);
1538
+ return resolveDefinition(definitions, id);
1539
+ };
1540
+ const issueByDefinition = async (definition, input) => {
1541
+ assertInputObject(input, "Shared access issue input");
1542
+ const issuer = managementPrincipal();
1543
+ assertCanManage(runtime, definition.id);
1544
+ const storage = requireShareStorage(runtime);
1545
+ const createdAt = new Date;
1546
+ const expiresAt = validFutureDate(input.expiresAt, createdAt);
1547
+ const target = exactTarget(definition, input.target);
1548
+ const object = await runtime.objectReader.getByPrimaryId({
1549
+ objectTypeId: target.objectTypeId,
1550
+ primaryId: target.primaryId
1551
+ });
1552
+ if (!object) {
1553
+ throw new ObjectNotFoundError(target.objectTypeId, target.primaryId, "Share target not found");
1554
+ }
1555
+ const authoritySnapshot = {
1556
+ version: 1,
1557
+ access: compileShareAccessPlan({
1558
+ share: definition,
1559
+ target,
1560
+ ontology: runtime.ontology,
1561
+ actions: runtime.actionRegistry
1562
+ })
1563
+ };
1564
+ for (let attempt = 0;attempt < MAX_CREATE_ATTEMPTS; attempt += 1) {
1565
+ const secret = randomBytes(32).toString("base64url");
1566
+ try {
1567
+ const grant = await storage.create({
1568
+ id: `shr_${randomUUID4()}`,
1569
+ projectId: runtime.projectId,
1570
+ definitionId: definition.id,
1571
+ target,
1572
+ issuedBy: issuer,
1573
+ authoritySnapshot,
1574
+ tokenHash: sha256(secret),
1575
+ destinationPath: input.destinationPath,
1576
+ createdAt,
1577
+ expiresAt
1578
+ });
1579
+ return { grant: publicGrant(grant), secret };
1580
+ } catch (error) {
1581
+ if (error instanceof ShareGrantStorageError && error.code === "invalid_input") {
1582
+ throw new ShareError("invalid_input", error.message, { cause: error });
1763
1583
  }
1764
- if (field.required !== undefined && typeof field.required !== "boolean" || field.nullable !== undefined && typeof field.nullable !== "boolean" || field.description !== undefined && (typeof field.description !== "string" || !field.description.trim())) {
1765
- throw invalidAgentToolSchema(toolName, `${path}.properties.${fieldId}`);
1584
+ if (!(error instanceof ShareGrantStorageError) || error.code !== "duplicate" || attempt === MAX_CREATE_ATTEMPTS - 1) {
1585
+ throw storageFailure("issue", error);
1766
1586
  }
1767
- assertValidAgentToolSchema(toolName, field.schema, `${path}.properties.${fieldId}.schema`, visiting);
1768
1587
  }
1769
- break;
1770
1588
  }
1771
- case "valueTypeRef":
1772
- if (typeof schema.valueTypeId !== "string" || !schema.valueTypeId.trim()) {
1773
- throw invalidAgentToolSchema(toolName, path);
1589
+ throw storageFailure("issue");
1590
+ };
1591
+ const listByDefinition = async (definition, input = {}) => {
1592
+ assertInputObject(input, "Shared access list input");
1593
+ managementPrincipal();
1594
+ assertCanManage(runtime, definition.id);
1595
+ const storage = requireShareStorage(runtime);
1596
+ const target = input.target === undefined ? undefined : exactTarget(definition, input.target);
1597
+ try {
1598
+ const result = await storage.list({
1599
+ projectId: runtime.projectId,
1600
+ definitionId: definition.id,
1601
+ ...target === undefined ? {} : { target },
1602
+ includeRevoked: input.includeRevoked,
1603
+ includeExpired: input.includeExpired,
1604
+ now: new Date,
1605
+ limit: input.limit,
1606
+ offset: input.offset
1607
+ });
1608
+ return { ...result, grants: result.grants.map(publicGrant) };
1609
+ } catch (error) {
1610
+ if (error instanceof ShareGrantStorageError && error.code === "invalid_input") {
1611
+ throw new ShareError("invalid_input", error.message, { cause: error });
1612
+ }
1613
+ throw storageFailure("list", error);
1614
+ }
1615
+ };
1616
+ return {
1617
+ listDefinitions: () => definitions.list().filter((definition) => canManage(definition.id)),
1618
+ getDefinitionById: (definitionId) => {
1619
+ const definition = definitions.getById(definitionId);
1620
+ return definition && canManage(definition.id) ? definition : null;
1621
+ },
1622
+ async issue(definition, input) {
1623
+ return issueByDefinition(resolveManageableDefinition(definitionIdFromReference(definition)), input);
1624
+ },
1625
+ async issueById(input) {
1626
+ assertInputObject(input, "Shared access issue input");
1627
+ return issueByDefinition(resolveManageableDefinition(input.definitionId), input);
1628
+ },
1629
+ async list(definition, input) {
1630
+ return listByDefinition(resolveManageableDefinition(definitionIdFromReference(definition)), input);
1631
+ },
1632
+ async listById(input) {
1633
+ assertInputObject(input, "Shared access list input");
1634
+ const definition = resolveManageableDefinition(input.definitionId);
1635
+ const { primaryId, includeRevoked, includeExpired, limit, offset } = input;
1636
+ return listByDefinition(definition, {
1637
+ ...primaryId === undefined ? {} : {
1638
+ target: {
1639
+ objectTypeId: definition.target.objectTypeId,
1640
+ primaryId
1641
+ }
1642
+ },
1643
+ includeRevoked,
1644
+ includeExpired,
1645
+ limit,
1646
+ offset
1647
+ });
1648
+ },
1649
+ revoke: async (grantId) => {
1650
+ const actor = managementPrincipal();
1651
+ const storage = requireShareStorage(runtime);
1652
+ if (typeof grantId !== "string" || !grantId.trim()) {
1653
+ throw new ShareError("invalid_input", "[Sixb] Shared access grant id must not be empty.");
1774
1654
  }
1775
- if (schema._resolved !== undefined) {
1776
- assertValidAgentToolSchema(toolName, schema._resolved, `${path}._resolved`, visiting);
1655
+ let current;
1656
+ try {
1657
+ current = await storage.getById({ projectId: runtime.projectId, id: grantId });
1658
+ } catch (error) {
1659
+ throw storageFailure("load for revocation", error);
1660
+ }
1661
+ if (!current)
1662
+ return null;
1663
+ if (!definitions.getById(current.definitionId) || !canManage(current.definitionId)) {
1664
+ return null;
1665
+ }
1666
+ try {
1667
+ const revoked = await storage.revoke({
1668
+ projectId: runtime.projectId,
1669
+ id: grantId,
1670
+ revokedAt: new Date,
1671
+ revokedBy: actor
1672
+ });
1673
+ return revoked ? publicGrant(revoked) : null;
1674
+ } catch (error) {
1675
+ throw storageFailure("revoke", error);
1777
1676
  }
1778
- break;
1779
- default:
1780
- throw invalidAgentToolSchema(toolName, path);
1781
- }
1782
- visiting.delete(schema);
1783
- }
1784
- function invalidAgentToolSchema(toolName, path) {
1785
- return new AgentDefinitionError(`[Sixb] Agent tool '${toolName}' ${path} must be a valid Sixb schema.`);
1786
- }
1787
- function isAgentToolDefinitionArray(value) {
1788
- if (!Array.isArray(value)) {
1789
- return false;
1790
- }
1791
- for (let index = 0;index < value.length; index += 1) {
1792
- if (!Object.hasOwn(value, index) || !isAgentToolDefinition(value[index])) {
1793
- return false;
1794
1677
  }
1795
- }
1796
- return true;
1678
+ };
1797
1679
  }
1798
- function assertValidAgentToolDefinitions(agentId, tools) {
1799
- const seen = new Set;
1800
- for (let index = 0;index < tools.length; index += 1) {
1801
- const tool = tools[index];
1802
- if (!Object.hasOwn(tools, index) || !isAgentToolDefinition(tool)) {
1803
- throw new AgentDefinitionError(`[Sixb] Agent '${agentId}' tools must contain only agent tool definitions.`);
1804
- }
1805
- assertValidAgentToolName(tool.name);
1806
- assertValidAgentToolDescription(tool.name, tool.description);
1807
- assertValidAgentToolInput(tool.name, tool.input);
1808
- if (seen.has(tool.name)) {
1809
- throw new AgentDefinitionError(`[Sixb] Agent '${agentId}' tools contains duplicate tool name '${tool.name}'.`);
1810
- }
1811
- seen.add(tool.name);
1812
- }
1680
+ function definitionIdFromReference(value) {
1681
+ return typeof value === "object" && value !== null ? value.id : undefined;
1813
1682
  }
1814
- function isValidAgentToolEnumValues(values, valueType) {
1815
- if (!Array.isArray(values) || values.length === 0) {
1816
- return false;
1817
- }
1818
- for (let index = 0;index < values.length; index += 1) {
1819
- if (!Object.hasOwn(values, index)) {
1820
- return false;
1821
- }
1822
- const value = values[index];
1823
- if (valueType === "string" ? typeof value !== "string" : valueType !== "integer" || typeof value !== "number" || !Number.isInteger(value)) {
1824
- return false;
1825
- }
1683
+ function assertInputObject(value, label) {
1684
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1685
+ throw new ShareError("invalid_input", `[Sixb] ${label} must be an object.`);
1826
1686
  }
1827
- return true;
1828
1687
  }
1829
- function deepFreeze(value, seen = new Set) {
1830
- if (value === null || typeof value !== "object" || seen.has(value)) {
1831
- return value;
1688
+ function resolveDefinition(definitions, definitionId) {
1689
+ const id = validDefinitionId(definitionId);
1690
+ const definition = definitions.getById(id);
1691
+ if (!definition) {
1692
+ throw new ShareError("not_found", `[Sixb] Unknown Share definition '${id}'.`);
1832
1693
  }
1833
- seen.add(value);
1834
- for (const key of Reflect.ownKeys(value)) {
1835
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
1836
- if (descriptor && "value" in descriptor) {
1837
- deepFreeze(descriptor.value, seen);
1838
- }
1694
+ return definition;
1695
+ }
1696
+ function validDefinitionId(value) {
1697
+ if (typeof value !== "string" || !value.trim()) {
1698
+ throw new ShareError("invalid_input", "[Sixb] Share definition id must not be empty.");
1839
1699
  }
1840
- return Object.freeze(value);
1700
+ return value;
1841
1701
  }
1842
- function isRecord(value) {
1843
- return typeof value === "object" && value !== null && !Array.isArray(value);
1702
+ function assertCanManage(runtime, shareId) {
1703
+ assertAuthorized(runtime, { kind: "share.manage", shareId });
1844
1704
  }
1845
-
1846
- // src/agents/tool-definition.ts
1847
- var EMPTY_AGENT_TOOLS = Object.freeze([]);
1848
- var normalizedAgentTools = new WeakSet;
1849
- function createAgentToolDefinition(definition) {
1850
- assertValidAgentToolName(definition.name);
1851
- assertValidAgentToolDescription(definition.name, definition.description);
1852
- if (typeof definition.handler !== "function") {
1853
- throw new AgentDefinitionError(`[Sixb] Agent tool '${definition.name}' handler must be a function.`);
1854
- }
1855
- const input = validateAndSnapshotAgentToolInput(definition.name, definition.input);
1856
- const tool = {
1857
- kind: "agentTool",
1858
- name: definition.name,
1859
- description: definition.description,
1860
- input,
1861
- handler: async (context) => {
1862
- const result = await definition.handler(context);
1863
- let snapshot;
1864
- try {
1865
- snapshot = cloneJsonValue(result, "result");
1866
- } catch (cause) {
1867
- throw new AgentToolResultValidationError(definition.name, getInvalidJsonValueReason(result, "result") ?? "result could not be cloned safely", { cause });
1868
- }
1869
- const richResultReason = getInvalidAgentToolResultReason(snapshot);
1870
- if (richResultReason) {
1871
- throw new AgentToolResultValidationError(definition.name, richResultReason);
1872
- }
1873
- return snapshot;
1874
- }
1875
- };
1876
- normalizedAgentTools.add(tool);
1877
- return Object.freeze(tool);
1705
+ function requireShareStorage(runtime) {
1706
+ const storage = runtime.storage.shareGrants;
1707
+ if (!storage) {
1708
+ throw new ShareError("storage_unavailable", "[Sixb] Share grant storage is not configured on this runtime.");
1709
+ }
1710
+ return storage;
1878
1711
  }
1879
- function toolsFromDefinitions(agentId, tools) {
1880
- if (tools === undefined) {
1881
- return EMPTY_AGENT_TOOLS;
1712
+ function exactTarget(definition, value) {
1713
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1714
+ throw new ShareError("invalid_input", "[Sixb] Share target must be an exact object reference.");
1882
1715
  }
1883
- if (!Array.isArray(tools)) {
1884
- throw new AgentDefinitionError(`[Sixb] Agent '${agentId}' tools must be an array of agent tool definitions.`);
1716
+ const objectTypeId = value.objectTypeId;
1717
+ const primaryId = value.primaryId;
1718
+ if (typeof objectTypeId !== "string" || typeof primaryId !== "string" || !primaryId.trim()) {
1719
+ throw new ShareError("invalid_input", "[Sixb] Share target must be an exact object reference.");
1885
1720
  }
1886
- assertValidAgentToolDefinitions(agentId, tools);
1887
- const normalized = [];
1888
- for (const tool of tools) {
1889
- normalized.push(normalizeAgentToolDefinition(tool));
1721
+ if (objectTypeId !== definition.target.objectTypeId) {
1722
+ throw new ShareError("invalid_input", `[Sixb] Share '${definition.id}' targets '${definition.target.objectTypeId}', not '${objectTypeId}'.`);
1890
1723
  }
1891
- return Object.freeze(normalized);
1724
+ return Object.freeze({ objectTypeId, primaryId });
1892
1725
  }
1893
- function normalizeAgentToolDefinition(tool) {
1894
- if (normalizedAgentTools.has(tool)) {
1895
- return tool;
1726
+ function validFutureDate(value, now) {
1727
+ if (!(value instanceof Date) || !Number.isFinite(value.getTime()) || value <= now) {
1728
+ throw new ShareError("invalid_input", "[Sixb] Shared access expiry must be a valid future date.");
1896
1729
  }
1897
- return createAgentToolDefinition({
1898
- name: tool.name,
1899
- description: tool.description,
1900
- input: tool.input,
1901
- handler: (context) => tool.handler(context)
1902
- });
1730
+ return new Date(value);
1903
1731
  }
1904
-
1905
- // src/agents/builders.ts
1906
- function defineAgentTool(name) {
1907
- assertValidAgentToolName(name);
1908
- return {
1909
- description(description) {
1910
- assertValidAgentToolDescription(name, description);
1911
- return {
1912
- input(input) {
1913
- assertValidAgentToolInput(name, input);
1914
- return {
1915
- run(handler) {
1916
- return createAgentToolDefinition({ name, description, input, handler });
1917
- }
1918
- };
1919
- }
1920
- };
1921
- }
1922
- };
1732
+ function sha256(value) {
1733
+ return createHash2("sha256").update(value).digest("hex");
1923
1734
  }
1924
- function defineAgent(id, config) {
1925
- assertNonEmpty(id, "id");
1926
- assertNonEmpty(config.name, "name");
1927
- assertNonEmpty(config.instructions, "instructions");
1928
- if (config.model === undefined || config.model === null) {
1929
- throw new AgentDefinitionError("[Sixb] Agent model is required.");
1930
- }
1931
- assertValidReasoningLevel(config.reasoning);
1932
- assertValidProviderOptions(config.providerOptions);
1933
- const loop = resolveAgentLoopConfig(config.loop);
1934
- const groupIds = groupIdsFromDefinitions(id, config.groups);
1935
- const tools = toolsFromDefinitions(id, config.tools);
1936
- return Object.freeze({
1937
- kind: "agent",
1938
- id,
1939
- name: config.name,
1940
- model: config.model,
1941
- ...config.reasoning !== undefined ? { reasoning: config.reasoning } : {},
1942
- ...config.providerOptions !== undefined ? { providerOptions: config.providerOptions } : {},
1943
- instructions: config.instructions,
1944
- groupIds,
1945
- tools,
1946
- ...config.description !== undefined ? { description: config.description } : {},
1947
- ...loop !== undefined ? { loop } : {}
1948
- });
1735
+ function publicGrant(record) {
1736
+ const {
1737
+ projectId: _projectId,
1738
+ authoritySnapshot: _authoritySnapshot,
1739
+ authorityDigest: _authorityDigest,
1740
+ tokenHash: _tokenHash,
1741
+ ...grant
1742
+ } = record;
1743
+ return structuredClone(grant);
1949
1744
  }
1950
- // src/agents/context-compaction.ts
1951
- var AGENT_CONTEXT_ESTIMATOR_VERSION = 1;
1952
- var CHARS_PER_TOKEN = 4;
1953
- var REQUEST_OVERHEAD_TOKENS = 8;
1954
- var MESSAGE_OVERHEAD_TOKENS = 8;
1955
- var TOOL_OVERHEAD_TOKENS = 16;
1956
- var STEP_OVERHEAD_TOKENS = 2;
1957
- var IMAGE_ALLOWANCE_TOKENS = 1200;
1958
- var FILE_TEXT_INLINE_MAX_BYTES = 50 * 1024;
1959
- var FILE_TEXT_INLINE_TOTAL_MAX_BYTES = 200 * 1024;
1960
- var TOOL_RESULT_SUMMARY_MAX_CHARS = 2000;
1961
- function shouldCompactAgentContext(input) {
1962
- return input.estimatedInputTokens > input.inputBudgetTokens;
1963
- }
1964
- function estimateAgentContextRequestTokens(input) {
1965
- const toolTokens = input.tools.reduce((total, tool) => total + TOOL_OVERHEAD_TOKENS + textTokens(tool.name) + textTokens(tool.description) + textTokens(tool.inputSchema), 0);
1966
- return {
1967
- tokens: REQUEST_OVERHEAD_TOKENS + textTokens(input.systemPrompt) + toolTokens + estimateAgentContextMessagesTokens(input.messages).tokens,
1968
- estimatorVersion: AGENT_CONTEXT_ESTIMATOR_VERSION
1969
- };
1745
+ function storageFailure(operation, cause) {
1746
+ return new ShareError("storage_failure", `[Sixb] Share grant storage failed to ${operation}.`, {
1747
+ cause
1748
+ });
1970
1749
  }
1971
- function estimateAgentContextMessagesTokens(messages) {
1972
- const attachments = { textBytesRemaining: FILE_TEXT_INLINE_TOTAL_MAX_BYTES };
1973
- let tokens = 0;
1974
- for (const message of messages) {
1975
- tokens += estimateMessageTokens(message, attachments);
1976
- }
1977
- return { tokens, estimatorVersion: AGENT_CONTEXT_ESTIMATOR_VERSION };
1978
- }
1979
- function selectAgentContextCompactionBoundary(input) {
1980
- if (input.messages.length < 2)
1981
- return null;
1982
- let retainedTokens = 0;
1983
- let boundaryIndex = null;
1984
- let closestDistance = Number.POSITIVE_INFINITY;
1985
- for (let index = input.messages.length - 1;index > 0; index -= 1) {
1986
- retainedTokens += estimateAgentContextMessagesTokens([input.messages[index]]).tokens;
1987
- if (input.messages[index]?.role !== "user")
1988
- continue;
1989
- const distance = Math.abs(input.keepRecentTokens - retainedTokens);
1990
- if (distance <= closestDistance) {
1991
- boundaryIndex = index;
1992
- closestDistance = distance;
1993
- }
1994
- if (retainedTokens >= input.keepRecentTokens)
1995
- break;
1996
- }
1997
- if (boundaryIndex === null)
1998
- return null;
1999
- const summarizedThroughSeq = input.messages[boundaryIndex - 1]?.seq;
2000
- if (summarizedThroughSeq === undefined)
2001
- return null;
1750
+
1751
+ // src/syncs/execution.ts
1752
+ function createSyncsRuntime(runtime, execution, source) {
1753
+ const authority = resolveRuntimeAuthorizationForProject(runtime);
1754
+ const allowed = (syncId) => isRuntimeAllowed(runtime, { kind: "sync.run", syncId });
1755
+ const visibleIds = () => source.list().filter((sync) => allowed(sync.id)).map((sync) => sync.id);
1756
+ const historyFilterIds = () => authority.type === "unrestricted" ? undefined : authority.type === "principal" ? visibleIds() : [];
2002
1757
  return {
2003
- messagesToSummarize: input.messages.slice(0, boundaryIndex),
2004
- retainedMessages: input.messages.slice(boundaryIndex),
2005
- summarizedThroughSeq
2006
- };
2007
- }
2008
- function serializeAgentMessagesForSummary(messages) {
2009
- const lines = ["<sixb_conversation_history>"];
2010
- for (const message of messages) {
2011
- lines.push(` <message id="${escapeXml2(message.id)}" seq="${message.seq}" role="${message.role}">`);
2012
- message.parts.forEach((part, partIndex) => {
2013
- lines.push(...serializeSummaryPart(message, part, partIndex));
2014
- });
2015
- lines.push(" </message>");
2016
- }
2017
- lines.push("</sixb_conversation_history>");
2018
- return lines.join(`
2019
- `);
2020
- }
2021
- function estimateMessageTokens(message, attachments) {
2022
- let tokens = MESSAGE_OVERHEAD_TOKENS;
2023
- for (const part of message.parts) {
2024
- switch (part.type) {
2025
- case "text":
2026
- case "reasoning":
2027
- tokens += textTokens(part.text);
2028
- break;
2029
- case "step-start":
2030
- tokens += STEP_OVERHEAD_TOKENS;
2031
- break;
2032
- case "context":
2033
- tokens += textTokens(stableJsonStringify(part.context));
2034
- break;
2035
- case "tool-call":
2036
- tokens += TOOL_OVERHEAD_TOKENS + textTokens(part.toolName) + textTokens(stableJsonStringify(part.input)) + (part.state === "output-available" ? textTokens(stableJsonStringify(part.output)) : textTokens(part.errorText));
2037
- break;
2038
- case "file": {
2039
- const file = part.fileRef;
2040
- tokens += textTokens([file.blobId, file.digest, file.fileName, file.mediaType, file.logicalPath].filter((value) => value !== undefined).join(" "));
2041
- if (message.role !== "assistant") {
2042
- if (looksLikeImage(file.mediaType, file.fileName)) {
2043
- tokens += IMAGE_ALLOWANCE_TOKENS;
2044
- } else {
2045
- const inlineBytes = Math.min(file.sizeBytes, FILE_TEXT_INLINE_MAX_BYTES, attachments.textBytesRemaining);
2046
- attachments.textBytesRemaining -= inlineBytes;
2047
- tokens += Math.ceil(inlineBytes / CHARS_PER_TOKEN);
2048
- }
1758
+ list: () => authority.type === "denied" || authority.type === "delegated" ? [] : source.list().filter((sync) => allowed(sync.id)),
1759
+ getById: (syncId) => {
1760
+ if (authority.type === "denied" || authority.type === "delegated")
1761
+ return null;
1762
+ const sync = source.getById(syncId);
1763
+ return sync && allowed(syncId) ? sync : null;
1764
+ },
1765
+ request: async (input) => {
1766
+ assertAuthorized(runtime, { kind: "sync.run", syncId: input.syncId });
1767
+ const sync = source.getById(input.syncId);
1768
+ if (!sync)
1769
+ throw new SyncValidationError(`[Sixb] Unknown sync '${input.syncId}'`);
1770
+ return requestSyncRun(runtime, execution, sync, input);
1771
+ },
1772
+ runs: {
1773
+ getById: async (runId) => {
1774
+ if (authority.type === "denied" || authority.type === "delegated")
1775
+ return null;
1776
+ const run = await runtime.storage.syncRuns?.getById({
1777
+ projectId: runtime.projectId,
1778
+ id: runId
1779
+ }) ?? null;
1780
+ return run && allowed(run.syncId) ? run : null;
1781
+ },
1782
+ list: (input = {}) => {
1783
+ if (authority.type === "denied" || authority.type === "delegated") {
1784
+ return Promise.resolve({ runs: [], hasMore: false, total: 0 });
1785
+ }
1786
+ const storage = runtime.storage.syncRuns;
1787
+ if (!storage)
1788
+ return Promise.resolve({ runs: [], hasMore: false, total: 0 });
1789
+ return storage.list({
1790
+ ...input,
1791
+ syncIds: historyFilterIds(),
1792
+ projectId: runtime.projectId
1793
+ });
1794
+ },
1795
+ listLatest: (syncIds) => {
1796
+ if (authority.type === "denied" || authority.type === "delegated") {
1797
+ return Promise.resolve({ runs: [] });
2049
1798
  }
2050
- break;
1799
+ const storage = runtime.storage.syncRuns;
1800
+ if (!storage || syncIds.length === 0)
1801
+ return Promise.resolve({ runs: [] });
1802
+ const allowedIds = syncIds.filter(allowed);
1803
+ return allowedIds.length === 0 ? Promise.resolve({ runs: [] }) : storage.listLatestBySyncIds({ projectId: runtime.projectId, syncIds: allowedIds });
2051
1804
  }
2052
1805
  }
2053
- }
2054
- return tokens;
2055
- }
2056
- function serializeSummaryPart(message, part, partIndex) {
2057
- const indent = " ";
2058
- switch (part.type) {
2059
- case "text":
2060
- return [`${indent}<text>${escapeXml2(part.text)}</text>`];
2061
- case "reasoning":
2062
- case "step-start":
2063
- return [];
2064
- case "context":
2065
- return part.context.kind === "object" ? [
2066
- `${indent}<object_context origin="${part.origin}" object_type_id="${escapeXml2(part.context.ref.objectTypeId)}" primary_id="${escapeXml2(part.context.ref.primaryId)}" />`
2067
- ] : [
2068
- `${indent}<app_context origin="${part.origin}" id="${escapeXml2(part.context.id)}" label="${escapeXml2(part.context.label)}">`,
2069
- `${indent} <description>${escapeXml2(part.context.description)}</description>`,
2070
- `${indent} <value format="json">${escapeXml2(stableJsonStringify(part.context.value))}</value>`,
2071
- `${indent}</app_context>`
2072
- ];
2073
- case "file": {
2074
- const file = part.fileRef;
2075
- const attributes = [
2076
- `message_id="${escapeXml2(message.id)}"`,
2077
- `part_index="${partIndex}"`,
2078
- `blob_id="${escapeXml2(file.blobId)}"`,
2079
- `digest="${escapeXml2(file.digest)}"`,
2080
- `size_bytes="${file.sizeBytes}"`,
2081
- ...file.fileName === undefined ? [] : [`file_name="${escapeXml2(file.fileName)}"`],
2082
- ...file.mediaType === undefined ? [] : [`media_type="${escapeXml2(file.mediaType)}"`],
2083
- ...file.logicalPath === undefined ? [] : [`logical_path="${escapeXml2(file.logicalPath)}"`]
2084
- ];
2085
- return [`${indent}<file ${attributes.join(" ")} />`];
2086
- }
2087
- case "tool-call": {
2088
- const output = part.state === "output-available" ? truncateToolResult(stableJsonStringify(part.output)) : truncateToolResult(part.errorText);
2089
- return [
2090
- `${indent}<tool_call id="${escapeXml2(part.toolCallId)}" name="${escapeXml2(part.toolName)}" state="${part.state}">`,
2091
- `${indent} <input format="json">${escapeXml2(stableJsonStringify(part.input))}</input>`,
2092
- `${indent} <result>${escapeXml2(output)}</result>`,
2093
- `${indent}</tool_call>`
2094
- ];
2095
- }
2096
- }
2097
- }
2098
- function truncateToolResult(value) {
2099
- if (value.length <= TOOL_RESULT_SUMMARY_MAX_CHARS)
2100
- return value;
2101
- return `${value.slice(0, TOOL_RESULT_SUMMARY_MAX_CHARS)}
2102
- [truncated ${value.length - TOOL_RESULT_SUMMARY_MAX_CHARS} characters]`;
2103
- }
2104
- function looksLikeImage(mediaType, fileName) {
2105
- if (mediaType?.toLowerCase().startsWith("image/"))
2106
- return true;
2107
- return /\.(?:avif|gif|jpe?g|png|webp)$/i.test(fileName ?? "");
2108
- }
2109
- function textTokens(value) {
2110
- return Math.ceil(new TextEncoder().encode(value).byteLength / CHARS_PER_TOKEN);
2111
- }
2112
- function escapeXml2(value) {
2113
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
2114
- }
2115
- // src/agents/thread-context-projection.ts
2116
- function projectAgentThreadModelContext(input) {
2117
- const { checkpoint, messages } = input;
2118
- if (!checkpoint)
2119
- return messages;
2120
- assertConsistentCheckpointProjection(checkpoint, messages);
2121
- return [
2122
- {
2123
- role: "user",
2124
- parts: [{ type: "text", text: serializeThreadSummary(checkpoint.summary) }]
2125
- },
2126
- ...messages
2127
- ];
2128
- }
2129
- function assertConsistentCheckpointProjection(checkpoint, messages) {
2130
- if (checkpoint.summaryFormatVersion !== 1 || checkpoint.summary.trim().length === 0) {
2131
- throw projectionError(checkpoint, "has an invalid summary");
2132
- }
2133
- if (checkpoint.summarizedThroughSeq >= checkpoint.observedHeadSeq) {
2134
- throw projectionError(checkpoint, "does not retain its observed head");
2135
- }
2136
- if (messages.length === 0) {
2137
- throw projectionError(checkpoint, "has no retained messages");
2138
- }
2139
- let expectedSeq = checkpoint.summarizedThroughSeq + 1;
2140
- for (const message of messages) {
2141
- if (message.projectId !== checkpoint.projectId || message.threadId !== checkpoint.threadId) {
2142
- throw projectionError(checkpoint, "contains a message from another thread");
2143
- }
2144
- if (message.seq !== expectedSeq) {
2145
- throw projectionError(checkpoint, `has a sequence gap before message '${message.id}'`);
2146
- }
2147
- expectedSeq += 1;
2148
- }
2149
- if (messages[0]?.role !== "user") {
2150
- throw projectionError(checkpoint, "does not begin at a user turn boundary");
2151
- }
2152
- if ((messages.at(-1)?.seq ?? 0) < checkpoint.observedHeadSeq) {
2153
- throw projectionError(checkpoint, "ends before the checkpoint's observed head");
2154
- }
2155
- }
2156
- function serializeThreadSummary(summary) {
2157
- return [
2158
- "The earlier conversation was compacted into this continuation summary.",
2159
- "",
2160
- "<sixb_thread_summary>",
2161
- escapeXml3(summary),
2162
- "</sixb_thread_summary>"
2163
- ].join(`
2164
- `);
1806
+ };
2165
1807
  }
2166
- function projectionError(checkpoint, detail) {
2167
- return new Error(`[Sixb] Agent context checkpoint '${checkpoint.id}' for thread '${checkpoint.threadId}' ${detail}.`);
1808
+
1809
+ // src/workflows/errors.ts
1810
+ class WorkflowDefinitionError extends Error {
1811
+ name = "WorkflowDefinitionError";
2168
1812
  }
2169
- function escapeXml3(value) {
2170
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
1813
+
1814
+ class WorkflowValidationError extends Error {
1815
+ name = "WorkflowValidationError";
1816
+ cause;
1817
+ constructor(message, options) {
1818
+ super(message);
1819
+ this.cause = options?.cause;
1820
+ }
2171
1821
  }
1822
+
1823
+ // src/workflows/run-dispatch.ts
1824
+ import { randomUUID as randomUUID5 } from "crypto";
1825
+ import { isDeepStrictEqual } from "util";
1826
+
2172
1827
  // src/workflows/validation.ts
2173
- function assertNonEmpty2(value, subject, field) {
1828
+ function assertNonEmpty(value, subject, field) {
2174
1829
  if (!value.trim()) {
2175
1830
  throw new WorkflowDefinitionError(`${subject} ${field} must not be empty.`);
2176
1831
  }
2177
1832
  }
2178
1833
  function isStepDefinition(value) {
2179
- return isRecord2(value) && value.kind === "step" && typeof value.id === "string" && isRecord2(value.input) && isRecord2(value.output) && typeof value.handler === "function";
1834
+ return isRecord(value) && value.kind === "step" && typeof value.id === "string" && isRecord(value.input) && isRecord(value.output) && typeof value.handler === "function";
2180
1835
  }
2181
1836
  function isAgentStepDefinition(value) {
2182
- return isRecord2(value) && value.kind === "agentStep" && typeof value.id === "string" && isAgentDefinition(value.agent) && isRecord2(value.input) && isRecord2(value.output) && typeof value.prompt === "function";
1837
+ return isRecord(value) && value.kind === "agentStep" && typeof value.id === "string" && (value.model === undefined || isLanguageModel(value.model)) && (value.reasoning === undefined || isModelReasoning(value.reasoning)) && typeof value.instructions === "string" && isStringArray(value.groupIds) && isStringArray(value.toolNames) && isRecord(value.input) && isRecord(value.output) && typeof value.prompt === "function";
2183
1838
  }
2184
1839
  function isInterventionDefinition(value) {
2185
- return isRecord2(value) && value.kind === "intervention" && typeof value.id === "string" && isRecord2(value.input) && isRecord2(value.response) && (value.defaults === undefined || typeof value.defaults === "function");
1840
+ return isRecord(value) && value.kind === "intervention" && typeof value.id === "string" && isRecord(value.input) && isRecord(value.response) && (value.defaults === undefined || typeof value.defaults === "function");
2186
1841
  }
2187
1842
  function isWorkflowDefinition(value) {
2188
- return isRecord2(value) && value.kind === "workflow" && typeof value.id === "string" && isRecord2(value.input) && Array.isArray(value.triggers) && Array.isArray(value.nodes);
1843
+ return isRecord(value) && value.kind === "workflow" && typeof value.id === "string" && isRecord(value.input) && Array.isArray(value.triggers) && Array.isArray(value.nodes);
2189
1844
  }
2190
1845
  function validateWorkflowDefinition(value) {
2191
1846
  if (!isWorkflowDefinition(value)) {
2192
1847
  throw new WorkflowDefinitionError("Invalid workflow definition.");
2193
1848
  }
2194
- assertNonEmpty2(value.id, "Workflow", "id");
1849
+ assertNonEmpty(value.id, "Workflow", "id");
2195
1850
  if (value.nodes.length === 0) {
2196
1851
  throw new WorkflowDefinitionError(`Workflow "${value.id}" must contain at least one node.`);
2197
1852
  }
@@ -2219,13 +1874,42 @@ function validateWorkflowsAtStartup(options) {
2219
1874
  if (node.type === "action" && !options.registeredActionIds.has(node.action.id)) {
2220
1875
  throw new WorkflowDefinitionError(`Workflow "${workflow.id}" references unknown action "${node.action.id}". Add it to 'actions' in createSixb() or export it from 'actions/'.`);
2221
1876
  }
2222
- if (node.type === "agent" && !options.registeredAgentIds.has(node.agentStep.agent.id)) {
2223
- throw new WorkflowDefinitionError(`Workflow "${workflow.id}" references unknown agent "${node.agentStep.agent.id}". Add it to 'agents' in createSixb() or export it from 'agents/'.`);
1877
+ if (node.type === "agent") {
1878
+ validateWorkflowAgentStepRuntimeReferences(workflow.id, node.agentStep, options);
2224
1879
  }
2225
1880
  }
2226
1881
  }
2227
1882
  return options.workflows;
2228
1883
  }
1884
+ function validateWorkflowAgentStepGroupReferences(workflows, security) {
1885
+ for (const workflow of workflows) {
1886
+ for (const node of workflow.nodes) {
1887
+ if (node.type !== "agent")
1888
+ continue;
1889
+ for (const groupId of node.agentStep.groupIds) {
1890
+ if (!security.getGroupById(groupId)) {
1891
+ throw new WorkflowDefinitionError(`Workflow "${workflow.id}" agent step "${node.id}" references unknown group "${groupId}". Add it to 'security/groups/' or pass it to createSixb({ groups }).`);
1892
+ }
1893
+ }
1894
+ }
1895
+ }
1896
+ }
1897
+ function validateWorkflowAgentStepRuntimeReferences(workflowId, step, options) {
1898
+ if (step.model === undefined && options.models === undefined) {
1899
+ throw new WorkflowDefinitionError(`Workflow "${workflowId}" agent step "${step.id}" needs a model. Configure 'models.language' or pass 'model' to defineAgentStep().`);
1900
+ }
1901
+ if (step.model !== undefined && options.models !== undefined) {
1902
+ const ref = { provider: step.model.providerId, modelId: step.model.modelId };
1903
+ if (options.models.language.getByRef(ref) === null) {
1904
+ throw new WorkflowDefinitionError(`Workflow "${workflowId}" agent step "${step.id}" uses unknown language model "${ref.provider}/${ref.modelId}". Add it to 'models.language' in createSixb().`);
1905
+ }
1906
+ }
1907
+ for (const toolName of step.toolNames) {
1908
+ if (options.tools.getByName(toolName) === null) {
1909
+ throw new WorkflowDefinitionError(`Workflow "${workflowId}" agent step "${step.id}" uses unknown project tool "${toolName}". Add it to 'tools' in createSixb().`);
1910
+ }
1911
+ }
1912
+ }
2229
1913
  function validateWorkflowInput(params) {
2230
1914
  return validateWorkflowContractRecord({
2231
1915
  shape: params.workflow.input,
@@ -2277,7 +1961,7 @@ function validateWorkflowInterventionDefaultResponse(params) {
2277
1961
  });
2278
1962
  }
2279
1963
  function validateWorkflowTriggerAtStartup(workflowId, trigger, registeredSchedules, inputFields) {
2280
- if (!isRecord2(trigger) || trigger.type !== "schedule") {
1964
+ if (!isRecord(trigger) || trigger.type !== "schedule") {
2281
1965
  throw new WorkflowDefinitionError(`Workflow "${workflowId}" contains an unsupported trigger.`);
2282
1966
  }
2283
1967
  validateScheduleWorkflowTrigger(workflowId, trigger, registeredSchedules, inputFields);
@@ -2301,7 +1985,7 @@ function validateScheduleWorkflowTrigger(workflowId, trigger, registeredSchedule
2301
1985
  }
2302
1986
  }
2303
1987
  function validateWorkflowNodeDefinition(workflowId, node) {
2304
- if (!isRecord2(node)) {
1988
+ if (!isRecord(node)) {
2305
1989
  throw new WorkflowDefinitionError(`Workflow "${workflowId}" contains an invalid node.`);
2306
1990
  }
2307
1991
  if (node.type === "step") {
@@ -2335,10 +2019,39 @@ function validateAgentNodeDefinition(workflowId, node) {
2335
2019
  if (node.id !== node.agentStep.id) {
2336
2020
  throw new WorkflowDefinitionError(`Workflow "${workflowId}" agent node id "${node.id}" does not match agent step definition id "${node.agentStep.id}".`);
2337
2021
  }
2022
+ if (!node.agentStep.instructions.trim()) {
2023
+ throw new WorkflowDefinitionError(`Workflow "${workflowId}" agent step "${node.id}" instructions must not be empty.`);
2024
+ }
2025
+ assertUniqueNonEmptyAgentStepValues(workflowId, node.id, "group", node.agentStep.groupIds);
2026
+ assertUniqueNonEmptyAgentStepValues(workflowId, node.id, "tool", node.agentStep.toolNames);
2338
2027
  if (node.mapper !== undefined && typeof node.mapper !== "function") {
2339
2028
  throw new WorkflowDefinitionError(`Workflow "${workflowId}" agent node "${node.id}" mapper must be a function.`);
2340
2029
  }
2341
2030
  }
2031
+ function assertUniqueNonEmptyAgentStepValues(workflowId, stepId, kind, values) {
2032
+ const seen = new Set;
2033
+ for (const value of values) {
2034
+ if (!value.trim()) {
2035
+ throw new WorkflowDefinitionError(`Workflow "${workflowId}" agent step "${stepId}" has an empty ${kind} id.`);
2036
+ }
2037
+ if (seen.has(value)) {
2038
+ throw new WorkflowDefinitionError(`Workflow "${workflowId}" agent step "${stepId}" has duplicate ${kind} '${value}'.`);
2039
+ }
2040
+ seen.add(value);
2041
+ }
2042
+ }
2043
+ function isLanguageModel(value) {
2044
+ return (typeof value === "object" || typeof value === "function") && value !== null;
2045
+ }
2046
+ function isStringArray(value) {
2047
+ if (!Array.isArray(value))
2048
+ return false;
2049
+ for (let index = 0;index < value.length; index += 1) {
2050
+ if (!Object.hasOwn(value, index) || typeof value[index] !== "string")
2051
+ return false;
2052
+ }
2053
+ return true;
2054
+ }
2342
2055
  function validateWorkflowAgentStepInput(params) {
2343
2056
  return validateWorkflowContractRecord({
2344
2057
  shape: params.agentStep.input,
@@ -2407,7 +2120,7 @@ function validateActionNodeDefinition(workflowId, node) {
2407
2120
  }
2408
2121
  }
2409
2122
  function validateWorkflowContractRecord(params) {
2410
- if (!isRecord2(params.value)) {
2123
+ if (!isRecord(params.value)) {
2411
2124
  throw new WorkflowValidationError(`[Sixb] ${params.path} must be an object`);
2412
2125
  }
2413
2126
  const fieldIds = new Set(Object.keys(params.shape));
@@ -2430,7 +2143,7 @@ function validateWorkflowContractRecord(params) {
2430
2143
  return params.value;
2431
2144
  }
2432
2145
  function validateWorkflowInterventionResponseRecord(params) {
2433
- if (!isRecord2(params.value)) {
2146
+ if (!isRecord(params.value)) {
2434
2147
  throw new WorkflowValidationError(`[Sixb] ${params.path} must be an object`);
2435
2148
  }
2436
2149
  const fieldIds = new Set(Object.keys(params.response));
@@ -2456,7 +2169,7 @@ function validateWorkflowInterventionResponseRecord(params) {
2456
2169
  return params.value;
2457
2170
  }
2458
2171
  function isInterventionFieldConfig(value) {
2459
- return isRecord2(value) && "schema" in value;
2172
+ return isRecord(value) && "schema" in value;
2460
2173
  }
2461
2174
  function interventionResponseFieldSchema(field) {
2462
2175
  return isInterventionFieldConfig(field) ? field.schema : field;
@@ -2473,7 +2186,7 @@ function toWorkflowValidationError(error) {
2473
2186
  }
2474
2187
  return new WorkflowValidationError(String(error), { cause: error });
2475
2188
  }
2476
- function isRecord2(value) {
2189
+ function isRecord(value) {
2477
2190
  return typeof value === "object" && value !== null && !Array.isArray(value);
2478
2191
  }
2479
2192
 
@@ -2588,7 +2301,7 @@ function snapshotWorkflowInterventionResponseRecord(params) {
2588
2301
  }
2589
2302
  function snapshotSchemaOrRefValue(params) {
2590
2303
  if (isObjectRefSchema(params.schema)) {
2591
- if (!isRecord3(params.value)) {
2304
+ if (!isRecord2(params.value)) {
2592
2305
  throw cannotSerialize(params.path);
2593
2306
  }
2594
2307
  return {
@@ -2629,7 +2342,7 @@ function snapshotSchemaValue(params) {
2629
2342
  }));
2630
2343
  }
2631
2344
  if (schema.type === "map") {
2632
- if (!isRecord3(value)) {
2345
+ if (!isRecord2(value)) {
2633
2346
  throw cannotSerialize(path);
2634
2347
  }
2635
2348
  const snapshot = {};
@@ -2644,7 +2357,7 @@ function snapshotSchemaValue(params) {
2644
2357
  return snapshot;
2645
2358
  }
2646
2359
  if (schema.type === "object") {
2647
- if (!isRecord3(value)) {
2360
+ if (!isRecord2(value)) {
2648
2361
  throw cannotSerialize(path);
2649
2362
  }
2650
2363
  const snapshot = {};
@@ -2714,7 +2427,7 @@ function snapshotDate(value, path) {
2714
2427
  function cannotSerialize(path) {
2715
2428
  return new WorkflowValidationError(`[Sixb] ${path} cannot be serialized as workflow IO`);
2716
2429
  }
2717
- function isRecord3(value) {
2430
+ function isRecord2(value) {
2718
2431
  return typeof value === "object" && value !== null && !Array.isArray(value);
2719
2432
  }
2720
2433
 
@@ -2797,7 +2510,7 @@ async function persistWorkflowRun(input, request) {
2797
2510
  assertExistingWorkflowRun(existing, input.workflow.id, request.snapshot);
2798
2511
  return { run: existing, created: false };
2799
2512
  }
2800
- const execution = await input.createExecution(`exec_${randomUUID3()}`, request.runId);
2513
+ const execution = await input.createExecution(`exec_${randomUUID5()}`, request.runId);
2801
2514
  const queuedAt = new Date;
2802
2515
  try {
2803
2516
  return await input.storage.transaction(async (tx) => {
@@ -2904,7 +2617,7 @@ async function failWorkflowRunPublication(input, run, error) {
2904
2617
  }
2905
2618
  function resolveWorkflowRunId(runId) {
2906
2619
  if (runId === undefined)
2907
- return `run_${randomUUID3()}`;
2620
+ return `run_${randomUUID5()}`;
2908
2621
  if (!runId.trim()) {
2909
2622
  throw new WorkflowValidationError("[Sixb] Workflow run id must not be empty");
2910
2623
  }
@@ -2950,6 +2663,10 @@ function assertNonBlank(value, label) {
2950
2663
 
2951
2664
  // src/workflows/request.ts
2952
2665
  async function requestWorkflowRun(runtime, execution, workflow, options = {}) {
2666
+ resolveExecutionScopeAuthorization(runtime.projectId, {
2667
+ execution,
2668
+ authorization: runtime.runtimeAuthorization
2669
+ });
2953
2670
  assertAuthorized(runtime, { kind: "workflow.run", workflowId: workflow.id });
2954
2671
  const requesterGroupIds = execution.requestedBy ? await snapshotRequesterGroupIds({
2955
2672
  auth: runtime.storage.auth,
@@ -2984,15 +2701,31 @@ async function requestWorkflowRun(runtime, execution, workflow, options = {}) {
2984
2701
 
2985
2702
  // src/workflows/execution.ts
2986
2703
  function createWorkflowsRuntime(runtime, execution, source) {
2987
- const allowed = (workflowId) => isAllowed(runtime.authorization, { kind: "workflow.run", workflowId });
2988
- const canAccessHistory = (workflowId) => allowed(workflowId) && (!runtime.authorization || source.getById(workflowId) !== null);
2704
+ const authority = resolveRuntimeAuthorizationForProject(runtime);
2705
+ const allowed = (workflowId) => isRuntimeAllowed(runtime, { kind: "workflow.run", workflowId });
2706
+ const canAccessHistory = (workflowId) => {
2707
+ switch (authority.type) {
2708
+ case "denied":
2709
+ case "delegated":
2710
+ return false;
2711
+ case "unrestricted":
2712
+ return true;
2713
+ case "principal":
2714
+ return allowed(workflowId) && source.getById(workflowId) !== null;
2715
+ }
2716
+ };
2989
2717
  const visibleIds = () => source.list().filter((workflow) => allowed(workflow.id)).map((workflow) => workflow.id);
2718
+ const historyFilterIds = () => authority.type === "unrestricted" ? undefined : authority.type === "principal" ? visibleIds() : [];
2990
2719
  const getVisibleRunRecord = async (runId) => {
2720
+ if (authority.type === "denied" || authority.type === "delegated")
2721
+ return null;
2991
2722
  const run = await runtime.storage.workflowRuns?.getById({
2992
2723
  projectId: runtime.projectId,
2993
2724
  id: runId
2994
2725
  }) ?? null;
2995
- return run && canViewWorkflowRun(runtime.authorization, run) && canAccessHistory(run.workflowId) ? run : null;
2726
+ if (!run || !canAccessHistory(run.workflowId))
2727
+ return null;
2728
+ return authority.type === "unrestricted" || canViewWorkflowRun(authority.context, run) ? run : null;
2996
2729
  };
2997
2730
  const getRun = async (runId) => {
2998
2731
  const run = await getVisibleRunRecord(runId);
@@ -3003,9 +2736,9 @@ function createWorkflowsRuntime(runtime, execution, source) {
3003
2736
  if (!storage || !await getVisibleRunRecord(runId))
3004
2737
  return null;
3005
2738
  const result = await storage.nodes.list({
3006
- projectId: runtime.projectId,
3007
2739
  ...input,
3008
- workflowRunId: runId
2740
+ workflowRunId: runId,
2741
+ projectId: runtime.projectId
3009
2742
  });
3010
2743
  return {
3011
2744
  ...result,
@@ -3013,13 +2746,16 @@ function createWorkflowsRuntime(runtime, execution, source) {
3013
2746
  };
3014
2747
  };
3015
2748
  return {
3016
- list: () => source.list().filter((workflow) => allowed(workflow.id)),
2749
+ list: () => authority.type === "denied" || authority.type === "delegated" ? [] : source.list().filter((workflow) => allowed(workflow.id)),
3017
2750
  getById: (workflowId) => {
2751
+ if (authority.type === "denied" || authority.type === "delegated")
2752
+ return null;
3018
2753
  const workflow = source.getById(workflowId);
3019
2754
  return workflow && allowed(workflowId) ? workflow : null;
3020
2755
  },
3021
2756
  request: (workflow, options) => requestWorkflowRun(runtime, execution, workflow, options),
3022
2757
  requestById: async (input) => {
2758
+ assertAuthorized(runtime, { kind: "workflow.run", workflowId: input.workflowId });
3023
2759
  const workflow = source.getById(input.workflowId);
3024
2760
  if (!workflow) {
3025
2761
  throw new WorkflowValidationError(`[Sixb] Unknown workflow '${input.workflowId}'`);
@@ -3029,13 +2765,16 @@ function createWorkflowsRuntime(runtime, execution, source) {
3029
2765
  runs: {
3030
2766
  getById: getRun,
3031
2767
  list: async (input = {}) => {
2768
+ if (authority.type === "denied" || authority.type === "delegated") {
2769
+ return { runs: [], hasMore: false, total: 0 };
2770
+ }
3032
2771
  const storage = runtime.storage.workflowRuns;
3033
2772
  if (!storage)
3034
2773
  return { runs: [], hasMore: false, total: 0 };
3035
2774
  const result = await storage.list({
3036
- projectId: runtime.projectId,
3037
2775
  ...input,
3038
- workflowIds: runtime.authorization ? visibleIds() : undefined
2776
+ workflowIds: historyFilterIds(),
2777
+ projectId: runtime.projectId
3039
2778
  });
3040
2779
  return {
3041
2780
  ...result,
@@ -3043,6 +2782,9 @@ function createWorkflowsRuntime(runtime, execution, source) {
3043
2782
  };
3044
2783
  },
3045
2784
  listLatest: async (workflowIds) => {
2785
+ if (authority.type === "denied" || authority.type === "delegated") {
2786
+ return { runs: [] };
2787
+ }
3046
2788
  const storage = runtime.storage.workflowRuns;
3047
2789
  if (!storage || workflowIds.length === 0)
3048
2790
  return { runs: [] };
@@ -3061,20 +2803,27 @@ function createWorkflowsRuntime(runtime, execution, source) {
3061
2803
  },
3062
2804
  interventions: {
3063
2805
  getById: async (interventionId) => {
2806
+ if (authority.type === "denied" || authority.type === "delegated")
2807
+ return null;
3064
2808
  const intervention = await runtime.storage.workflowInterventions?.getById({
3065
2809
  projectId: runtime.projectId,
3066
2810
  id: interventionId
3067
2811
  }) ?? null;
3068
- return intervention && canViewWorkflowIntervention(runtime.authorization, intervention) && canAccessHistory(intervention.workflowId) ? intervention : null;
2812
+ if (!intervention || !canAccessHistory(intervention.workflowId))
2813
+ return null;
2814
+ return authority.type === "unrestricted" || canViewWorkflowIntervention(authority.context, intervention) ? intervention : null;
3069
2815
  },
3070
2816
  list: (input = {}) => {
2817
+ if (authority.type === "denied" || authority.type === "delegated") {
2818
+ return Promise.resolve({ interventions: [], hasMore: false, total: 0 });
2819
+ }
3071
2820
  const storage = runtime.storage.workflowInterventions;
3072
2821
  if (!storage)
3073
2822
  return Promise.resolve({ interventions: [], hasMore: false, total: 0 });
3074
2823
  return storage.list({
3075
- projectId: runtime.projectId,
3076
2824
  ...input,
3077
- workflowIds: runtime.authorization ? visibleIds() : undefined
2825
+ workflowIds: historyFilterIds(),
2826
+ projectId: runtime.projectId
3078
2827
  });
3079
2828
  }
3080
2829
  }
@@ -3121,7 +2870,6 @@ function toWorkflowAgentNodeRunView(execution, usage, cost) {
3121
2870
  projectId: execution.projectId,
3122
2871
  nodeRunId: execution.nodeRunId,
3123
2872
  executionId: execution.executionId,
3124
- agentId: execution.agentId,
3125
2873
  status: execution.status,
3126
2874
  prompt: execution.prompt,
3127
2875
  modelId: execution.modelId,
@@ -3154,6 +2902,14 @@ async function attachRequestedBy(runtime, run) {
3154
2902
  // src/runtime/sixb.ts
3155
2903
  var boundSixbInstances = new WeakSet;
3156
2904
  function createBoundSixb(runtime, dependencies, execution) {
2905
+ resolveExecutionScopeAuthorization(runtime.projectId, {
2906
+ execution,
2907
+ authorization: runtime.runtimeAuthorization
2908
+ });
2909
+ assertAuthorizedObjectReaderBinding({
2910
+ reader: runtime.objectReader,
2911
+ scope: { execution, authorization: runtime.runtimeAuthorization }
2912
+ });
3157
2913
  const sixb = {
3158
2914
  execution,
3159
2915
  ...createExecutionFacades(runtime, execution, dependencies)
@@ -3172,24 +2928,29 @@ function createExecutionFacades(runtime, execution, dependencies) {
3172
2928
  return {
3173
2929
  objects: createObjectsRuntime(runtime, execution),
3174
2930
  actions: createActionsRuntime(runtime, execution),
3175
- datasets: createDatasetsRuntime(runtime, dependencies.definitions.datasets),
2931
+ datasets: createDatasetsRuntime(runtime, execution, dependencies.definitions.datasets, dependencies.lakeStorage, dependencies.blobStorage),
3176
2932
  workflows: createWorkflowsRuntime(runtime, execution, dependencies.definitions.workflows),
3177
2933
  syncs: createSyncsRuntime(runtime, execution, dependencies.definitions.syncs),
3178
2934
  pipelines: createPipelinesRuntime(runtime, execution, dependencies.definitions.pipelines),
3179
2935
  projections: createProjectionsRuntime(runtime, dependencies.definitions.projections),
3180
2936
  rules: createRulesRuntime(runtime, dependencies.definitions.rules),
3181
- agents: createAgentsRuntime(runtime, execution, dependencies.definitions.agents, dependencies.definitions.security),
2937
+ agent: createAgentRuntime(runtime, execution, dependencies.definitions.models),
2938
+ aiUsage: createAiUsageRuntime(runtime, dependencies.definitions.security),
3182
2939
  events: createEventsRuntime(runtime),
3183
2940
  logs: createLogsRuntime(runtime, dependencies.logging),
3184
- schedules: createSchedulesRuntime(dependencies.definitions.schedules),
2941
+ schedules: createSchedulesRuntime(runtime, dependencies.definitions.schedules),
2942
+ shares: createSharesRuntime(runtime, execution, dependencies.definitions.shares),
3185
2943
  connector: createConnectorRuntime(runtime, execution, dependencies.connectorService),
3186
2944
  blobs: createBlobsRuntime(runtime, execution, dependencies.blobStorage)
3187
2945
  };
3188
2946
  }
3189
-
3190
2947
  // src/execution/agent.ts
2948
+ function canInheritAgentRequestAuthorization(authorization) {
2949
+ const ref = getAuthorizationRef(authorization);
2950
+ return ref.type === "disabled" || ref.type === "principal" && ref.principal.type === "user" && ref.credential !== undefined;
2951
+ }
3191
2952
  function createAgentExecutionRecord(input) {
3192
- assertAgentPrincipal(input.agentId, input.principal);
2953
+ assertAgentPrincipal(input.actorId, input.principal);
3193
2954
  return {
3194
2955
  id: input.id,
3195
2956
  projectId: input.parent.projectId,
@@ -3203,6 +2964,21 @@ function createAgentExecutionRecord(input) {
3203
2964
  }
3204
2965
  };
3205
2966
  }
2967
+ function createInheritedAgentExecutionRecord(input) {
2968
+ const authority = input.parent.authorizationRef;
2969
+ if (authority.type !== "disabled" && !(authority.type === "principal" && authority.principal.type === "user" && authority.credential !== undefined)) {
2970
+ throw new ExecutionStorageError("invalid_input", `[Sixb] Agent run '${input.runId}' requires inheritable user or auth-disabled authority.`);
2971
+ }
2972
+ return {
2973
+ id: input.id,
2974
+ projectId: input.parent.projectId,
2975
+ ...input.parent.requestedBy === undefined ? {} : { requestedBy: structuredClone(input.parent.requestedBy) },
2976
+ executor: { type: "agent", runId: input.runId },
2977
+ source: { type: "execution", executionId: input.parent.id },
2978
+ correlationId: input.parent.correlationId,
2979
+ authorizationRef: structuredClone(authority)
2980
+ };
2981
+ }
3206
2982
  function bindDurableAgentExecution(host, input) {
3207
2983
  const scope = restoreAgentExecutionScope(input);
3208
2984
  const sixb = host.withScope(scope);
@@ -3217,38 +2993,65 @@ function restoreAgentExecutionScope(input) {
3217
2993
  id: input.execution.id,
3218
2994
  projectId: input.execution.projectId,
3219
2995
  ...input.execution.requestedBy === undefined ? {} : { requestedBy: Object.freeze(structuredClone(input.execution.requestedBy)) },
3220
- executor: Object.freeze({ type: "agent", agentId: input.agentId, runId: input.runId }),
2996
+ executor: Object.freeze({
2997
+ type: "agent",
2998
+ ...input.actorId === undefined ? {} : { actorId: input.actorId },
2999
+ runId: input.runId
3000
+ }),
3221
3001
  source: Object.freeze(structuredClone(input.execution.source)),
3222
3002
  correlationId: input.execution.correlationId
3223
3003
  });
3224
3004
  return Object.freeze({
3225
3005
  execution: context,
3226
3006
  authorization: createAgentRuntimeAuthorization({
3227
- projectId: input.execution.projectId,
3228
- context: input.authorization,
3229
- executionId: input.execution.id,
3230
- agentId: input.agentId,
3231
- runId: input.runId
3007
+ execution: context,
3008
+ authority: input.authorization.type === "principal" ? {
3009
+ type: "principal",
3010
+ context: input.authorization.context,
3011
+ ...input.execution.authorizationRef.type === "principal" && input.execution.authorizationRef.credential !== undefined ? { credential: input.execution.authorizationRef.credential } : {}
3012
+ } : { type: "disabled" }
3232
3013
  })
3233
3014
  });
3234
3015
  }
3235
3016
  function assertAgentExecutionRecord(input) {
3236
3017
  const authority = input.execution.authorizationRef;
3237
- if (input.execution.executor.type !== "agent" || input.execution.executor.runId !== input.runId || input.execution.source.type !== "execution" || authority.type !== "principal" || authority.principal.type !== "serviceAccount" || input.authorization.principal.type !== "serviceAccount" || authority.principal.id !== input.authorization.principal.id || authority.credential !== undefined) {
3018
+ if (input.execution.executor.type !== "agent" || input.execution.executor.runId !== input.runId || input.execution.source.type !== "execution") {
3019
+ invalidAgentExecution(input.execution.id, input.runId);
3020
+ }
3021
+ if (input.authorization.type === "disabled" || input.authorization.context.principal.type === "user") {
3022
+ assertInheritedAgentAuthority(input.execution, input.runId, input.authorization);
3023
+ return;
3024
+ }
3025
+ if (input.authorization.type !== "principal" || authority.type !== "principal" || authority.principal.type !== "serviceAccount" || input.authorization.context.principal.type !== "serviceAccount" || authority.principal.id !== input.authorization.context.principal.id || authority.credential !== undefined) {
3026
+ invalidAgentExecution(input.execution.id, input.runId);
3027
+ }
3028
+ if (input.actorId === undefined) {
3238
3029
  invalidAgentExecution(input.execution.id, input.runId);
3239
3030
  }
3240
- assertAgentPrincipal(input.agentId, authority.principal);
3031
+ assertAgentPrincipal(input.actorId, authority.principal);
3032
+ }
3033
+ function assertInheritedAgentAuthority(execution, runId, authorization) {
3034
+ const authority = execution.authorizationRef;
3035
+ if (authorization.type === "disabled") {
3036
+ if (authority.type !== "disabled")
3037
+ invalidAgentExecution(execution.id, runId);
3038
+ return;
3039
+ }
3040
+ const principal = authorization.context.principal;
3041
+ if (authority.type !== "principal" || authority.principal.type !== "user" || principal.type !== "user" || authority.principal.id !== principal.id || authority.credential === undefined || (authority.credential.type === "session" ? authorization.context.sessionId !== authority.credential.id : authorization.context.sessionId !== undefined)) {
3042
+ invalidAgentExecution(execution.id, runId);
3043
+ }
3241
3044
  }
3242
- function assertAgentPrincipal(agentId, principal) {
3243
- const expectedId = agentServiceAccountId(agentId);
3045
+ function assertAgentPrincipal(actorId, principal) {
3046
+ const expectedId = agentServiceAccountId(actorId);
3244
3047
  if (principal.id !== expectedId) {
3245
- throw new ExecutionStorageError("invalid_input", `[Sixb] Agent '${agentId}' execution authority must reference service account '${expectedId}'.`);
3048
+ throw new ExecutionStorageError("invalid_input", `[Sixb] Agent '${actorId}' execution authority must reference service account '${expectedId}'.`);
3246
3049
  }
3247
3050
  }
3248
3051
  function invalidAgentExecution(executionId, runId) {
3249
3052
  throw new ExecutionStorageError("invalid_input", `[Sixb] Execution '${executionId}' does not authorize Agent run '${runId}'.`);
3250
3053
  }
3251
3054
 
3252
- export { serializeAgentContextForModel, isAgentToolResult, omitUndefinedObjectProperties, fromAiSdk, toUiMessage, toModelMessages, AGENT_API_GATEWAY_PREFIX, AGENT_API_ROUTES, createAgentApiGatewayCapability, isValidAgentApiGatewayCapability, isAllowedAgentApiRequest, AGENT_REASONING_LEVELS, AGENT_RESERVED_TOOL_NAMES, isAgentDefinition, isAgentToolDefinition, validateAndNormalizeAgentToolInput, validateAgentToolsAtStartup, validateAgentGroupReferences, defineAgentTool, defineAgent, AGENT_CONTEXT_ESTIMATOR_VERSION, shouldCompactAgentContext, estimateAgentContextRequestTokens, estimateAgentContextMessagesTokens, selectAgentContextCompactionBoundary, serializeAgentMessagesForSummary, resolveAgentContextParts, agentRunQueueJobId, workflowAgentNodeQueueJobId, dispatchQueuedAgentRuns, createAgentThreadId, createAgentRunId, createAgentMessageId, agentContextCheckpointId, createAgentRunExecutionToken, WorkflowDefinitionError, WorkflowValidationError, assertNonEmpty2 as assertNonEmpty, isStepDefinition, isAgentStepDefinition, isInterventionDefinition, isWorkflowDefinition, validateWorkflowDefinition, validateWorkflowsAtStartup, validateWorkflowInput, validateWorkflowStepInput, validateWorkflowStepOutput, validateWorkflowInterventionInput, validateWorkflowInterventionResponse, validateWorkflowInterventionDefaultResponse, validateWorkflowAgentStepInput, validateWorkflowAgentStepOutput, snapshotWorkflowAgentStepInput, snapshotWorkflowAgentStepOutput, snapshotWorkflowInput, snapshotWorkflowStepInput, snapshotWorkflowStepOutput, snapshotWorkflowInterventionInput, snapshotWorkflowInterventionResponse, snapshotWorkflowInterventionDefaultResponse, snapshotWorkflowActionInput, WorkflowRunDispatcher, requestWorkflowRun, createBoundSixb, isBoundSixb, createAgentExecutionRecord, bindDurableAgentExecution, restoreAgentExecutionScope, assertAgentExecutionRecord, requestAgentRun, retryAgentRun, projectAgentThreadModelContext };
3055
+ export { resolveAgentContextParts, agentRunQueueJobId, subagentRunQueueJobId, workflowAgentNodeQueueJobId, dispatchQueuedAgentRuns, dispatchQueuedSubagentRuns, createAgentThreadId, createAgentRunId, createSubagentRunId, createSubagentExecutionId, createAgentMessageId, agentContextCheckpointId, createAgentRunExecutionToken, assertNoAgentDefinitions, ShareError, WorkflowDefinitionError, WorkflowValidationError, assertNonEmpty, isStepDefinition, isAgentStepDefinition, isInterventionDefinition, isWorkflowDefinition, validateWorkflowDefinition, validateWorkflowsAtStartup, validateWorkflowAgentStepGroupReferences, validateWorkflowInput, validateWorkflowStepInput, validateWorkflowStepOutput, validateWorkflowInterventionInput, validateWorkflowInterventionResponse, validateWorkflowInterventionDefaultResponse, validateWorkflowAgentStepInput, validateWorkflowAgentStepOutput, snapshotWorkflowAgentStepInput, snapshotWorkflowAgentStepOutput, snapshotWorkflowInput, snapshotWorkflowStepInput, snapshotWorkflowStepOutput, snapshotWorkflowInterventionInput, snapshotWorkflowInterventionResponse, snapshotWorkflowInterventionDefaultResponse, snapshotWorkflowActionInput, WorkflowRunDispatcher, requestWorkflowRun, createBoundSixb, isBoundSixb, canInheritAgentRequestAuthorization, createAgentExecutionRecord, createInheritedAgentExecutionRecord, bindDurableAgentExecution, restoreAgentExecutionScope, assertAgentExecutionRecord, requestAgentRun, retryAgentRun };
3253
3056
 
3254
- //# debugId=E5777634D231818464756E2164756E21
3057
+ //# debugId=3C841C41C07F660564756E2164756E21