@sixb/core 0.1.26 → 0.2.1

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 (617) hide show
  1. package/dist/actions/index.js +47 -47
  2. package/dist/actions/request.d.ts.map +1 -1
  3. package/dist/actions/run/context.d.ts +1 -0
  4. package/dist/actions/run/context.d.ts.map +1 -1
  5. package/dist/actions/run/execute.d.ts +3 -0
  6. package/dist/actions/run/execute.d.ts.map +1 -1
  7. package/dist/actions/run/executor.d.ts +3 -0
  8. package/dist/actions/run/executor.d.ts.map +1 -1
  9. package/dist/actions/run/types.d.ts +5 -0
  10. package/dist/actions/run/types.d.ts.map +1 -1
  11. package/dist/actions/types/context.d.ts +11 -0
  12. package/dist/actions/types/context.d.ts.map +1 -1
  13. package/dist/agents/adapters.d.ts +30 -4
  14. package/dist/agents/adapters.d.ts.map +1 -1
  15. package/dist/agents/approvals.d.ts +8 -0
  16. package/dist/agents/approvals.d.ts.map +1 -1
  17. package/dist/agents/context-budget.d.ts +48 -0
  18. package/dist/agents/context-budget.d.ts.map +1 -0
  19. package/dist/agents/context-compaction.d.ts +89 -9
  20. package/dist/agents/context-compaction.d.ts.map +1 -1
  21. package/dist/agents/context-files.d.ts +12 -0
  22. package/dist/agents/context-files.d.ts.map +1 -0
  23. package/dist/agents/context-parts.d.ts +41 -0
  24. package/dist/agents/context-parts.d.ts.map +1 -0
  25. package/dist/agents/context-request.d.ts +47 -0
  26. package/dist/agents/context-request.d.ts.map +1 -0
  27. package/dist/agents/context-token-rate.d.ts +98 -0
  28. package/dist/agents/context-token-rate.d.ts.map +1 -0
  29. package/dist/agents/context-use.d.ts +51 -0
  30. package/dist/agents/context-use.d.ts.map +1 -0
  31. package/dist/agents/dispatch.d.ts.map +1 -1
  32. package/dist/agents/execution.d.ts +13 -1
  33. package/dist/agents/execution.d.ts.map +1 -1
  34. package/dist/agents/index.d.ts +21 -7
  35. package/dist/agents/index.d.ts.map +1 -1
  36. package/dist/agents/index.js +109 -55
  37. package/dist/agents/index.js.map +1 -1
  38. package/dist/agents/inline-images.d.ts +17 -0
  39. package/dist/agents/inline-images.d.ts.map +1 -0
  40. package/dist/agents/message.d.ts +55 -0
  41. package/dist/agents/message.d.ts.map +1 -1
  42. package/dist/agents/model-loop.d.ts +23 -3
  43. package/dist/agents/model-loop.d.ts.map +1 -1
  44. package/dist/agents/request.d.ts +6 -1
  45. package/dist/agents/request.d.ts.map +1 -1
  46. package/dist/agents/run-events.d.ts +3 -2
  47. package/dist/agents/run-events.d.ts.map +1 -1
  48. package/dist/agents/run-plan.d.ts +12 -2
  49. package/dist/agents/run-plan.d.ts.map +1 -1
  50. package/dist/agents/run-session-http.d.ts +6 -3
  51. package/dist/agents/run-session-http.d.ts.map +1 -1
  52. package/dist/agents/run-session-serve.d.ts +18 -2
  53. package/dist/agents/run-session-serve.d.ts.map +1 -1
  54. package/dist/agents/run-session.d.ts +3 -1
  55. package/dist/agents/run-session.d.ts.map +1 -1
  56. package/dist/agents/run-tools.d.ts +7 -0
  57. package/dist/agents/run-tools.d.ts.map +1 -1
  58. package/dist/agents/run-turn.d.ts +39 -4
  59. package/dist/agents/run-turn.d.ts.map +1 -1
  60. package/dist/agents/skills.d.ts +9 -2
  61. package/dist/agents/skills.d.ts.map +1 -1
  62. package/dist/agents/step-limits.d.ts +18 -0
  63. package/dist/agents/step-limits.d.ts.map +1 -0
  64. package/dist/agents/streams/index.d.ts +1 -1
  65. package/dist/agents/streams/index.d.ts.map +1 -1
  66. package/dist/agents/streams/index.js +2 -2
  67. package/dist/agents/streams/internal.d.ts +1 -1
  68. package/dist/agents/streams/internal.d.ts.map +1 -1
  69. package/dist/agents/streams/internal.js +7 -3
  70. package/dist/agents/streams/internal.js.map +1 -1
  71. package/dist/agents/streams/protocol.d.ts +36 -1
  72. package/dist/agents/streams/protocol.d.ts.map +1 -1
  73. package/dist/agents/thread-context-projection.d.ts +10 -0
  74. package/dist/agents/thread-context-projection.d.ts.map +1 -1
  75. package/dist/agents/tool-files.d.ts +22 -0
  76. package/dist/agents/tool-files.d.ts.map +1 -1
  77. package/dist/artifacts/publish/index.js +26 -26
  78. package/dist/auth/index.js +12 -12
  79. package/dist/auth/index.js.map +1 -1
  80. package/dist/auth/runtime.d.ts +2 -0
  81. package/dist/auth/runtime.d.ts.map +1 -1
  82. package/dist/auth/types.d.ts +5 -0
  83. package/dist/auth/types.d.ts.map +1 -1
  84. package/dist/authorization/decision.d.ts +2 -0
  85. package/dist/authorization/decision.d.ts.map +1 -1
  86. package/dist/authorization/grant-kinds.d.ts +2 -2
  87. package/dist/authorization/grant-kinds.d.ts.map +1 -1
  88. package/dist/authorization/index.d.ts +1 -1
  89. package/dist/authorization/index.d.ts.map +1 -1
  90. package/dist/authorization/index.js +7 -5
  91. package/dist/authorization/index.js.map +1 -1
  92. package/dist/authorization/run-visibility.d.ts +17 -0
  93. package/dist/authorization/run-visibility.d.ts.map +1 -1
  94. package/dist/bootstrap/index.js +55 -55
  95. package/dist/{chunk-t3brw0wd.js → chunk-0g5nyx0k.js} +181 -30
  96. package/dist/chunk-0g5nyx0k.js.map +14 -0
  97. package/dist/{chunk-fakrpfy3.js → chunk-0k1h5hmr.js} +2 -1
  98. package/dist/{chunk-fakrpfy3.js.map → chunk-0k1h5hmr.js.map} +3 -3
  99. package/dist/{chunk-c0vk1djt.js → chunk-165c9wm6.js} +1 -1
  100. package/dist/{chunk-8mb7mt8n.js → chunk-21q0j5f2.js} +2 -2
  101. package/dist/{chunk-hn76sanm.js → chunk-23s66j86.js} +1 -1
  102. package/dist/{chunk-h1na2cxc.js → chunk-2g0r46hy.js} +2 -2
  103. package/dist/{chunk-8v6xzwgr.js → chunk-3x3bebz7.js} +95 -19
  104. package/dist/{chunk-8v6xzwgr.js.map → chunk-3x3bebz7.js.map} +10 -9
  105. package/dist/{chunk-tdxfsg1c.js → chunk-47e09r7z.js} +2 -2
  106. package/dist/{chunk-73j0v4qv.js → chunk-4zm1k3xj.js} +14 -2
  107. package/dist/{chunk-73j0v4qv.js.map → chunk-4zm1k3xj.js.map} +3 -3
  108. package/dist/{chunk-fntqb7qy.js → chunk-57g0215c.js} +1 -1
  109. package/dist/{chunk-npcr0228.js → chunk-5kyvrtjh.js} +1 -1
  110. package/dist/{chunk-zhh1jd89.js → chunk-5taem5aw.js} +1 -1
  111. package/dist/{chunk-tnhqtfea.js → chunk-6b61s40c.js} +1 -1
  112. package/dist/{chunk-4ymrcdbm.js → chunk-7hd2ez3q.js} +1 -1
  113. package/dist/{chunk-315qye3g.js → chunk-80nh73br.js} +1 -1
  114. package/dist/{chunk-b6ghvap7.js → chunk-8yzhjawq.js} +7 -7
  115. package/dist/{chunk-2vjnyz1s.js → chunk-9rh8ncs5.js} +2 -2
  116. package/dist/{chunk-pgrf64hp.js → chunk-agn8d8ys.js} +1 -1
  117. package/dist/{chunk-6qn7nmd3.js → chunk-aqyjb86c.js} +9 -9
  118. package/dist/{chunk-4jq2bg8t.js → chunk-ax10ft8d.js} +6 -6
  119. package/dist/{chunk-mqx25wwh.js → chunk-b7a97n8b.js} +12 -10
  120. package/dist/{chunk-mqx25wwh.js.map → chunk-b7a97n8b.js.map} +3 -3
  121. package/dist/{chunk-8v5a54qz.js → chunk-cb21tx14.js} +165 -42
  122. package/dist/{chunk-8v5a54qz.js.map → chunk-cb21tx14.js.map} +12 -12
  123. package/dist/{chunk-7ex2p3zp.js → chunk-cgznz22f.js} +2 -2
  124. package/dist/{chunk-vhbw5sqm.js → chunk-d7v97qxq.js} +7 -1
  125. package/dist/chunk-d7v97qxq.js.map +10 -0
  126. package/dist/chunk-de5sfbc3.js +3 -0
  127. package/dist/{chunk-ratkv4zc.js.map → chunk-de5sfbc3.js.map} +1 -1
  128. package/dist/{chunk-qgvbxfqv.js → chunk-djs3hw9p.js} +1 -1
  129. package/dist/{chunk-ye5c8016.js → chunk-dz7a4t3a.js} +26 -5
  130. package/dist/{chunk-ye5c8016.js.map → chunk-dz7a4t3a.js.map} +4 -4
  131. package/dist/{chunk-fe8zwt8b.js → chunk-e6xgz4h4.js} +22 -4
  132. package/dist/{chunk-fe8zwt8b.js.map → chunk-e6xgz4h4.js.map} +5 -3
  133. package/dist/{chunk-dgtd0836.js → chunk-e7v3trpz.js} +1 -1
  134. package/dist/{chunk-z9mg7wya.js → chunk-edx8xcsm.js} +111 -11
  135. package/dist/chunk-edx8xcsm.js.map +13 -0
  136. package/dist/{chunk-0bc3w0zq.js → chunk-epyfm23v.js} +38 -11
  137. package/dist/chunk-epyfm23v.js.map +11 -0
  138. package/dist/{chunk-zbc929zg.js → chunk-escedwyt.js} +9 -1
  139. package/dist/{chunk-zbc929zg.js.map → chunk-escedwyt.js.map} +3 -3
  140. package/dist/{chunk-jt3r6thp.js → chunk-fg1db9xx.js} +46 -6
  141. package/dist/chunk-fg1db9xx.js.map +10 -0
  142. package/dist/{chunk-73v685wb.js → chunk-frsz8wxd.js} +4 -4
  143. package/dist/{chunk-73v685wb.js.map → chunk-frsz8wxd.js.map} +3 -3
  144. package/dist/{chunk-axb4ss9a.js → chunk-h05rg3bx.js} +43 -12
  145. package/dist/chunk-h05rg3bx.js.map +12 -0
  146. package/dist/{chunk-06sg8s4z.js → chunk-j1ny5fwh.js} +37 -13
  147. package/dist/chunk-j1ny5fwh.js.map +15 -0
  148. package/dist/{chunk-59kf345w.js → chunk-jbw70d6t.js} +2 -2
  149. package/dist/{chunk-cbcgs9f7.js → chunk-jftd33rc.js} +21 -21
  150. package/dist/chunk-jftd33rc.js.map +11 -0
  151. package/dist/{chunk-78ymxrn0.js → chunk-jhbk10wf.js} +1 -1
  152. package/dist/{chunk-phm3c7b9.js → chunk-jjmggm9a.js} +2 -2
  153. package/dist/{chunk-18sk89cg.js → chunk-jk97v21j.js} +7 -2
  154. package/dist/chunk-jk97v21j.js.map +10 -0
  155. package/dist/chunk-kcqpk9w1.js.map +2 -2
  156. package/dist/{chunk-xm8qgbqm.js → chunk-ks87m383.js} +55 -45
  157. package/dist/{chunk-xm8qgbqm.js.map → chunk-ks87m383.js.map} +5 -5
  158. package/dist/{chunk-ft3w5ahs.js → chunk-m3qe54bb.js} +1 -1
  159. package/dist/{chunk-y7j6x4h0.js → chunk-neftrg0n.js} +3 -3
  160. package/dist/{chunk-07kkp2e1.js → chunk-nghc7eq0.js} +2 -2
  161. package/dist/{chunk-vx4e4zv4.js → chunk-nqnfz3jg.js} +4 -4
  162. package/dist/{chunk-1xvqgg88.js → chunk-nz7815t3.js} +18 -2
  163. package/dist/chunk-nz7815t3.js.map +14 -0
  164. package/dist/{chunk-e24fvw8g.js → chunk-qbrmpgvv.js} +1 -1
  165. package/dist/{chunk-dp0cdtj2.js → chunk-qsg8rw04.js} +2 -2
  166. package/dist/{chunk-0kk2wt0h.js → chunk-r1cxq7vv.js} +2 -2
  167. package/dist/{chunk-yd00vzqr.js → chunk-ratj7t3t.js} +1009 -354
  168. package/dist/chunk-ratj7t3t.js.map +45 -0
  169. package/dist/{chunk-yavhtnac.js → chunk-rjeeyssy.js} +89 -43
  170. package/dist/{chunk-yavhtnac.js.map → chunk-rjeeyssy.js.map} +3 -3
  171. package/dist/{chunk-kyjcwqz6.js → chunk-rtkqczbr.js} +3 -1
  172. package/dist/{chunk-kyjcwqz6.js.map → chunk-rtkqczbr.js.map} +3 -3
  173. package/dist/{chunk-9mab3dvg.js → chunk-s038wa5v.js} +9 -1
  174. package/dist/{chunk-9mab3dvg.js.map → chunk-s038wa5v.js.map} +3 -3
  175. package/dist/{chunk-2adz0h75.js → chunk-s7xqfxs9.js} +35 -3
  176. package/dist/chunk-s7xqfxs9.js.map +11 -0
  177. package/dist/{chunk-g663fahq.js → chunk-scyq22td.js} +1 -1
  178. package/dist/{chunk-8xnz9vvp.js → chunk-t5daew4g.js} +23 -19
  179. package/dist/chunk-t5daew4g.js.map +12 -0
  180. package/dist/{chunk-7wn5z7mq.js → chunk-t9xyr7y9.js} +5 -5
  181. package/dist/{chunk-qst145py.js → chunk-tvbmh7tj.js} +24 -14
  182. package/dist/chunk-tvbmh7tj.js.map +18 -0
  183. package/dist/{chunk-pdt5cw8z.js → chunk-tvefbgvw.js} +5 -2
  184. package/dist/{chunk-pdt5cw8z.js.map → chunk-tvefbgvw.js.map} +3 -3
  185. package/dist/{chunk-45ngkxkp.js → chunk-w122ymx4.js} +2 -2
  186. package/dist/{chunk-jn3ysaf2.js → chunk-w53trr0c.js} +12 -12
  187. package/dist/{chunk-jn3ysaf2.js.map → chunk-w53trr0c.js.map} +1 -1
  188. package/dist/{chunk-48jezz3j.js → chunk-w976a4me.js} +1 -1
  189. package/dist/{chunk-qtzftvxa.js → chunk-wx7smkn2.js} +1 -1
  190. package/dist/{chunk-c14ap3s9.js → chunk-y2x2935j.js} +3 -3
  191. package/dist/{chunk-7hf6tkgs.js → chunk-ytzcxtpt.js} +5 -5
  192. package/dist/{chunk-7hf6tkgs.js.map → chunk-ytzcxtpt.js.map} +1 -1
  193. package/dist/{chunk-mdxmt0n3.js → chunk-z3evap21.js} +1074 -122
  194. package/dist/chunk-z3evap21.js.map +129 -0
  195. package/dist/datasets/execution.d.ts +26 -1
  196. package/dist/datasets/execution.d.ts.map +1 -1
  197. package/dist/datasets/index.d.ts +1 -1
  198. package/dist/datasets/index.d.ts.map +1 -1
  199. package/dist/datasets/lineage.d.ts +55 -0
  200. package/dist/datasets/lineage.d.ts.map +1 -0
  201. package/dist/datasets/write.js +5 -5
  202. package/dist/deploy/types.d.ts +8 -1
  203. package/dist/deploy/types.d.ts.map +1 -1
  204. package/dist/env/index.d.ts +36 -0
  205. package/dist/env/index.d.ts.map +1 -0
  206. package/dist/env/index.js +17 -0
  207. package/dist/env/index.js.map +10 -0
  208. package/dist/error-reporting/internal.js +3 -3
  209. package/dist/errors/catalog.d.ts +8 -0
  210. package/dist/errors/catalog.d.ts.map +1 -1
  211. package/dist/errors/internal.js +1 -1
  212. package/dist/events/index.js +4 -4
  213. package/dist/events/selectors/index.js +1 -1
  214. package/dist/events/selectors/predicate.d.ts.map +1 -1
  215. package/dist/events/types/datasets.d.ts +6 -0
  216. package/dist/events/types/datasets.d.ts.map +1 -1
  217. package/dist/execution/agent.js +47 -47
  218. package/dist/execution/index.d.ts +1 -0
  219. package/dist/execution/index.d.ts.map +1 -1
  220. package/dist/execution/primitive.js +47 -47
  221. package/dist/execution/request-client.d.ts +21 -0
  222. package/dist/execution/request-client.d.ts.map +1 -0
  223. package/dist/execution/request.d.ts.map +1 -1
  224. package/dist/execution/request.js +49 -47
  225. package/dist/execution/request.js.map +3 -3
  226. package/dist/http/api-routes.d.ts.map +1 -1
  227. package/dist/http/index.js +1 -1
  228. package/dist/index.d.ts +7 -5
  229. package/dist/index.d.ts.map +1 -1
  230. package/dist/index.js +67 -67
  231. package/dist/index.js.map +1 -1
  232. package/dist/lake-storage/in-memory.d.ts.map +1 -1
  233. package/dist/lake-storage/index.d.ts +2 -2
  234. package/dist/lake-storage/index.d.ts.map +1 -1
  235. package/dist/lake-storage/index.js +10 -6
  236. package/dist/lake-storage/index.js.map +1 -1
  237. package/dist/lake-storage/source-ordering.d.ts +7 -0
  238. package/dist/lake-storage/source-ordering.d.ts.map +1 -1
  239. package/dist/lake-storage/types.d.ts +18 -0
  240. package/dist/lake-storage/types.d.ts.map +1 -1
  241. package/dist/lake-storage/version-inputs.d.ts +11 -3
  242. package/dist/lake-storage/version-inputs.d.ts.map +1 -1
  243. package/dist/lineage/commits.d.ts +45 -0
  244. package/dist/lineage/commits.d.ts.map +1 -0
  245. package/dist/lineage/executors.d.ts +14 -0
  246. package/dist/lineage/executors.d.ts.map +1 -0
  247. package/dist/lineage/link.d.ts +10 -0
  248. package/dist/lineage/link.d.ts.map +1 -0
  249. package/dist/lineage/object.d.ts +10 -0
  250. package/dist/lineage/object.d.ts.map +1 -0
  251. package/dist/lineage/projections.d.ts +34 -0
  252. package/dist/lineage/projections.d.ts.map +1 -0
  253. package/dist/lineage/reader.d.ts +34 -0
  254. package/dist/lineage/reader.d.ts.map +1 -0
  255. package/dist/lineage/sources.d.ts +62 -0
  256. package/dist/lineage/sources.d.ts.map +1 -0
  257. package/dist/lineage/types.d.ts +140 -0
  258. package/dist/lineage/types.d.ts.map +1 -0
  259. package/dist/materializer/effective/resolve.d.ts +63 -6
  260. package/dist/materializer/effective/resolve.d.ts.map +1 -1
  261. package/dist/materializer/index.js +27 -27
  262. package/dist/models/errors.d.ts +8 -0
  263. package/dist/models/errors.d.ts.map +1 -1
  264. package/dist/models/events.d.ts +10 -0
  265. package/dist/models/events.d.ts.map +1 -1
  266. package/dist/models/execution/index.d.ts +1 -0
  267. package/dist/models/execution/index.d.ts.map +1 -1
  268. package/dist/models/execution/index.js +34 -31
  269. package/dist/models/execution/index.js.map +1 -1
  270. package/dist/models/execution/model-call-recorder.d.ts +2 -0
  271. package/dist/models/execution/model-call-recorder.d.ts.map +1 -1
  272. package/dist/models/index.d.ts +2 -1
  273. package/dist/models/index.d.ts.map +1 -1
  274. package/dist/models/index.js +3 -3
  275. package/dist/models/language-model.d.ts +29 -2
  276. package/dist/models/language-model.d.ts.map +1 -1
  277. package/dist/objects/execution.d.ts +4 -1
  278. package/dist/objects/execution.d.ts.map +1 -1
  279. package/dist/objects/index.js +47 -47
  280. package/dist/objects/query/executor.d.ts.map +1 -1
  281. package/dist/objects/query/index.d.ts +1 -0
  282. package/dist/objects/query/index.d.ts.map +1 -1
  283. package/dist/objects/query/index.js +30 -28
  284. package/dist/objects/query/index.js.map +1 -1
  285. package/dist/objects/query/ir.d.ts +16 -0
  286. package/dist/objects/query/ir.d.ts.map +1 -1
  287. package/dist/objects/query/link-endpoints.d.ts +11 -0
  288. package/dist/objects/query/link-endpoints.d.ts.map +1 -0
  289. package/dist/objects/query/normalize.d.ts.map +1 -1
  290. package/dist/objects/query/planner.d.ts +5 -0
  291. package/dist/objects/query/planner.d.ts.map +1 -1
  292. package/dist/objects/query/validate.d.ts +2 -0
  293. package/dist/objects/query/validate.d.ts.map +1 -1
  294. package/dist/objects/sdk/object-set.d.ts +2 -0
  295. package/dist/objects/sdk/object-set.d.ts.map +1 -1
  296. package/dist/ontology/index.js +5 -5
  297. package/dist/ontology/internal.js +3 -3
  298. package/dist/pipelines/index.js +33 -33
  299. package/dist/pipelines/run-dispatch.d.ts +2 -0
  300. package/dist/pipelines/run-dispatch.d.ts.map +1 -1
  301. package/dist/projections/internal.js +27 -27
  302. package/dist/query.js +2 -2
  303. package/dist/queues/in-memory.d.ts +1 -1
  304. package/dist/queues/in-memory.d.ts.map +1 -1
  305. package/dist/runtime/create.d.ts +3 -0
  306. package/dist/runtime/create.d.ts.map +1 -1
  307. package/dist/runtime/internal.js +33 -33
  308. package/dist/runtime/resolve-definitions.d.ts.map +1 -1
  309. package/dist/runtime/types.d.ts +16 -0
  310. package/dist/runtime/types.d.ts.map +1 -1
  311. package/dist/sandboxes/exec.d.ts.map +1 -1
  312. package/dist/sandboxes/index.js +5 -5
  313. package/dist/schedules/index.js +2 -2
  314. package/dist/security/grants.d.ts +1 -1
  315. package/dist/security/grants.d.ts.map +1 -1
  316. package/dist/security/internal.js +1 -1
  317. package/dist/security/project.d.ts.map +1 -1
  318. package/dist/security/public.js +2 -2
  319. package/dist/security/types.d.ts +10 -3
  320. package/dist/security/types.d.ts.map +1 -1
  321. package/dist/security/validation.d.ts.map +1 -1
  322. package/dist/shares/execution.d.ts +9 -0
  323. package/dist/shares/execution.d.ts.map +1 -1
  324. package/dist/shares/index.d.ts +1 -1
  325. package/dist/shares/index.d.ts.map +1 -1
  326. package/dist/shares/internal.js +24 -24
  327. package/dist/storage/action-runs/failure.js +2 -2
  328. package/dist/storage/agents/in-memory.d.ts +38 -1
  329. package/dist/storage/agents/in-memory.d.ts.map +1 -1
  330. package/dist/storage/agents/index.d.ts +1 -1
  331. package/dist/storage/agents/index.d.ts.map +1 -1
  332. package/dist/storage/agents/provider.d.ts +43 -5
  333. package/dist/storage/agents/provider.d.ts.map +1 -1
  334. package/dist/storage/agents/provider.js +30 -6
  335. package/dist/storage/agents/provider.js.map +1 -1
  336. package/dist/storage/agents/types.d.ts +132 -10
  337. package/dist/storage/agents/types.d.ts.map +1 -1
  338. package/dist/storage/ai-cost/analytics.d.ts +13 -5
  339. package/dist/storage/ai-cost/analytics.d.ts.map +1 -1
  340. package/dist/storage/ai-cost/groups.d.ts +19 -2
  341. package/dist/storage/ai-cost/groups.d.ts.map +1 -1
  342. package/dist/storage/ai-cost/in-memory.d.ts +6 -1
  343. package/dist/storage/ai-cost/in-memory.d.ts.map +1 -1
  344. package/dist/storage/ai-cost/index.d.ts +1 -1
  345. package/dist/storage/ai-cost/index.d.ts.map +1 -1
  346. package/dist/storage/ai-cost/provider.d.ts +1 -1
  347. package/dist/storage/ai-cost/provider.d.ts.map +1 -1
  348. package/dist/storage/ai-cost/provider.js +7 -5
  349. package/dist/storage/ai-cost/provider.js.map +1 -1
  350. package/dist/storage/ai-cost/types.d.ts +65 -9
  351. package/dist/storage/ai-cost/types.d.ts.map +1 -1
  352. package/dist/storage/ai-limits/enforcement.js +4 -4
  353. package/dist/storage/ai-limits/provider.js +2 -2
  354. package/dist/storage/connector-connections/provider.js +1 -1
  355. package/dist/storage/file-upload-sessions/provider.js +10 -10
  356. package/dist/storage/in-memory/index.d.ts.map +1 -1
  357. package/dist/storage/index.d.ts +3 -3
  358. package/dist/storage/index.d.ts.map +1 -1
  359. package/dist/storage/index.js +31 -31
  360. package/dist/storage/index.js.map +1 -1
  361. package/dist/storage/internal.d.ts +2 -0
  362. package/dist/storage/internal.d.ts.map +1 -1
  363. package/dist/storage/internal.js +11 -7
  364. package/dist/storage/internal.js.map +1 -1
  365. package/dist/storage/objects/in-memory/query.d.ts.map +1 -1
  366. package/dist/storage/objects/query-preparation.d.ts +5 -0
  367. package/dist/storage/objects/query-preparation.d.ts.map +1 -1
  368. package/dist/storage/ontology/commits.d.ts +6 -1
  369. package/dist/storage/ontology/commits.d.ts.map +1 -1
  370. package/dist/storage/ontology/in-memory/commits.d.ts.map +1 -1
  371. package/dist/storage/ontology/in-memory/materializations.d.ts +2 -1
  372. package/dist/storage/ontology/in-memory/materializations.d.ts.map +1 -1
  373. package/dist/storage/ontology/index.d.ts +1 -1
  374. package/dist/storage/ontology/index.d.ts.map +1 -1
  375. package/dist/storage/ontology/materializations.d.ts +16 -0
  376. package/dist/storage/ontology/materializations.d.ts.map +1 -1
  377. package/dist/storage/ontology/provider.d.ts +6 -1
  378. package/dist/storage/ontology/provider.d.ts.map +1 -1
  379. package/dist/storage/ontology/provider.js +4 -2
  380. package/dist/storage/ontology/provider.js.map +1 -1
  381. package/dist/storage/operation-scope.d.ts +10 -0
  382. package/dist/storage/operation-scope.d.ts.map +1 -1
  383. package/dist/storage/operation-scope.js +7 -3
  384. package/dist/storage/operation-scope.js.map +1 -1
  385. package/dist/storage/pipeline-runs/in-memory.d.ts.map +1 -1
  386. package/dist/storage/pipeline-runs/transitions.d.ts +7 -0
  387. package/dist/storage/pipeline-runs/transitions.d.ts.map +1 -0
  388. package/dist/storage/projection-runs/provider.js +2 -2
  389. package/dist/storage/sync-runs/in-memory.d.ts.map +1 -1
  390. package/dist/storage/sync-runs/transitions.d.ts +7 -0
  391. package/dist/storage/sync-runs/transitions.d.ts.map +1 -0
  392. package/dist/storage/workflow-runs/provider.js +10 -10
  393. package/dist/syncs/index.js +34 -34
  394. package/dist/syncs/run-dispatch.d.ts +2 -0
  395. package/dist/syncs/run-dispatch.d.ts.map +1 -1
  396. package/dist/testing/agent-storage-contract.d.ts.map +1 -1
  397. package/dist/testing/agent-token-rate-storage-contract.d.ts +14 -0
  398. package/dist/testing/agent-token-rate-storage-contract.d.ts.map +1 -0
  399. package/dist/testing/ai-model-call-groups-contract.d.ts +1 -1
  400. package/dist/testing/ai-model-call-groups-contract.d.ts.map +1 -1
  401. package/dist/testing/dataset-sequence-contract.d.ts.map +1 -1
  402. package/dist/testing/index.d.ts +1 -0
  403. package/dist/testing/index.d.ts.map +1 -1
  404. package/dist/testing/index.js +4514 -3530
  405. package/dist/testing/index.js.map +13 -12
  406. package/dist/testing/lake-changes-contract.d.ts.map +1 -1
  407. package/dist/testing/lake-storage-contract.d.ts.map +1 -1
  408. package/dist/testing/materializer-storage-contract.d.ts.map +1 -1
  409. package/dist/testing/object-query-contract.d.ts.map +1 -1
  410. package/dist/testing/ontology-contract-fixture.d.ts +3 -3
  411. package/dist/testing/ontology-contract-fixture.d.ts.map +1 -1
  412. package/dist/testing/ontology-storage-contract.d.ts.map +1 -1
  413. package/dist/webhooks/internal.js +25 -25
  414. package/dist/workers/index.d.ts +1 -0
  415. package/dist/workers/index.d.ts.map +1 -1
  416. package/dist/workers/index.js +13 -3
  417. package/dist/workers/index.js.map +5 -4
  418. package/dist/workers/unstarted-run.d.ts +10 -0
  419. package/dist/workers/unstarted-run.d.ts.map +1 -0
  420. package/dist/workflows/builders.d.ts.map +1 -1
  421. package/dist/workflows/index.js +54 -54
  422. package/dist/workflows/types.d.ts +6 -0
  423. package/dist/workflows/types.d.ts.map +1 -1
  424. package/dist/workflows/validation.d.ts.map +1 -1
  425. package/package.json +7 -1
  426. package/src/actions/request.ts +6 -0
  427. package/src/actions/run/context.ts +6 -0
  428. package/src/actions/run/execute.ts +8 -2
  429. package/src/actions/run/executor.ts +4 -0
  430. package/src/actions/run/types.ts +5 -0
  431. package/src/actions/types/context.ts +11 -0
  432. package/src/agents/README.md +11 -3
  433. package/src/agents/adapters.ts +73 -23
  434. package/src/agents/approvals.ts +22 -0
  435. package/src/agents/context-budget.ts +121 -0
  436. package/src/agents/context-compaction.ts +317 -150
  437. package/src/agents/context-files.ts +48 -0
  438. package/src/agents/context-parts.ts +219 -0
  439. package/src/agents/context-request.ts +100 -0
  440. package/src/agents/context-token-rate.ts +224 -0
  441. package/src/agents/context-use.ts +187 -0
  442. package/src/agents/dispatch.ts +2 -0
  443. package/src/agents/execution.ts +105 -0
  444. package/src/agents/index.ts +46 -2
  445. package/src/agents/inline-images.ts +17 -0
  446. package/src/agents/message.ts +70 -1
  447. package/src/agents/model-loop.ts +192 -61
  448. package/src/agents/request.ts +18 -1
  449. package/src/agents/run-events.ts +3 -2
  450. package/src/agents/run-plan.ts +22 -3
  451. package/src/agents/run-session-http.ts +8 -5
  452. package/src/agents/run-session-serve.ts +133 -9
  453. package/src/agents/run-session.ts +30 -4
  454. package/src/agents/run-tools.ts +10 -2
  455. package/src/agents/run-turn.ts +116 -26
  456. package/src/agents/skills.ts +9 -2
  457. package/src/agents/step-limits.ts +27 -0
  458. package/src/agents/streams/index.ts +2 -0
  459. package/src/agents/streams/internal.ts +2 -0
  460. package/src/agents/streams/protocol.ts +125 -2
  461. package/src/agents/thread-context-projection.ts +25 -17
  462. package/src/agents/tool-files.ts +41 -3
  463. package/src/auth/runtime.ts +30 -1
  464. package/src/auth/types.ts +5 -0
  465. package/src/authorization/decision.ts +5 -0
  466. package/src/authorization/grant-kinds.ts +8 -0
  467. package/src/authorization/index.ts +2 -0
  468. package/src/authorization/run-visibility.ts +37 -0
  469. package/src/datasets/execution.ts +91 -2
  470. package/src/datasets/index.ts +1 -0
  471. package/src/datasets/lineage.ts +194 -0
  472. package/src/deploy/types.ts +8 -1
  473. package/src/env/index.ts +46 -0
  474. package/src/errors/catalog.ts +12 -0
  475. package/src/events/selectors/predicate.ts +15 -0
  476. package/src/events/types/datasets.ts +6 -0
  477. package/src/execution/index.ts +1 -0
  478. package/src/execution/request-client.ts +44 -0
  479. package/src/execution/request.ts +2 -0
  480. package/src/http/api-routes.ts +24 -25
  481. package/src/index.ts +32 -0
  482. package/src/lake-storage/in-memory.ts +30 -20
  483. package/src/lake-storage/index.ts +2 -1
  484. package/src/lake-storage/source-ordering.ts +31 -4
  485. package/src/lake-storage/types.ts +18 -0
  486. package/src/lake-storage/version-inputs.ts +21 -5
  487. package/src/lineage/README.md +107 -0
  488. package/src/lineage/commits.ts +173 -0
  489. package/src/lineage/executors.ts +103 -0
  490. package/src/lineage/link.ts +138 -0
  491. package/src/lineage/object.ts +218 -0
  492. package/src/lineage/projections.ts +174 -0
  493. package/src/lineage/reader.ts +89 -0
  494. package/src/lineage/sources.ts +156 -0
  495. package/src/lineage/types.ts +149 -0
  496. package/src/materializer/effective/resolve.ts +198 -50
  497. package/src/models/errors.ts +10 -0
  498. package/src/models/events.ts +13 -1
  499. package/src/models/execution/index.ts +1 -0
  500. package/src/models/execution/model-call-recorder.ts +7 -1
  501. package/src/models/index.ts +3 -0
  502. package/src/models/language-model.ts +34 -2
  503. package/src/objects/execution.ts +6 -1
  504. package/src/objects/query/executor.ts +28 -13
  505. package/src/objects/query/index.ts +1 -0
  506. package/src/objects/query/ir.ts +16 -0
  507. package/src/objects/query/link-endpoints.ts +29 -0
  508. package/src/objects/query/normalize.ts +3 -0
  509. package/src/objects/query/planner.ts +5 -0
  510. package/src/objects/query/validate.ts +73 -3
  511. package/src/objects/sdk/object-set.ts +33 -1
  512. package/src/pipelines/run-dispatch.ts +53 -6
  513. package/src/runtime/create.ts +6 -0
  514. package/src/runtime/resolve-definitions.ts +7 -0
  515. package/src/runtime/sixb.ts +4 -1
  516. package/src/runtime/types.ts +18 -0
  517. package/src/sandboxes/exec.ts +19 -0
  518. package/src/security/grants.ts +3 -0
  519. package/src/security/project.ts +1 -0
  520. package/src/security/types.ts +8 -3
  521. package/src/security/validation.ts +5 -4
  522. package/src/shares/execution.ts +35 -3
  523. package/src/shares/index.ts +1 -0
  524. package/src/storage/agents/in-memory.ts +179 -8
  525. package/src/storage/agents/index.ts +8 -0
  526. package/src/storage/agents/provider.ts +219 -6
  527. package/src/storage/agents/types.ts +145 -9
  528. package/src/storage/ai-cost/analytics.ts +177 -10
  529. package/src/storage/ai-cost/groups.ts +122 -35
  530. package/src/storage/ai-cost/in-memory.ts +10 -4
  531. package/src/storage/ai-cost/index.ts +5 -0
  532. package/src/storage/ai-cost/provider.ts +5 -1
  533. package/src/storage/ai-cost/types.ts +65 -9
  534. package/src/storage/in-memory/index.ts +10 -0
  535. package/src/storage/index.ts +15 -0
  536. package/src/storage/internal.ts +2 -0
  537. package/src/storage/objects/in-memory/query.ts +5 -1
  538. package/src/storage/objects/query-preparation.ts +10 -0
  539. package/src/storage/ontology/commits.ts +6 -1
  540. package/src/storage/ontology/in-memory/commits.ts +7 -0
  541. package/src/storage/ontology/in-memory/materializations.ts +24 -0
  542. package/src/storage/ontology/index.ts +2 -0
  543. package/src/storage/ontology/materializations.ts +21 -0
  544. package/src/storage/ontology/provider.ts +41 -1
  545. package/src/storage/operation-scope.ts +41 -0
  546. package/src/storage/pipeline-runs/in-memory.ts +2 -5
  547. package/src/storage/pipeline-runs/transitions.ts +14 -0
  548. package/src/storage/sync-runs/in-memory.ts +2 -5
  549. package/src/storage/sync-runs/transitions.ts +11 -0
  550. package/src/syncs/run-dispatch.ts +68 -13
  551. package/src/testing/agent-storage-contract.ts +426 -20
  552. package/src/testing/agent-token-rate-storage-contract.ts +171 -0
  553. package/src/testing/ai-model-call-groups-contract.ts +225 -7
  554. package/src/testing/dataset-sequence-contract.ts +81 -0
  555. package/src/testing/index.ts +5 -0
  556. package/src/testing/lake-changes-contract.ts +2 -1
  557. package/src/testing/lake-storage-contract.ts +112 -0
  558. package/src/testing/materializer-storage-contract.ts +294 -10
  559. package/src/testing/object-query-contract.ts +48 -0
  560. package/src/testing/ontology-contract-fixture.ts +18 -7
  561. package/src/testing/ontology-storage-contract.ts +42 -0
  562. package/src/workers/index.ts +1 -0
  563. package/src/workers/unstarted-run.ts +18 -0
  564. package/src/workflows/builders.ts +8 -1
  565. package/src/workflows/types.ts +6 -0
  566. package/src/workflows/validation.ts +1 -0
  567. package/dist/chunk-06sg8s4z.js.map +0 -15
  568. package/dist/chunk-0bc3w0zq.js.map +0 -11
  569. package/dist/chunk-18sk89cg.js.map +0 -10
  570. package/dist/chunk-1xvqgg88.js.map +0 -14
  571. package/dist/chunk-2adz0h75.js.map +0 -11
  572. package/dist/chunk-8xnz9vvp.js.map +0 -12
  573. package/dist/chunk-axb4ss9a.js.map +0 -12
  574. package/dist/chunk-cbcgs9f7.js.map +0 -11
  575. package/dist/chunk-jt3r6thp.js.map +0 -10
  576. package/dist/chunk-mdxmt0n3.js.map +0 -120
  577. package/dist/chunk-qst145py.js.map +0 -18
  578. package/dist/chunk-ratkv4zc.js +0 -3
  579. package/dist/chunk-t3brw0wd.js.map +0 -14
  580. package/dist/chunk-vhbw5sqm.js.map +0 -10
  581. package/dist/chunk-yd00vzqr.js.map +0 -37
  582. package/dist/chunk-z9mg7wya.js.map +0 -13
  583. /package/dist/{chunk-c0vk1djt.js.map → chunk-165c9wm6.js.map} +0 -0
  584. /package/dist/{chunk-8mb7mt8n.js.map → chunk-21q0j5f2.js.map} +0 -0
  585. /package/dist/{chunk-hn76sanm.js.map → chunk-23s66j86.js.map} +0 -0
  586. /package/dist/{chunk-h1na2cxc.js.map → chunk-2g0r46hy.js.map} +0 -0
  587. /package/dist/{chunk-tdxfsg1c.js.map → chunk-47e09r7z.js.map} +0 -0
  588. /package/dist/{chunk-fntqb7qy.js.map → chunk-57g0215c.js.map} +0 -0
  589. /package/dist/{chunk-npcr0228.js.map → chunk-5kyvrtjh.js.map} +0 -0
  590. /package/dist/{chunk-zhh1jd89.js.map → chunk-5taem5aw.js.map} +0 -0
  591. /package/dist/{chunk-tnhqtfea.js.map → chunk-6b61s40c.js.map} +0 -0
  592. /package/dist/{chunk-4ymrcdbm.js.map → chunk-7hd2ez3q.js.map} +0 -0
  593. /package/dist/{chunk-315qye3g.js.map → chunk-80nh73br.js.map} +0 -0
  594. /package/dist/{chunk-b6ghvap7.js.map → chunk-8yzhjawq.js.map} +0 -0
  595. /package/dist/{chunk-2vjnyz1s.js.map → chunk-9rh8ncs5.js.map} +0 -0
  596. /package/dist/{chunk-pgrf64hp.js.map → chunk-agn8d8ys.js.map} +0 -0
  597. /package/dist/{chunk-6qn7nmd3.js.map → chunk-aqyjb86c.js.map} +0 -0
  598. /package/dist/{chunk-4jq2bg8t.js.map → chunk-ax10ft8d.js.map} +0 -0
  599. /package/dist/{chunk-7ex2p3zp.js.map → chunk-cgznz22f.js.map} +0 -0
  600. /package/dist/{chunk-qgvbxfqv.js.map → chunk-djs3hw9p.js.map} +0 -0
  601. /package/dist/{chunk-dgtd0836.js.map → chunk-e7v3trpz.js.map} +0 -0
  602. /package/dist/{chunk-59kf345w.js.map → chunk-jbw70d6t.js.map} +0 -0
  603. /package/dist/{chunk-78ymxrn0.js.map → chunk-jhbk10wf.js.map} +0 -0
  604. /package/dist/{chunk-phm3c7b9.js.map → chunk-jjmggm9a.js.map} +0 -0
  605. /package/dist/{chunk-ft3w5ahs.js.map → chunk-m3qe54bb.js.map} +0 -0
  606. /package/dist/{chunk-y7j6x4h0.js.map → chunk-neftrg0n.js.map} +0 -0
  607. /package/dist/{chunk-07kkp2e1.js.map → chunk-nghc7eq0.js.map} +0 -0
  608. /package/dist/{chunk-vx4e4zv4.js.map → chunk-nqnfz3jg.js.map} +0 -0
  609. /package/dist/{chunk-e24fvw8g.js.map → chunk-qbrmpgvv.js.map} +0 -0
  610. /package/dist/{chunk-dp0cdtj2.js.map → chunk-qsg8rw04.js.map} +0 -0
  611. /package/dist/{chunk-0kk2wt0h.js.map → chunk-r1cxq7vv.js.map} +0 -0
  612. /package/dist/{chunk-g663fahq.js.map → chunk-scyq22td.js.map} +0 -0
  613. /package/dist/{chunk-7wn5z7mq.js.map → chunk-t9xyr7y9.js.map} +0 -0
  614. /package/dist/{chunk-45ngkxkp.js.map → chunk-w122ymx4.js.map} +0 -0
  615. /package/dist/{chunk-48jezz3j.js.map → chunk-w976a4me.js.map} +0 -0
  616. /package/dist/{chunk-qtzftvxa.js.map → chunk-wx7smkn2.js.map} +0 -0
  617. /package/dist/{chunk-c14ap3s9.js.map → chunk-y2x2935j.js.map} +0 -0
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  validateSchemaValue2,
4
4
  normalizeSchemaValue2
5
- } from "./chunk-qgvbxfqv.js";
5
+ } from "./chunk-djs3hw9p.js";
6
6
  import {
7
7
  sniffFileMediaType2,
8
8
  isFileRef2
@@ -23,28 +23,28 @@ import {
23
23
  requestAgentRunCancel2,
24
24
  listSubagentThreadRuns2,
25
25
  subagentSandboxFiles2
26
- } from "./chunk-mdxmt0n3.js";
26
+ } from "./chunk-z3evap21.js";
27
27
  import {
28
28
  createSixbError2,
29
29
  captureSixbFailure2,
30
30
  isSixbError2
31
- } from "./chunk-zbc929zg.js";
31
+ } from "./chunk-escedwyt.js";
32
32
  import {
33
33
  principalsEqual2
34
- } from "./chunk-8v6xzwgr.js";
34
+ } from "./chunk-3x3bebz7.js";
35
35
  import {
36
36
  resolveAgentPropertyClearance2,
37
37
  resolveAgentExecutionAuthorization2,
38
38
  userCanRunAgent2,
39
39
  resolveInheritedAgentExecutionAuthorization2
40
- } from "./chunk-y7j6x4h0.js";
40
+ } from "./chunk-neftrg0n.js";
41
41
  import {
42
42
  AgentStorageError2,
43
43
  createSubagentRunId2,
44
44
  createSubagentThreadId2,
45
45
  createSubagentExecutionId2,
46
46
  createAgentRunExecutionToken2
47
- } from "./chunk-z9mg7wya.js";
47
+ } from "./chunk-edx8xcsm.js";
48
48
  import {
49
49
  ARTIFACT_LIMITS2
50
50
  } from "./chunk-hz5d43gn.js";
@@ -59,7 +59,7 @@ import {
59
59
  agentRunFinishedEvent2,
60
60
  agentRunStreamEventBase2,
61
61
  agentRunStreamIdempotencyKey2
62
- } from "./chunk-jt3r6thp.js";
62
+ } from "./chunk-fg1db9xx.js";
63
63
  import {
64
64
  ArtifactRequestError2
65
65
  } from "./chunk-kwfhd1g0.js";
@@ -70,32 +70,35 @@ import {
70
70
  artifactVersionWarnings2,
71
71
  artifactAccessRule2,
72
72
  artifactQueryChecker2
73
- } from "./chunk-7wn5z7mq.js";
73
+ } from "./chunk-t9xyr7y9.js";
74
74
  import {
75
75
  ModelUsageRecordingError2,
76
76
  createAiModelCallLimitController2,
77
77
  AiModelCallRecorder2
78
- } from "./chunk-mqx25wwh.js";
78
+ } from "./chunk-b7a97n8b.js";
79
79
  import {
80
80
  renderOntologyDocs2
81
- } from "./chunk-zhh1jd89.js";
81
+ } from "./chunk-5taem5aw.js";
82
82
  import {
83
83
  SIXB_API_ROUTES2,
84
84
  matchesPathPattern2,
85
85
  normalizeRoutePath2
86
- } from "./chunk-cbcgs9f7.js";
86
+ } from "./chunk-jftd33rc.js";
87
87
  import {
88
88
  assertValidSchema
89
- } from "./chunk-0kk2wt0h.js";
89
+ } from "./chunk-r1cxq7vv.js";
90
90
  import {
91
91
  schemaRecordToJsonSchema2
92
92
  } from "./chunk-e5wf5vz0.js";
93
93
  import {
94
94
  ensureExecutionRecord2
95
- } from "./chunk-e24fvw8g.js";
95
+ } from "./chunk-qbrmpgvv.js";
96
96
  import {
97
97
  resolveLanguageModel2
98
- } from "./chunk-07kkp2e1.js";
98
+ } from "./chunk-nghc7eq0.js";
99
+ import {
100
+ RuntimeError2
101
+ } from "./chunk-m4ehq95f.js";
99
102
  import {
100
103
  OntologyValidationError2
101
104
  } from "./chunk-cqr3acm1.js";
@@ -106,12 +109,16 @@ import {
106
109
  AgentMemoryError2
107
110
  } from "./chunk-9wr3yajk.js";
108
111
  import {
109
- AGENT_RUN_FAILURE_CODES2
110
- } from "./chunk-18sk89cg.js";
112
+ AGENT_RUN_FAILURE_CODES2,
113
+ AGENT_TOKEN_RATE_SAMPLES2,
114
+ AGENT_TOKEN_RATE_MIN_BYTES_PER_TOKEN2,
115
+ AGENT_TOKEN_RATE_MAX_BYTES_PER_TOKEN
116
+ } from "./chunk-jk97v21j.js";
111
117
  import {
112
118
  openFileRef2
113
119
  } from "./chunk-a3faa34j.js";
114
120
  import {
121
+ isJsonValue2,
115
122
  cloneJsonValue2,
116
123
  stableJsonStringify2,
117
124
  getInvalidJsonValueReason2,
@@ -335,17 +342,31 @@ function userModelMessage(message, options) {
335
342
  ${suffix}` });
336
343
  return { role: "user", content };
337
344
  }
338
- function appendAssistantModelMessages(result, message, options) {
339
- let block = [];
345
+ function agentMessageSteps2(message) {
346
+ const steps = [];
347
+ let parts = [];
340
348
  const flush = () => {
341
- if (block.length === 0) {
349
+ if (parts.length === 0)
342
350
  return;
351
+ const localToolCalls = parts.flatMap(({ part, partIndex }) => part.type === "tool-call" && part.providerExecuted !== true ? [{ part, partIndex }] : []);
352
+ steps.push({ parts, localToolCalls });
353
+ parts = [];
354
+ };
355
+ message.parts.forEach((part, partIndex) => {
356
+ if (part.type === "step-start") {
357
+ flush();
358
+ } else {
359
+ parts.push({ part, partIndex });
343
360
  }
344
- const current = block;
345
- block = [];
361
+ });
362
+ flush();
363
+ return steps;
364
+ }
365
+ function appendAssistantModelMessages(result, message, options) {
366
+ for (const step of agentMessageSteps2(message)) {
346
367
  const content = [];
347
368
  const toolResults = [];
348
- for (const { part, partIndex } of current) {
369
+ for (const { part, partIndex } of step.parts) {
349
370
  if (part.type === "text" || part.type === "reasoning") {
350
371
  content.push({
351
372
  type: part.type,
@@ -369,18 +390,14 @@ function appendAssistantModelMessages(result, message, options) {
369
390
  }
370
391
  if (content.length > 0)
371
392
  result.push({ role: "assistant", content });
372
- if (toolResults.length > 0) {
393
+ const first = step.localToolCalls[0];
394
+ if (toolResults.length > 0 && first) {
373
395
  result.push({ role: "tool", content: toolResults });
396
+ const followUp = options.afterToolResults?.({ message, partIndex: first.partIndex });
397
+ if (followUp)
398
+ result.push(followUp);
374
399
  }
375
- };
376
- message.parts.forEach((part, partIndex) => {
377
- if (part.type === "step-start") {
378
- flush();
379
- } else {
380
- block.push({ part, partIndex });
381
- }
382
- });
383
- flush();
400
+ }
384
401
  }
385
402
  function toolCallModelPart(part) {
386
403
  return {
@@ -404,6 +421,9 @@ function toolResultOutput(message, part, partIndex, errorMode, options) {
404
421
  if (part.state === "output-error") {
405
422
  return errorMode === "json" ? { type: "error-json", value: part.errorText } : { type: "error-text", value: part.errorText };
406
423
  }
424
+ const modelOutput = storedModelOutput(part.modelOutput);
425
+ if (modelOutput)
426
+ return modelOutput;
407
427
  if (isAgentToolResult2(part.output)) {
408
428
  const value = [];
409
429
  part.output.content.forEach((contentPart, contentIndex) => {
@@ -425,6 +445,16 @@ function toolResultOutput(message, part, partIndex, errorMode, options) {
425
445
  }
426
446
  return typeof part.output === "string" ? { type: "text", value: part.output } : { type: "json", value: part.output };
427
447
  }
448
+ function storedModelOutput(value) {
449
+ if (typeof value !== "object" || value === null)
450
+ return;
451
+ const { type, value: content } = value;
452
+ if (type === "text" && typeof content === "string")
453
+ return { type, value: content };
454
+ if (type === "json" && isJsonValue2(content))
455
+ return { type, value: content };
456
+ return;
457
+ }
428
458
  function toolResultFileFallbackText(part) {
429
459
  const attributes = [
430
460
  part.fileRef.fileName ? `name=${JSON.stringify(part.fileRef.fileName)}` : undefined,
@@ -659,52 +689,230 @@ function defineAgentTool2(name) {
659
689
  }
660
690
  };
661
691
  }
692
+ // src/agents/context-files.ts
693
+ import { posix } from "path";
694
+ var CONTEXT_FILE_READERS = new Set(["read", "view_file"]);
695
+ var CONTEXT_FOLDERS = [
696
+ { part: "memory", folder: "memory", variable: "$SIXB_MEMORY_DIR" },
697
+ { part: "skills", folder: "skills", variable: "$SIXB_SKILLS_DIR" },
698
+ { part: "ontology", folder: "ontology", variable: "$SIXB_ONTOLOGY_DIR" }
699
+ ];
700
+ function agentContextFileKind(call, contextDirectory) {
701
+ if (!CONTEXT_FILE_READERS.has(call.toolName))
702
+ return;
703
+ const input = call.input;
704
+ const path = typeof input === "object" && input !== null && !Array.isArray(input) ? input.path : undefined;
705
+ if (typeof path !== "string")
706
+ return;
707
+ const normalized = posix.normalize(path.trim());
708
+ const root = contextDirectory === undefined ? undefined : posix.normalize(contextDirectory);
709
+ const under = (folder) => {
710
+ if (root === undefined)
711
+ return false;
712
+ const prefix = `${posix.join(root, folder)}/`;
713
+ return normalized.startsWith(prefix) || !posix.isAbsolute(root) && normalized.includes(`/${prefix}`);
714
+ };
715
+ const match = CONTEXT_FOLDERS.find(({ folder, variable }) => normalized.startsWith(`${variable}/`) || under(folder));
716
+ return match?.part;
717
+ }
718
+
719
+ // src/agents/inline-images.ts
720
+ var AGENT_INLINE_IMAGE_LIMITS2 = {
721
+ maxBytes: 16 * 1024 * 1024,
722
+ maxImages: 100
723
+ };
724
+ var AGENT_IMAGE_INPUT_TOKENS2 = 5400;
725
+
726
+ // src/agents/thread-context-projection.ts
727
+ function projectAgentThreadModelContext2(input) {
728
+ const { checkpoint, messages } = input;
729
+ if (!checkpoint)
730
+ return messages;
731
+ assertConsistentCheckpointProjection(checkpoint, messages);
732
+ const summary = serializeThreadSummary(checkpoint.summary, input.historyReadable ?? true);
733
+ return [{ role: "user", parts: [{ type: "text", text: summary }] }, ...messages];
734
+ }
735
+ function assertConsistentCheckpointProjection(checkpoint, messages) {
736
+ if (checkpoint.summaryFormatVersion !== 1 || checkpoint.summary.trim().length === 0) {
737
+ throw projectionError(checkpoint, "has an invalid summary");
738
+ }
739
+ if (checkpoint.summarizedThroughSeq >= checkpoint.observedHeadSeq) {
740
+ throw projectionError(checkpoint, "does not retain its observed head");
741
+ }
742
+ if (messages.length === 0) {
743
+ throw projectionError(checkpoint, "has no retained messages");
744
+ }
745
+ let expectedSeq = checkpoint.summarizedThroughSeq + 1;
746
+ for (const message of messages) {
747
+ if (message.projectId !== checkpoint.projectId || message.threadId !== checkpoint.threadId) {
748
+ throw projectionError(checkpoint, "contains a message from another thread");
749
+ }
750
+ if (message.seq !== expectedSeq) {
751
+ throw projectionError(checkpoint, `has a sequence gap before message '${message.id}'`);
752
+ }
753
+ expectedSeq += 1;
754
+ }
755
+ if (messages[0]?.role !== "user") {
756
+ throw projectionError(checkpoint, "does not begin at a user turn boundary");
757
+ }
758
+ if ((messages.at(-1)?.seq ?? 0) < checkpoint.observedHeadSeq) {
759
+ throw projectionError(checkpoint, "ends before the checkpoint's observed head");
760
+ }
761
+ }
762
+ var SUMMARY_INTRO = "The earlier conversation was compacted into this continuation summary.";
763
+ function isAgentThreadSummaryText(text) {
764
+ return text.startsWith(SUMMARY_INTRO) && text.includes(`
765
+ <sixb_thread_summary>
766
+ `);
767
+ }
768
+ function serializeThreadSummary(summary, historyReadable) {
769
+ return [
770
+ historyReadable ? `${SUMMARY_INTRO} Its messages are still stored: \`sixb history\` prints them.` : SUMMARY_INTRO,
771
+ "",
772
+ "<sixb_thread_summary>",
773
+ escapeXmlText(summary),
774
+ "</sixb_thread_summary>"
775
+ ].join(`
776
+ `);
777
+ }
778
+ function projectionError(checkpoint, detail) {
779
+ return new Error(`[Sixb] Agent context checkpoint '${checkpoint.id}' for thread '${checkpoint.threadId}' ${detail}.`);
780
+ }
781
+ function escapeXmlText(value) {
782
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
783
+ }
784
+
662
785
  // src/agents/context-compaction.ts
663
- var AGENT_CONTEXT_ESTIMATOR_VERSION2 = 1;
664
- var CHARS_PER_TOKEN = 4;
786
+ var AGENT_CONTEXT_ESTIMATOR_VERSION2 = 2;
665
787
  var REQUEST_OVERHEAD_TOKENS = 8;
666
788
  var MESSAGE_OVERHEAD_TOKENS = 8;
667
789
  var TOOL_OVERHEAD_TOKENS = 16;
668
790
  var STEP_OVERHEAD_TOKENS = 2;
669
- var IMAGE_ALLOWANCE_TOKENS = 1200;
670
791
  var FILE_TEXT_INLINE_MAX_BYTES = 50 * 1024;
671
792
  var FILE_TEXT_INLINE_TOTAL_MAX_BYTES = 200 * 1024;
672
- var TOOL_RESULT_SUMMARY_MAX_CHARS = 2000;
673
793
  function shouldCompactAgentContext2(input) {
674
794
  return input.estimatedInputTokens > input.inputBudgetTokens;
675
795
  }
676
796
  function estimateAgentContextRequestTokens2(input) {
677
- const toolTokens = input.tools.reduce((total, tool) => total + TOOL_OVERHEAD_TOKENS + textTokens(tool.name) + textTokens(tool.description) + textTokens(tool.inputSchema), 0);
678
797
  return {
679
- tokens: REQUEST_OVERHEAD_TOKENS + textTokens(input.systemPrompt) + toolTokens + estimateAgentContextMessagesTokens2(input.messages).tokens,
798
+ tokens: agentContextSizeTokens2(measureAgentContextRequest(input), input.bytesPerToken),
680
799
  estimatorVersion: AGENT_CONTEXT_ESTIMATOR_VERSION2
681
800
  };
682
801
  }
683
- function estimateAgentContextMessagesTokens2(messages) {
684
- const attachments = { textBytesRemaining: FILE_TEXT_INLINE_TOTAL_MAX_BYTES };
685
- let tokens = 0;
686
- for (const message of messages) {
687
- tokens += estimateMessageTokens(message, attachments);
802
+ function estimateAgentContextMessagesTokens2(messages, bytesPerToken) {
803
+ return {
804
+ tokens: agentContextSizeTokens2(measureAgentContextHistory({ messages }), bytesPerToken),
805
+ estimatorVersion: AGENT_CONTEXT_ESTIMATOR_VERSION2
806
+ };
807
+ }
808
+ function measureAgentContextRequest(input) {
809
+ return addAgentContextSizes(measureAgentContextFixed(input), measureAgentContextHistory(input));
810
+ }
811
+ function measureAgentContextFixed(input) {
812
+ return fixedAgentContextSize({
813
+ systemBytes: utf8Bytes(input.systemPrompt),
814
+ tools: {
815
+ count: input.tools.length,
816
+ bytes: input.tools.reduce((bytes, tool) => bytes + utf8Bytes(tool.name) + utf8Bytes(tool.description) + utf8Bytes(tool.inputSchema), 0)
817
+ }
818
+ });
819
+ }
820
+ function fixedAgentContextSize(input) {
821
+ return {
822
+ bytes: input.systemBytes + input.tools.bytes,
823
+ tokens: REQUEST_OVERHEAD_TOKENS + input.tools.count * TOOL_OVERHEAD_TOKENS
824
+ };
825
+ }
826
+ function measureAgentContextHistory(input) {
827
+ const images = { remaining: AGENT_INLINE_IMAGE_LIMITS2.maxImages };
828
+ const size = { bytes: 0, tokens: 0, parts: {} };
829
+ for (const message of input.messages) {
830
+ measureMessage(message, { textBytesRemaining: FILE_TEXT_INLINE_TOTAL_MAX_BYTES }, images, size, input.contextDirectory);
831
+ if (message.role === "assistant")
832
+ size.tokens += toolImageTokens(message, images);
688
833
  }
689
- return { tokens, estimatorVersion: AGENT_CONTEXT_ESTIMATOR_VERSION2 };
834
+ return { ...size, images: AGENT_INLINE_IMAGE_LIMITS2.maxImages - images.remaining };
835
+ }
836
+ function addAgentContextSizes(left, right) {
837
+ return {
838
+ bytes: left.bytes + right.bytes,
839
+ tokens: left.tokens + right.tokens,
840
+ images: (left.images ?? 0) + (right.images ?? 0)
841
+ };
842
+ }
843
+ function agentContextSizeTokens2(size, bytesPerToken) {
844
+ return size.tokens + Math.ceil(size.bytes / bytesPerToken);
845
+ }
846
+ function measureAgentModelRequest2(request) {
847
+ const size = { ...measureModelRequest2(request), images: 0 };
848
+ for (const message of request.messages) {
849
+ if (message.role !== "user")
850
+ continue;
851
+ for (const part of message.content) {
852
+ if (part.type !== "file")
853
+ continue;
854
+ if (part.mediaType.startsWith("image/")) {
855
+ size.tokens += AGENT_IMAGE_INPUT_TOKENS2;
856
+ size.images += 1;
857
+ } else {
858
+ size.bytes += utf8Bytes(part.data.href);
859
+ }
860
+ }
861
+ }
862
+ return size;
863
+ }
864
+ function measureModelRequest2(request) {
865
+ const size = { bytes: 0, tokens: REQUEST_OVERHEAD_TOKENS };
866
+ for (const tool of request.tools) {
867
+ size.tokens += TOOL_OVERHEAD_TOKENS;
868
+ size.bytes += utf8Bytes(tool.name) + utf8Bytes(tool.description) + utf8Bytes(stableJsonStringify2(tool.inputSchema));
869
+ }
870
+ if (request.responseFormat) {
871
+ size.bytes += utf8Bytes(stableJsonStringify2(request.responseFormat.schema));
872
+ }
873
+ for (const message of request.messages) {
874
+ size.tokens += MESSAGE_OVERHEAD_TOKENS;
875
+ if (message.role === "system") {
876
+ size.bytes += utf8Bytes(message.content);
877
+ continue;
878
+ }
879
+ for (const part of message.content) {
880
+ switch (part.type) {
881
+ case "text":
882
+ case "reasoning":
883
+ size.bytes += utf8Bytes(part.text);
884
+ break;
885
+ case "file":
886
+ size.bytes += utf8Bytes(`${part.filename ?? ""} ${part.mediaType}`);
887
+ break;
888
+ case "provider-state":
889
+ size.bytes += utf8Bytes(stableJsonStringify2(part.data));
890
+ break;
891
+ case "tool-call":
892
+ size.tokens += TOOL_OVERHEAD_TOKENS;
893
+ size.bytes += utf8Bytes(part.toolName) + utf8Bytes(stableJsonStringify2(part.input));
894
+ break;
895
+ case "tool-result":
896
+ size.tokens += TOOL_OVERHEAD_TOKENS;
897
+ size.bytes += typeof part.output.value === "string" ? utf8Bytes(part.output.value) : utf8Bytes(stableJsonStringify2(part.output.value));
898
+ break;
899
+ }
900
+ }
901
+ }
902
+ return size;
690
903
  }
691
904
  function selectAgentContextCompactionBoundary2(input) {
692
905
  if (input.messages.length < 2)
693
906
  return null;
694
907
  let retainedTokens = 0;
695
908
  let boundaryIndex = null;
696
- let closestDistance = Number.POSITIVE_INFINITY;
697
909
  for (let index = input.messages.length - 1;index > 0; index -= 1) {
698
- retainedTokens += estimateAgentContextMessagesTokens2([input.messages[index]]).tokens;
910
+ retainedTokens += estimateAgentContextMessagesTokens2([input.messages[index]], input.bytesPerToken).tokens;
699
911
  if (input.messages[index]?.role !== "user")
700
912
  continue;
701
- const distance = Math.abs(input.keepRecentTokens - retainedTokens);
702
- if (distance <= closestDistance) {
703
- boundaryIndex = index;
704
- closestDistance = distance;
705
- }
706
- if (retainedTokens >= input.keepRecentTokens)
913
+ if (boundaryIndex !== null && retainedTokens > input.keepRecentTokens)
707
914
  break;
915
+ boundaryIndex = index;
708
916
  }
709
917
  if (boundaryIndex === null)
710
918
  return null;
@@ -717,131 +925,660 @@ function selectAgentContextCompactionBoundary2(input) {
717
925
  summarizedThroughSeq
718
926
  };
719
927
  }
720
- function serializeAgentMessagesForSummary2(messages) {
721
- const lines = ["<sixb_conversation_history>"];
722
- for (const message of messages) {
723
- lines.push(` <message id="${escapeXml2(message.id)}" seq="${message.seq}" role="${message.role}">`);
724
- message.parts.forEach((part, partIndex) => {
725
- lines.push(...serializeSummaryPart(message, part, partIndex));
726
- });
727
- lines.push(" </message>");
728
- }
729
- lines.push("</sixb_conversation_history>");
730
- return lines.join(`
731
- `);
928
+ function addBytes(size, part, bytes) {
929
+ size.bytes += bytes;
930
+ size.parts[part] = (size.parts[part] ?? 0) + bytes;
732
931
  }
733
- function estimateMessageTokens(message, attachments) {
734
- let tokens = MESSAGE_OVERHEAD_TOKENS;
932
+ function measureMessage(message, attachments, images, size, contextDirectory) {
933
+ size.tokens += MESSAGE_OVERHEAD_TOKENS;
735
934
  for (const part of message.parts) {
736
935
  switch (part.type) {
737
936
  case "text":
937
+ addBytes(size, message.role === "user" && isAgentThreadSummaryText(part.text) ? "summary" : "messages", utf8Bytes(part.text));
938
+ break;
738
939
  case "reasoning":
739
- tokens += textTokens(part.text);
940
+ addBytes(size, "messages", utf8Bytes(part.text));
740
941
  break;
741
942
  case "step-start":
742
- tokens += STEP_OVERHEAD_TOKENS;
943
+ size.tokens += STEP_OVERHEAD_TOKENS;
743
944
  break;
744
945
  case "continuation":
745
- tokens += textTokens(AGENT_CONTINUATION_INSTRUCTION);
946
+ addBytes(size, "messages", utf8Bytes(AGENT_CONTINUATION_INSTRUCTION));
746
947
  break;
747
948
  case "approval-outcome":
748
- tokens += textTokens(approvalOutcomeInstruction(part));
949
+ addBytes(size, "messages", utf8Bytes(approvalOutcomeInstruction(part)));
749
950
  break;
750
951
  case "mail":
751
- tokens += textTokens(agentMailInstruction(part));
952
+ addBytes(size, "messages", utf8Bytes(agentMailInstruction(part)));
752
953
  break;
753
954
  case "context":
754
- tokens += textTokens(stableJsonStringify2(part.context));
955
+ addBytes(size, "messages", utf8Bytes(stableJsonStringify2(part.context)));
755
956
  break;
756
957
  case "provider-state":
757
- tokens += textTokens(stableJsonStringify2(part.data));
958
+ addBytes(size, "messages", utf8Bytes(stableJsonStringify2(part.data)));
758
959
  break;
759
960
  case "tool-call":
760
- tokens += TOOL_OVERHEAD_TOKENS + textTokens(part.toolName) + textTokens(stableJsonStringify2(part.input)) + (part.state === "output-available" ? textTokens(stableJsonStringify2(part.output)) : textTokens(part.errorText));
961
+ size.tokens += TOOL_OVERHEAD_TOKENS;
962
+ addBytes(size, "messages", utf8Bytes(part.toolName) + utf8Bytes(stableJsonStringify2(part.input)));
963
+ addBytes(size, agentContextFileKind(part, contextDirectory) ?? "toolResults", toolOutputBytes(part));
761
964
  break;
762
965
  case "file": {
763
966
  const file = part.fileRef;
764
- tokens += textTokens([file.blobId, file.digest, file.fileName, file.mediaType, file.logicalPath].filter((value) => value !== undefined).join(" "));
967
+ addBytes(size, "files", utf8Bytes([file.blobId, file.digest, file.fileName, file.mediaType, file.logicalPath].filter((value) => value !== undefined).join(" ")));
765
968
  if (message.role !== "assistant") {
766
969
  if (looksLikeImage(file.mediaType, file.fileName)) {
767
- tokens += IMAGE_ALLOWANCE_TOKENS;
970
+ size.tokens += imageTokens(images);
768
971
  } else {
769
972
  const inlineBytes = Math.min(file.sizeBytes, FILE_TEXT_INLINE_MAX_BYTES, attachments.textBytesRemaining);
770
973
  attachments.textBytesRemaining -= inlineBytes;
771
- tokens += Math.ceil(inlineBytes / CHARS_PER_TOKEN);
974
+ addBytes(size, "files", inlineBytes);
772
975
  }
773
976
  }
774
977
  break;
775
978
  }
776
979
  }
777
980
  }
981
+ }
982
+ function looksLikeImage(mediaType, fileName) {
983
+ if (mediaType?.toLowerCase().startsWith("image/"))
984
+ return true;
985
+ return /\.(?:avif|gif|jpe?g|png|webp)$/i.test(fileName ?? "");
986
+ }
987
+ function toolImageTokens(message, images) {
988
+ let tokens = 0;
989
+ for (const step of agentMessageSteps2(message)) {
990
+ const seen = new Set;
991
+ for (const { part } of step.localToolCalls) {
992
+ if (part.state !== "output-available" || !isAgentToolResult2(part.output))
993
+ continue;
994
+ for (const content of part.output.content) {
995
+ if (content.type !== "file")
996
+ continue;
997
+ if (!looksLikeImage(content.fileRef.mediaType, content.fileRef.fileName))
998
+ continue;
999
+ const identity = `${content.fileRef.digest}:${content.fileRef.sizeBytes}`;
1000
+ if (seen.has(identity))
1001
+ continue;
1002
+ seen.add(identity);
1003
+ tokens += imageTokens(images);
1004
+ }
1005
+ }
1006
+ }
778
1007
  return tokens;
779
1008
  }
780
- function serializeSummaryPart(message, part, partIndex) {
781
- const indent = " ";
782
- switch (part.type) {
783
- case "text":
784
- return [`${indent}<text>${escapeXml2(part.text)}</text>`];
785
- case "reasoning":
786
- case "provider-state":
787
- case "step-start":
788
- return [];
789
- case "continuation":
790
- return [`${indent}<continuation_request />`];
791
- case "approval-outcome":
792
- return [`${indent}${escapeXml2(approvalOutcomeInstruction(part))}`];
793
- case "mail":
794
- return [`${indent}${escapeXml2(agentMailInstruction(part))}`];
795
- case "context":
796
- return part.context.kind === "object" ? [
797
- `${indent}<object_context origin="${part.origin}" object_type_id="${escapeXml2(part.context.ref.objectTypeId)}" primary_id="${escapeXml2(part.context.ref.primaryId)}" />`
798
- ] : [
799
- `${indent}<app_context origin="${part.origin}" id="${escapeXml2(part.context.id)}" label="${escapeXml2(part.context.label)}">`,
800
- `${indent} <description>${escapeXml2(part.context.description)}</description>`,
801
- `${indent} <value format="json">${escapeXml2(stableJsonStringify2(part.context.value))}</value>`,
802
- `${indent}</app_context>`
803
- ];
804
- case "file": {
805
- const file = part.fileRef;
806
- const attributes = [
807
- `message_id="${escapeXml2(message.id)}"`,
808
- `part_index="${partIndex}"`,
809
- `blob_id="${escapeXml2(file.blobId)}"`,
810
- `digest="${escapeXml2(file.digest)}"`,
811
- `size_bytes="${file.sizeBytes}"`,
812
- ...file.fileName === undefined ? [] : [`file_name="${escapeXml2(file.fileName)}"`],
813
- ...file.mediaType === undefined ? [] : [`media_type="${escapeXml2(file.mediaType)}"`],
814
- ...file.logicalPath === undefined ? [] : [`logical_path="${escapeXml2(file.logicalPath)}"`]
815
- ];
816
- return [`${indent}<file ${attributes.join(" ")} />`];
1009
+ function imageTokens(images) {
1010
+ if (images.remaining === 0)
1011
+ return 0;
1012
+ images.remaining -= 1;
1013
+ return AGENT_IMAGE_INPUT_TOKENS2;
1014
+ }
1015
+ function toolOutputBytes(part) {
1016
+ if (part.state === "output-error")
1017
+ return utf8Bytes(part.errorText);
1018
+ if (part.modelOutput?.type === "text")
1019
+ return utf8Bytes(part.modelOutput.value);
1020
+ if (part.modelOutput)
1021
+ return utf8Bytes(stableJsonStringify2(part.modelOutput.value));
1022
+ return utf8Bytes(stableJsonStringify2(part.output));
1023
+ }
1024
+ function utf8Bytes(value) {
1025
+ return new TextEncoder().encode(value).byteLength;
1026
+ }
1027
+
1028
+ // src/agents/context-token-rate.ts
1029
+ var AGENT_CONTEXT_DEFAULT_BYTES_PER_TOKEN = 2;
1030
+ var CALIBRATION_MIN_TEXT_TOKENS = 1000;
1031
+ var CALIBRATION_MIN_FACTOR = 0.5;
1032
+ var CALIBRATION_MAX_FACTOR = 1.25;
1033
+ function measureAgentContextTokenRate2(input) {
1034
+ const { size } = input;
1035
+ if ((size.images ?? 0) > 0)
1036
+ return;
1037
+ const tokens = input.inputTokens - size.tokens;
1038
+ if (tokens < CALIBRATION_MIN_TEXT_TOKENS || size.bytes <= 0)
1039
+ return;
1040
+ return { bytes: size.bytes, tokens };
1041
+ }
1042
+ function calibrateAgentContextBytesPerToken2(input) {
1043
+ const sample = measureAgentContextTokenRate2(input);
1044
+ if (!sample)
1045
+ return input.bytesPerToken;
1046
+ return Math.min(input.bytesPerToken * CALIBRATION_MAX_FACTOR, Math.max(input.bytesPerToken * CALIBRATION_MIN_FACTOR, sample.bytes / sample.tokens));
1047
+ }
1048
+ function learnedAgentContextBytesPerToken2(samples) {
1049
+ if (samples.length === 0)
1050
+ return AGENT_CONTEXT_DEFAULT_BYTES_PER_TOKEN;
1051
+ const rates = samples.slice(0, AGENT_TOKEN_RATE_SAMPLES2).map((sample) => sample.bytes / sample.tokens).sort((a, b) => a - b);
1052
+ const rate = rates[Math.ceil(rates.length / 2) - 1];
1053
+ return Math.min(AGENT_TOKEN_RATE_MAX_BYTES_PER_TOKEN, Math.max(AGENT_TOKEN_RATE_MIN_BYTES_PER_TOKEN2, rate));
1054
+ }
1055
+ async function readAgentContextTokenRates2(input) {
1056
+ const { projectId, model } = input;
1057
+ try {
1058
+ const samples = await input.tokenRates.listLatest({
1059
+ projectId,
1060
+ providerId: model.providerId,
1061
+ modelId: model.modelId
1062
+ });
1063
+ return samples.map(({ bytes, tokens }) => ({ bytes, tokens }));
1064
+ } catch (error) {
1065
+ console.warn(`[Sixb] Could not read the bytes per token measured for '${model.providerId}/${model.modelId}'; estimating its context at ${AGENT_CONTEXT_DEFAULT_BYTES_PER_TOKEN} until a call counts.`, error);
1066
+ return [];
1067
+ }
1068
+ }
1069
+ async function recordAgentContextTokenRate(input) {
1070
+ const { projectId, runId, sample } = input;
1071
+ try {
1072
+ await input.tokenRates.record({
1073
+ projectId,
1074
+ runId,
1075
+ providerId: sample.providerId,
1076
+ modelId: sample.modelId,
1077
+ bytes: sample.bytes,
1078
+ tokens: sample.tokens,
1079
+ measuredAt: input.measuredAt
1080
+ });
1081
+ } catch (error) {
1082
+ console.warn(`[Sixb] Could not keep the bytes per token agent run '${runId}' measured; later runs start from the measurements before it.`, error);
1083
+ }
1084
+ }
1085
+ function measuringAgentContextTokenRates2(model, run) {
1086
+ return {
1087
+ ...model,
1088
+ stream: async (request) => {
1089
+ const size = measureAgentModelRequest2(request);
1090
+ const stream = await model.stream(request);
1091
+ return { ...stream, events: measuredEvents(stream.events, size, model, run) };
817
1092
  }
818
- case "tool-call": {
819
- const output = part.state === "output-available" ? truncateToolResult(stableJsonStringify2(part.output)) : truncateToolResult(part.errorText);
820
- return [
821
- `${indent}<tool_call id="${escapeXml2(part.toolCallId)}" name="${escapeXml2(part.toolName)}" state="${part.state}">`,
822
- `${indent} <input format="json">${escapeXml2(stableJsonStringify2(part.input))}</input>`,
823
- `${indent} <result>${escapeXml2(output)}</result>`,
824
- `${indent}</tool_call>`
825
- ];
1093
+ };
1094
+ }
1095
+ async function* measuredEvents(events, size, model, run) {
1096
+ let inputTokens;
1097
+ for await (const event of events) {
1098
+ if (event.type === "finish")
1099
+ inputTokens = event.usage.inputTokens;
1100
+ yield event;
1101
+ }
1102
+ const sample = inputTokens === undefined ? undefined : measureAgentContextTokenRate2({ size, inputTokens });
1103
+ if (!sample)
1104
+ return;
1105
+ await recordAgentContextTokenRate({
1106
+ ...run,
1107
+ sample: { providerId: model.providerId, modelId: model.modelId, ...sample },
1108
+ measuredAt: new Date
1109
+ });
1110
+ }
1111
+
1112
+ // src/agents/context-budget.ts
1113
+ var DEFAULT_AGENT_CONTEXT_WINDOW_TOKENS2 = 128000;
1114
+ var AGENT_CONTEXT_COMPACTED_SHARE2 = 0.6;
1115
+ var AGENT_IDLE_COMPACTION_TOKENS2 = 200000;
1116
+ function agentOutputCapTokens2(binding, definition) {
1117
+ if (binding.maxOutputTokens === undefined)
1118
+ return definition.maxOutputTokens;
1119
+ return Math.min(binding.maxOutputTokens, definition.maxOutputTokens ?? binding.maxOutputTokens);
1120
+ }
1121
+ function resolveAgentContextBudget2(selection, definition = selection.model.definition) {
1122
+ const modelWindow = definition.contextWindow ?? definition.maxInputTokens;
1123
+ const windowTokens = modelWindow ?? DEFAULT_AGENT_CONTEXT_WINDOW_TOKENS2;
1124
+ const reserveTokens = Math.max(Math.min(16384, Math.floor(windowTokens * 0.25), agentOutputCapTokens2(selection.model, definition) ?? Number.POSITIVE_INFINITY), typeof selection.reasoning === "object" ? selection.reasoning.budgetTokens + 1 : 0);
1125
+ assertPositiveSafeInteger(windowTokens, "windowTokens");
1126
+ assertPositiveSafeInteger(reserveTokens, "reserveTokens");
1127
+ if (reserveTokens >= windowTokens) {
1128
+ throw invalidBudget("reserveTokens must be less than the resolved context window.");
1129
+ }
1130
+ const inputBudgetTokens = Math.min(definition.maxInputTokens ?? Number.POSITIVE_INFINITY, windowTokens - reserveTokens);
1131
+ assertPositiveSafeInteger(inputBudgetTokens, "inputBudgetTokens");
1132
+ const tokenRates = selection.tokenRates ?? [];
1133
+ const bytesPerToken = learnedAgentContextBytesPerToken2(tokenRates);
1134
+ if (!Number.isFinite(bytesPerToken) || bytesPerToken <= 0) {
1135
+ throw invalidBudget("token rates must measure a positive number of bytes per token.");
1136
+ }
1137
+ const keepRecentTokens = Math.min(20000, Math.floor(inputBudgetTokens * 0.5));
1138
+ assertPositiveSafeInteger(keepRecentTokens, "keepRecentTokens");
1139
+ if (keepRecentTokens >= inputBudgetTokens) {
1140
+ throw invalidBudget("keepRecentTokens must be less than the resolved input budget.");
1141
+ }
1142
+ return Object.freeze({
1143
+ windowTokens,
1144
+ inputBudgetTokens,
1145
+ reserveTokens,
1146
+ keepRecentTokens,
1147
+ source: modelWindow === undefined ? "fallback" : "model",
1148
+ bytesPerToken
1149
+ });
1150
+ }
1151
+ function contextSummaryOutputTokens2(reserveTokens) {
1152
+ return Math.min(8192, Math.max(1, Math.floor(reserveTokens / 2)));
1153
+ }
1154
+ function invalidBudget(message) {
1155
+ return new AgentDefinitionError2(`[SixbAgent] Agent context ${message}`);
1156
+ }
1157
+ function assertPositiveSafeInteger(value, field) {
1158
+ if (!Number.isSafeInteger(value) || value <= 0) {
1159
+ throw invalidBudget(`${field} must be a positive safe integer.`);
1160
+ }
1161
+ }
1162
+ // src/agents/context-parts.ts
1163
+ var AGENT_CONTEXT_PARTS = [
1164
+ "system",
1165
+ "instructions",
1166
+ "memory",
1167
+ "skills",
1168
+ "ontology",
1169
+ "tools",
1170
+ "summary",
1171
+ "messages",
1172
+ "toolResults",
1173
+ "files"
1174
+ ];
1175
+ function measureAgentStepRequest2(input) {
1176
+ const system = {};
1177
+ const history = {};
1178
+ let images = 0;
1179
+ const add = (into, part, bytes) => {
1180
+ if (bytes > 0)
1181
+ into[part] = (into[part] ?? 0) + bytes;
1182
+ };
1183
+ const calls = new Map;
1184
+ for (const message of input.messages) {
1185
+ if (message.role !== "assistant")
1186
+ continue;
1187
+ for (const part of message.content) {
1188
+ if (part.type === "tool-call")
1189
+ calls.set(part.toolCallId, part);
826
1190
  }
827
1191
  }
1192
+ const resultPart = (toolCallId) => {
1193
+ const call = calls.get(toolCallId);
1194
+ return (call && agentContextFileKind(call, input.contextDirectory)) ?? "toolResults";
1195
+ };
1196
+ for (const message of input.messages) {
1197
+ switch (message.role) {
1198
+ case "system":
1199
+ if (input.systemPrompt && message.content === input.systemPrompt.text) {
1200
+ for (const [part, bytes] of Object.entries(input.systemPrompt.bytes)) {
1201
+ add(system, part, bytes ?? 0);
1202
+ }
1203
+ } else {
1204
+ add(system, "system", utf8Bytes2(message.content));
1205
+ }
1206
+ break;
1207
+ case "user":
1208
+ for (const part of message.content) {
1209
+ if (part.type === "file") {
1210
+ if (part.mediaType.toLowerCase().startsWith("image/"))
1211
+ images += 1;
1212
+ else
1213
+ add(history, "files", utf8Bytes2(`${part.filename ?? ""} ${part.mediaType}`));
1214
+ } else if (isAgentThreadSummaryText(part.text)) {
1215
+ add(history, "summary", utf8Bytes2(part.text));
1216
+ } else {
1217
+ add(history, part.text.startsWith("<attachment ") ? "files" : "messages", utf8Bytes2(part.text));
1218
+ }
1219
+ }
1220
+ break;
1221
+ case "assistant":
1222
+ for (const part of message.content) {
1223
+ switch (part.type) {
1224
+ case "text":
1225
+ case "reasoning":
1226
+ add(history, "messages", utf8Bytes2(part.text));
1227
+ break;
1228
+ case "provider-state":
1229
+ add(history, "messages", utf8Bytes2(stableJsonStringify2(part.data)));
1230
+ break;
1231
+ case "tool-call":
1232
+ add(history, "messages", utf8Bytes2(part.toolName) + utf8Bytes2(stableJsonStringify2(part.input)));
1233
+ break;
1234
+ case "tool-result":
1235
+ add(history, resultPart(part.toolCallId), toolResultBytes(part.output));
1236
+ break;
1237
+ }
1238
+ }
1239
+ break;
1240
+ case "tool":
1241
+ for (const part of message.content) {
1242
+ add(history, resultPart(part.toolCallId), toolResultBytes(part.output));
1243
+ }
1244
+ break;
1245
+ }
1246
+ }
1247
+ return {
1248
+ system,
1249
+ tools: {
1250
+ count: input.tools.length,
1251
+ bytes: input.tools.reduce((bytes, tool) => bytes + utf8Bytes2(tool.name) + utf8Bytes2(tool.description) + utf8Bytes2(stableJsonStringify2(tool.inputSchema)), 0)
1252
+ },
1253
+ history,
1254
+ ...images > 0 ? { images } : {},
1255
+ ...input.contextDirectory === undefined ? {} : { contextDirectory: input.contextDirectory }
1256
+ };
1257
+ }
1258
+ function apportionAgentContextTokens(input) {
1259
+ const total = Math.max(0, Math.round(input.totalTokens));
1260
+ const weigh = (bytes, rate, images = 0) => AGENT_CONTEXT_PARTS.map((part) => ({
1261
+ part,
1262
+ weight: (bytes[part] ?? 0) / rate + (part === "files" ? images * AGENT_IMAGE_INPUT_TOKENS2 : 0)
1263
+ }));
1264
+ const sum = (weights) => weights.reduce((tokens, { weight }) => tokens + weight, 0);
1265
+ let prompt = weigh(input.prompt, input.promptBytesPerToken);
1266
+ let history = weigh(input.history, input.bytesPerToken, input.images);
1267
+ const promptTokens = sum(prompt);
1268
+ const historyTokens = sum(history);
1269
+ if (total === 0 || promptTokens + historyTokens === 0)
1270
+ return [];
1271
+ const scale = (weights, to, from) => weights.map(({ part, weight }) => ({ part, weight: from > 0 ? weight / from * to : 0 }));
1272
+ if (promptTokens >= total || historyTokens === 0) {
1273
+ prompt = scale(prompt, total, promptTokens);
1274
+ history = scale(history, 0, historyTokens);
1275
+ } else {
1276
+ history = scale(history, total - promptTokens, historyTokens);
1277
+ }
1278
+ const exact = AGENT_CONTEXT_PARTS.map((part, index) => ({
1279
+ part,
1280
+ exact: (prompt[index]?.weight ?? 0) + (history[index]?.weight ?? 0)
1281
+ }));
1282
+ const shares = exact.map(({ part, exact }) => ({
1283
+ part,
1284
+ tokens: Math.floor(exact),
1285
+ remainder: exact - Math.floor(exact)
1286
+ }));
1287
+ let left = total - shares.reduce((tokens, share) => tokens + share.tokens, 0);
1288
+ for (const share of [...shares].sort((a, b) => b.remainder - a.remainder)) {
1289
+ if (left === 0)
1290
+ break;
1291
+ share.tokens += 1;
1292
+ left -= 1;
1293
+ }
1294
+ return shares.filter((share) => share.tokens > 0).map(({ part, tokens }) => ({ part, tokens }));
1295
+ }
1296
+ function toolResultBytes(output) {
1297
+ return typeof output.value === "string" ? utf8Bytes2(output.value) : utf8Bytes2(stableJsonStringify2(output.value));
1298
+ }
1299
+ function utf8Bytes2(value) {
1300
+ return new TextEncoder().encode(value).byteLength;
1301
+ }
1302
+ // src/agents/run-turn.ts
1303
+ async function readAgentRunContext(host, run) {
1304
+ const execution = await host.storage.executions.getById({
1305
+ projectId: host.projectId,
1306
+ id: run.executionId
1307
+ });
1308
+ return run.kind === "conversation" ? readTurnContext(host, run, execution) : readChildContext(host, run, execution);
1309
+ }
1310
+ async function readAgentTurnHistory(host, threadId) {
1311
+ const { checkpoint, messages } = await readRetainedHistory(host, threadId);
1312
+ const [sent, usageAnchor] = await Promise.all([
1313
+ readSentSettings(host, threadId, messages),
1314
+ readUsageAnchor(host, messages, checkpoint)
1315
+ ]);
1316
+ return { checkpoint, messages, ...sent, ...usageAnchor ? { usageAnchor } : {} };
1317
+ }
1318
+ async function readAgentThreadHistory(host, threadId) {
1319
+ const { checkpoint, messages } = await readRetainedHistory(host, threadId);
1320
+ const usageAnchor = await readUsageAnchor(host, messages, checkpoint);
1321
+ return { checkpoint, messages, ...usageAnchor ? { usageAnchor } : {} };
1322
+ }
1323
+ async function readRetainedHistory(host, threadId) {
1324
+ const { projectId } = host;
1325
+ const agents = host.storage.agents;
1326
+ const checkpoint = await agents.checkpoints.getLatest({ projectId, threadId });
1327
+ const { messages } = await agents.messages.list({
1328
+ projectId,
1329
+ threadId,
1330
+ ...checkpoint ? { afterSeq: checkpoint.summarizedThroughSeq } : {},
1331
+ order: "asc"
1332
+ });
1333
+ return { checkpoint, messages };
1334
+ }
1335
+ async function readTurnContext(host, run, execution) {
1336
+ const { projectId } = host;
1337
+ const [thread, participants, history] = await Promise.all([
1338
+ host.storage.agents.threads.getById({ projectId, id: run.threadId }),
1339
+ host.storage.agents.threads.listParticipants({ projectId, threadIds: [run.threadId] }),
1340
+ readAgentTurnHistory(host, run.threadId)
1341
+ ]);
1342
+ const readers = await readReaders(host, participants);
1343
+ const named = [
1344
+ ...execution?.requestedBy?.type === "user" ? [execution.requestedBy] : [],
1345
+ ...thread ? [thread.ownerPrincipal] : [],
1346
+ ...readers,
1347
+ ...history.messages.flatMap((message) => message.role === "user" && message.authorPrincipal ? [message.authorPrincipal] : [])
1348
+ ];
1349
+ return {
1350
+ kind: "conversation",
1351
+ thread,
1352
+ execution,
1353
+ participants,
1354
+ readers,
1355
+ names: await readNames(host, named),
1356
+ history
1357
+ };
1358
+ }
1359
+ async function readChildContext(host, run, execution) {
1360
+ const { projectId } = host;
1361
+ const agents = host.storage.agents;
1362
+ const [parent, thread, history, runs] = await Promise.all([
1363
+ agents.runs.getById({ projectId, id: run.parentRunId }),
1364
+ agents.threads.getById({ projectId, id: run.threadId }),
1365
+ readAgentTurnHistory(host, run.threadId),
1366
+ listSubagentThreadRuns2(agents, { projectId, threadId: run.threadId })
1367
+ ]);
1368
+ const [conversation, task] = await Promise.all([
1369
+ thread ? agents.threads.getById({ projectId, id: conversationThreadId2(thread) }) : null,
1370
+ history.checkpoint ? agents.messages.list({ projectId, threadId: run.threadId, order: "asc", limit: 1 }).then(({ messages }) => messages[0]) : undefined
1371
+ ]);
1372
+ const previous = runs.filter((each) => each.status === "succeeded").at(-1);
1373
+ const paused = previous && isPausedSubagentRun2(previous) ? previous : undefined;
1374
+ return {
1375
+ kind: "subagent",
1376
+ parent,
1377
+ execution,
1378
+ thread,
1379
+ conversation,
1380
+ history,
1381
+ ...task ? { task } : {},
1382
+ ...paused ? { paused } : {},
1383
+ names: await readNames(host, execution?.requestedBy ? [execution.requestedBy] : [])
1384
+ };
1385
+ }
1386
+ async function readReaders(host, participants) {
1387
+ const readers = await Promise.all(participants.map(async ({ principal }) => {
1388
+ const user = await readUser(host, principal.id);
1389
+ if (user?.status !== "active")
1390
+ return null;
1391
+ const allowed = await userCanRunAgent2({
1392
+ auth: host.storage.auth,
1393
+ projectId: host.projectId,
1394
+ userId: principal.id,
1395
+ security: host.security
1396
+ });
1397
+ return allowed ? principal : null;
1398
+ }));
1399
+ return readers.filter((reader) => reader !== null);
1400
+ }
1401
+ async function readNames(host, principals) {
1402
+ const users = [
1403
+ ...new Set(principals.flatMap((principal) => principal.type === "user" ? [principal.id] : []))
1404
+ ];
1405
+ const names = {};
1406
+ await Promise.all(users.map(async (id) => {
1407
+ const name = (await readUser(host, id))?.displayName;
1408
+ if (name)
1409
+ names[`user:${id}`] = name;
1410
+ }));
1411
+ return names;
1412
+ }
1413
+ function readUser(host, id) {
1414
+ return host.storage.auth.users.getById({ projectId: host.projectId, id });
1415
+ }
1416
+ async function readSentSettings(host, threadId, messages) {
1417
+ const userMessages = messages.filter((message) => message.role === "user");
1418
+ const oldest = userMessages[0];
1419
+ if (!oldest)
1420
+ return { sentTimeZones: {}, sentLocales: {} };
1421
+ const { runs } = await host.storage.agents.runs.list({
1422
+ projectId: host.projectId,
1423
+ threadId,
1424
+ kinds: ["conversation"],
1425
+ startedAfter: new Date(oldest.createdAt.getTime() - 1)
1426
+ });
1427
+ const retained = new Set(userMessages.map((message) => message.id));
1428
+ const zones = {};
1429
+ const locales = {};
1430
+ for (const run of runs) {
1431
+ if (run.kind !== "conversation" || !retained.has(run.triggerMessageId))
1432
+ continue;
1433
+ if (run.spec?.timeZone)
1434
+ zones[run.triggerMessageId] = run.spec.timeZone;
1435
+ if (run.spec?.locale)
1436
+ locales[run.triggerMessageId] = run.spec.locale;
1437
+ }
1438
+ return { sentTimeZones: zones, sentLocales: locales };
1439
+ }
1440
+ function matchingAgentUsageAnchor(history, model) {
1441
+ const anchor = history.usageAnchor;
1442
+ const index = anchor ? history.messages.findIndex((message) => message.id === anchor.messageId) : -1;
1443
+ const call = anchor?.modelCall;
1444
+ const inputTokens = call?.usage.inputTokens;
1445
+ const outputTokens = call?.usage.outputTokens;
1446
+ const lastStep = [...history.messages[index]?.parts ?? []].reverse().find((part) => part.type === "step-start");
1447
+ if (lastStep?.type === "step-start" && lastStep.reducedRequest)
1448
+ return;
1449
+ if (index < 0 || call?.providerId !== model.providerId || call.requestedModelId !== model.modelId || inputTokens === undefined || inputTokens <= 0 || outputTokens === undefined || outputTokens <= 0) {
1450
+ return;
1451
+ }
1452
+ return { index, inputTokens, outputTokens };
828
1453
  }
829
- function truncateToolResult(value) {
830
- if (value.length <= TOOL_RESULT_SUMMARY_MAX_CHARS)
831
- return value;
832
- return `${value.slice(0, TOOL_RESULT_SUMMARY_MAX_CHARS)}
833
- [truncated ${value.length - TOOL_RESULT_SUMMARY_MAX_CHARS} characters]`;
1454
+ async function readUsageAnchor(host, messages, checkpoint) {
1455
+ const afterSeq = checkpoint?.observedHeadSeq ?? 0;
1456
+ const anchor = [...messages].reverse().find((message) => message.role === "assistant" && message.seq > afterSeq && message.runId);
1457
+ if (!anchor?.runId)
1458
+ return;
1459
+ const run = await host.storage.agents.runs.getById({
1460
+ projectId: host.projectId,
1461
+ id: anchor.runId
1462
+ });
1463
+ if (!run)
1464
+ return;
1465
+ if (run.id === checkpoint?.createdByRunId && run.status !== "succeeded")
1466
+ return;
1467
+ const modelCall = await host.storage.aiUsage.getLatestForExecution({
1468
+ projectId: host.projectId,
1469
+ executionId: run.executionId
1470
+ });
1471
+ return modelCall ? { messageId: anchor.id, modelCall } : undefined;
834
1472
  }
835
- function looksLikeImage(mediaType, fileName) {
836
- if (mediaType?.toLowerCase().startsWith("image/"))
837
- return true;
838
- return /\.(?:avif|gif|jpe?g|png|webp)$/i.test(fileName ?? "");
1473
+
1474
+ // src/agents/context-request.ts
1475
+ function estimateAgentThreadRequest2(input) {
1476
+ const { retainedMessages, modelMessages } = input;
1477
+ const head = input.head ?? [];
1478
+ const fixed = "fixed" in input ? input.fixed : measureAgentContextFixed(input);
1479
+ const history = measureAgentContextHistory({
1480
+ messages: [...head, ...modelMessages],
1481
+ ...input.contextDirectory === undefined ? {} : { contextDirectory: input.contextDirectory }
1482
+ });
1483
+ const full = (bytesPerToken) => agentContextSizeTokens2(addAgentContextSizes(fixed, history), bytesPerToken);
1484
+ const anchor = matchingAgentUsageAnchor({ usageAnchor: input.usageAnchor, messages: retainedMessages }, input.model);
1485
+ if (!anchor) {
1486
+ return { tokens: full(input.bytesPerToken), bytesPerToken: input.bytesPerToken, history };
1487
+ }
1488
+ const offset = modelMessages.length - retainedMessages.length;
1489
+ const answer = retainedMessages[anchor.index];
1490
+ const lastStep = answer.parts.map((part) => part.type).lastIndexOf("step-start");
1491
+ const answered = lastStep > 0 ? [{ ...answer, parts: answer.parts.slice(0, lastStep) }] : [];
1492
+ const bytesPerToken = calibrateAgentContextBytesPerToken2({
1493
+ bytesPerToken: input.bytesPerToken,
1494
+ inputTokens: anchor.inputTokens,
1495
+ size: addAgentContextSizes(fixed, measureAgentContextHistory({
1496
+ messages: [...head, ...modelMessages.slice(0, offset + anchor.index), ...answered]
1497
+ }))
1498
+ });
1499
+ const anchored = anchor.inputTokens + anchor.outputTokens + estimateAgentContextMessagesTokens2(retainedMessages.slice(anchor.index + 1), bytesPerToken).tokens;
1500
+ return { tokens: Math.max(anchored, full(bytesPerToken)), bytesPerToken, history };
1501
+ }
1502
+ // src/agents/context-use.ts
1503
+ async function readAgentThreadContextUse2(host, input) {
1504
+ const history = await readAgentThreadHistory(host, input.threadId);
1505
+ const tokenRates = await readAgentContextTokenRates2({
1506
+ tokenRates: host.storage.agents.tokenRates,
1507
+ projectId: host.projectId,
1508
+ model: input.model
1509
+ });
1510
+ const budget = resolveAgentContextBudget2({
1511
+ model: input.model,
1512
+ ...input.reasoning === undefined ? {} : { reasoning: input.reasoning },
1513
+ tokenRates
1514
+ });
1515
+ const call = history.usageAnchor?.modelCall;
1516
+ const inputTokens = call?.usage.inputTokens;
1517
+ const lastCall = call && inputTokens !== undefined && inputTokens > 0 ? {
1518
+ inputTokens,
1519
+ ...call.usage.outputTokens === undefined ? {} : { outputTokens: call.usage.outputTokens },
1520
+ ...call.usage.cacheReadInputTokens === undefined ? {} : { cacheReadInputTokens: call.usage.cacheReadInputTokens },
1521
+ occurredAt: call.occurredAt
1522
+ } : undefined;
1523
+ const used = contextUsed(history, input.model, budget);
1524
+ const checkpoint = history.checkpoint;
1525
+ return {
1526
+ windowTokens: budget.windowTokens,
1527
+ limitTokens: budget.inputBudgetTokens,
1528
+ ...used ? { usedTokens: used.tokens, parts: used.parts } : {},
1529
+ ...lastCall ? { lastCall } : {},
1530
+ ...checkpoint ? {
1531
+ lastCompaction: {
1532
+ reason: checkpoint.reason,
1533
+ createdAt: checkpoint.createdAt,
1534
+ estimatedInputTokensBefore: checkpoint.estimatedInputTokensBefore,
1535
+ estimatedInputTokensAfter: checkpoint.estimatedInputTokensAfter
1536
+ }
1537
+ } : {}
1538
+ };
839
1539
  }
840
- function textTokens(value) {
841
- return Math.ceil(new TextEncoder().encode(value).byteLength / CHARS_PER_TOKEN);
1540
+ function contextUsed(history, model, budget) {
1541
+ const { checkpoint, messages } = history;
1542
+ if (!checkpoint && !messages.some((message) => message.role === "assistant"))
1543
+ return;
1544
+ const request = latestStepRequest(messages);
1545
+ const systemBytes = Object.values(request?.system ?? {}).reduce((total, bytes) => total + (bytes ?? 0), 0);
1546
+ const estimate = estimateAgentThreadRequest2({
1547
+ usageAnchor: history.usageAnchor,
1548
+ retainedMessages: messages,
1549
+ modelMessages: projectAgentThreadModelContext2({ checkpoint, messages }),
1550
+ model,
1551
+ bytesPerToken: budget.bytesPerToken,
1552
+ fixed: fixedAgentContextSize({
1553
+ systemBytes,
1554
+ tools: request?.tools ?? { count: 0, bytes: 0 }
1555
+ }),
1556
+ ...request?.contextDirectory === undefined ? {} : { contextDirectory: request.contextDirectory }
1557
+ });
1558
+ const after = checkpoint ? messages.filter((message) => message.seq > checkpoint.observedHeadSeq) : [];
1559
+ const tokens = checkpoint && !request ? Math.max(estimate.tokens, checkpoint.estimatedInputTokensAfter + estimateAgentContextMessagesTokens2(after, estimate.bytesPerToken).tokens) : estimate.tokens;
1560
+ return {
1561
+ tokens,
1562
+ parts: apportionAgentContextTokens({
1563
+ totalTokens: tokens,
1564
+ prompt: { ...request?.system, tools: request?.tools.bytes ?? 0 },
1565
+ promptBytesPerToken: budget.bytesPerToken,
1566
+ history: estimate.history.parts,
1567
+ ...estimate.history.images ? { images: estimate.history.images } : {},
1568
+ bytesPerToken: estimate.bytesPerToken
1569
+ })
1570
+ };
842
1571
  }
843
- function escapeXml2(value) {
844
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
1572
+ function latestStepRequest(messages) {
1573
+ for (const message of [...messages].reverse()) {
1574
+ if (message.role !== "assistant")
1575
+ continue;
1576
+ for (const part of [...message.parts].reverse()) {
1577
+ if (part.type === "step-start" && part.request)
1578
+ return part.request;
1579
+ }
1580
+ }
1581
+ return;
845
1582
  }
846
1583
  // src/agents/reference.ts
847
1584
  var agent2 = Object.freeze({
@@ -1252,11 +1989,11 @@ function toBrokerJson(value, label, details) {
1252
1989
  }
1253
1990
  }
1254
1991
  // src/agents/run-tools.ts
1255
- import { posix as posix2 } from "path";
1992
+ import { posix as posix3 } from "path";
1256
1993
 
1257
1994
  // src/agents/tool-files.ts
1258
1995
  import { createHash } from "crypto";
1259
- import { posix } from "path";
1996
+ import { posix as posix2 } from "path";
1260
1997
  var SANDBOX_CONTEXT_DIRECTORY2 = ".sixb/agent";
1261
1998
  var AGENT_FILE_MAX_BYTES2 = ARTIFACT_LIMITS2.maxFileBytes;
1262
1999
  var MAX_FILE_NAME_BYTES = 255;
@@ -1285,7 +2022,7 @@ async function storeAgentToolFile2(input) {
1285
2022
  mediaType
1286
2023
  });
1287
2024
  signal.throwIfAborted();
1288
- return { fileRef, path: toolFilePath(input.toolCallId, fileRef, fileName), bytes };
2025
+ return { fileRef, path: agentToolFilePath2(input.toolCallId, fileRef, fileName), bytes };
1289
2026
  }
1290
2027
  async function readFileBody(input) {
1291
2028
  const { body, signal } = input;
@@ -1394,10 +2131,26 @@ var SIGNATURE_REQUIRED_MEDIA_TYPES = new Set([
1394
2131
  "image/png",
1395
2132
  "image/webp"
1396
2133
  ]);
1397
- function toolFilePath(toolCallId, fileRef, fileName) {
2134
+ function agentToolFilePath2(toolCallId, fileRef, fileName) {
1398
2135
  const callKey = createHash("sha256").update(toolCallId).digest("hex").slice(0, 16);
1399
2136
  const digestKey = fileRef.digest.slice("sha256:".length, "sha256:".length + 12);
1400
- return posix.join("tool-files", callKey, `${digestKey}-${fileName}`);
2137
+ return posix2.join("tool-files", callKey, `${digestKey}-${fileName}`);
2138
+ }
2139
+ function agentToolOutputPath2(toolCallId, sha256) {
2140
+ const call = SAFE_CALL_ID.test(toolCallId) ? toolCallId : createHash("sha256").update(toolCallId).digest("hex").slice(0, 16);
2141
+ return `${AGENT_TOOL_OUTPUTS_DIRECTORY2}/${call}-${sha256.slice(0, 12)}.txt`;
2142
+ }
2143
+ var AGENT_TOOL_OUTPUTS_DIRECTORY2 = "tool-outputs";
2144
+ var SAFE_CALL_ID = /^[A-Za-z0-9_-]{1,128}$/;
2145
+ var TOOL_OUTPUT_PATH = /^tool-outputs\/[A-Za-z0-9_-]{1,128}-([0-9a-f]{12})\.txt$/;
2146
+ function isAgentToolOutputFile2(value) {
2147
+ if (typeof value !== "object" || value === null)
2148
+ return false;
2149
+ const { fileRef, path } = value;
2150
+ if (!isFileRef2(fileRef) || typeof path !== "string")
2151
+ return false;
2152
+ const digest = TOOL_OUTPUT_PATH.exec(path)?.[1];
2153
+ return digest !== undefined && fileRef.digest.startsWith(`sha256:${digest}`);
1401
2154
  }
1402
2155
  function toolFileError(toolName, message) {
1403
2156
  return new AgentToolPublicError2(`[SixbAgent] Agent tool '${toolName}' ${message}.`);
@@ -1444,7 +2197,8 @@ async function runAgentTool2(input) {
1444
2197
  }
1445
2198
  });
1446
2199
  stored.push({ fileRef, path });
1447
- return { fileRef, sandboxPath: posix2.join(SANDBOX_CONTEXT_DIRECTORY2, path) };
2200
+ const contextDirectory = input.contextDirectory ?? SANDBOX_CONTEXT_DIRECTORY2;
2201
+ return { fileRef, sandboxPath: posix3.join(contextDirectory, path) };
1448
2202
  }
1449
2203
  },
1450
2204
  attachments: input.attachments
@@ -1478,6 +2232,16 @@ function unknownAttachment(key) {
1478
2232
  return new AgentToolPublicError2(`[SixbAgent] '${key}' is not an attachment of this run. Pass a key listed in $SIXB_ATTACHMENTS.`);
1479
2233
  }
1480
2234
 
2235
+ // src/agents/step-limits.ts
2236
+ var UNATTENDED_AGENT_MAX_STEPS2 = 500;
2237
+ function assertMaxSteps(value, name) {
2238
+ if (value === undefined)
2239
+ return;
2240
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
2241
+ throw new RuntimeError2(`[Sixb] ${name} must be a positive integer.`);
2242
+ }
2243
+ }
2244
+
1481
2245
  // src/agents/run-plan.ts
1482
2246
  function readAgentRunPlan2(definitions, run, view) {
1483
2247
  const { agent, models, tools } = definitions;
@@ -1487,6 +2251,7 @@ function readAgentRunPlan2(definitions, run, view) {
1487
2251
  sandboxModels: listSandboxModels2(models),
1488
2252
  ontologyDocs: renderAgentRunOntologyDocs2({ ...view, catalog: agent.ontologyDocs })
1489
2253
  };
2254
+ const subagentMaxSteps = agent.subagentMaxSteps ?? UNATTENDED_AGENT_MAX_STEPS2;
1490
2255
  if (run.kind === "subagent") {
1491
2256
  const { model, reasoning, timeZone, locale } = run.spec;
1492
2257
  if (!models?.language?.getByRef(model)) {
@@ -1496,6 +2261,7 @@ function readAgentRunPlan2(definitions, run, view) {
1496
2261
  ...shared,
1497
2262
  model: { provider: model.provider, modelId: model.modelId },
1498
2263
  tools: toolSpecs(definitions, run.spec.toolNames),
2264
+ maxSteps: Math.min(run.spec.maxSteps ?? subagentMaxSteps, subagentMaxSteps),
1499
2265
  ...reasoning === undefined ? {} : { reasoning },
1500
2266
  ...timeZone === undefined ? {} : { timeZone },
1501
2267
  ...locale === undefined ? {} : { locale }
@@ -1512,7 +2278,8 @@ function readAgentRunPlan2(definitions, run, view) {
1512
2278
  return Object.freeze({
1513
2279
  ...shared,
1514
2280
  model: { provider: entry.provider, modelId: entry.modelId },
1515
- ...language ? { delegation: readAgentRunDelegation2(language) } : {},
2281
+ ...agent.maxSteps === undefined ? {} : { maxSteps: agent.maxSteps },
2282
+ ...language ? { delegation: readAgentRunDelegation2(language, subagentMaxSteps) } : {},
1516
2283
  tools: toolSpecs(definitions, tools.list().map((tool) => tool.name)),
1517
2284
  ...reasoning === undefined ? {} : { reasoning },
1518
2285
  ...spec?.timeZone === undefined ? {} : { timeZone: spec.timeZone },
@@ -1594,7 +2361,7 @@ function renderAgentRunOntologyDocs2(input) {
1594
2361
  views.delete(oldest);
1595
2362
  return rendered;
1596
2363
  }
1597
- function readAgentRunDelegation2(language) {
2364
+ function readAgentRunDelegation2(language, maxSteps = UNATTENDED_AGENT_MAX_STEPS2) {
1598
2365
  return {
1599
2366
  models: language.list().map(({ provider, modelId, tier, model }) => ({
1600
2367
  provider,
@@ -1604,7 +2371,8 @@ function readAgentRunDelegation2(language) {
1604
2371
  ...model.defaultReasoning === undefined ? {} : { defaultReasoning: model.defaultReasoning }
1605
2372
  })),
1606
2373
  defaultModel: { provider: language.default.provider, modelId: language.default.modelId },
1607
- tiers: language.tiers
2374
+ tiers: language.tiers,
2375
+ maxSteps
1608
2376
  };
1609
2377
  }
1610
2378
  function toolSpecs(definitions, names) {
@@ -1767,144 +2535,6 @@ async function childLimit(host, run, child) {
1767
2535
  return Math.max(limit, continuing.size);
1768
2536
  }
1769
2537
 
1770
- // src/agents/run-turn.ts
1771
- async function readAgentRunContext(host, run) {
1772
- const execution = await host.storage.executions.getById({
1773
- projectId: host.projectId,
1774
- id: run.executionId
1775
- });
1776
- return run.kind === "conversation" ? readTurnContext(host, run, execution) : readChildContext(host, run, execution);
1777
- }
1778
- async function readAgentTurnHistory(host, threadId) {
1779
- const { projectId } = host;
1780
- const agents = host.storage.agents;
1781
- const checkpoint = await agents.checkpoints.getLatest({ projectId, threadId });
1782
- const { messages } = await agents.messages.list({
1783
- projectId,
1784
- threadId,
1785
- ...checkpoint ? { afterSeq: checkpoint.summarizedThroughSeq } : {},
1786
- order: "asc"
1787
- });
1788
- const [sentTimeZones, usageAnchor] = await Promise.all([
1789
- readSentTimeZones(host, threadId, messages),
1790
- readUsageAnchor(host, messages, checkpoint?.observedHeadSeq ?? 0)
1791
- ]);
1792
- return { checkpoint, messages, sentTimeZones, ...usageAnchor ? { usageAnchor } : {} };
1793
- }
1794
- async function readTurnContext(host, run, execution) {
1795
- const { projectId } = host;
1796
- const [thread, participants, history] = await Promise.all([
1797
- host.storage.agents.threads.getById({ projectId, id: run.threadId }),
1798
- host.storage.agents.threads.listParticipants({ projectId, threadIds: [run.threadId] }),
1799
- readAgentTurnHistory(host, run.threadId)
1800
- ]);
1801
- const readers = await readReaders(host, participants);
1802
- const named = [
1803
- ...execution?.requestedBy?.type === "user" ? [execution.requestedBy] : [],
1804
- ...thread ? [thread.ownerPrincipal] : [],
1805
- ...readers,
1806
- ...history.messages.flatMap((message) => message.role === "user" && message.authorPrincipal ? [message.authorPrincipal] : [])
1807
- ];
1808
- return {
1809
- kind: "conversation",
1810
- thread,
1811
- execution,
1812
- participants,
1813
- readers,
1814
- names: await readNames(host, named),
1815
- history
1816
- };
1817
- }
1818
- async function readChildContext(host, run, execution) {
1819
- const { projectId } = host;
1820
- const agents = host.storage.agents;
1821
- const [parent, thread, { messages }, runs] = await Promise.all([
1822
- agents.runs.getById({ projectId, id: run.parentRunId }),
1823
- agents.threads.getById({ projectId, id: run.threadId }),
1824
- agents.messages.list({ projectId, threadId: run.threadId, order: "asc" }),
1825
- listSubagentThreadRuns2(agents, { projectId, threadId: run.threadId })
1826
- ]);
1827
- const conversation = thread ? await agents.threads.getById({ projectId, id: conversationThreadId2(thread) }) : null;
1828
- const previous = runs.filter((each) => each.status === "succeeded").at(-1);
1829
- const paused = previous && isPausedSubagentRun2(previous) ? previous : undefined;
1830
- return {
1831
- kind: "subagent",
1832
- parent,
1833
- execution,
1834
- thread,
1835
- conversation,
1836
- messages,
1837
- ...paused ? { paused } : {},
1838
- names: await readNames(host, execution?.requestedBy ? [execution.requestedBy] : [])
1839
- };
1840
- }
1841
- async function readReaders(host, participants) {
1842
- const readers = await Promise.all(participants.map(async ({ principal }) => {
1843
- const user = await readUser(host, principal.id);
1844
- if (user?.status !== "active")
1845
- return null;
1846
- const allowed = await userCanRunAgent2({
1847
- auth: host.storage.auth,
1848
- projectId: host.projectId,
1849
- userId: principal.id,
1850
- security: host.security
1851
- });
1852
- return allowed ? principal : null;
1853
- }));
1854
- return readers.filter((reader) => reader !== null);
1855
- }
1856
- async function readNames(host, principals) {
1857
- const users = [
1858
- ...new Set(principals.flatMap((principal) => principal.type === "user" ? [principal.id] : []))
1859
- ];
1860
- const names = {};
1861
- await Promise.all(users.map(async (id) => {
1862
- const name = (await readUser(host, id))?.displayName;
1863
- if (name)
1864
- names[`user:${id}`] = name;
1865
- }));
1866
- return names;
1867
- }
1868
- function readUser(host, id) {
1869
- return host.storage.auth.users.getById({ projectId: host.projectId, id });
1870
- }
1871
- async function readSentTimeZones(host, threadId, messages) {
1872
- const userMessages = messages.filter((message) => message.role === "user");
1873
- const oldest = userMessages[0];
1874
- if (!oldest)
1875
- return {};
1876
- const { runs } = await host.storage.agents.runs.list({
1877
- projectId: host.projectId,
1878
- threadId,
1879
- kinds: ["conversation"],
1880
- startedAfter: new Date(oldest.createdAt.getTime() - 1)
1881
- });
1882
- const retained = new Set(userMessages.map((message) => message.id));
1883
- const zones = {};
1884
- for (const run of runs) {
1885
- if (run.kind === "conversation" && run.spec?.timeZone && retained.has(run.triggerMessageId)) {
1886
- zones[run.triggerMessageId] = run.spec.timeZone;
1887
- }
1888
- }
1889
- return zones;
1890
- }
1891
- async function readUsageAnchor(host, messages, afterSeq) {
1892
- const anchor = [...messages].reverse().find((message) => message.role === "assistant" && message.seq > afterSeq && message.runId);
1893
- if (!anchor?.runId)
1894
- return;
1895
- const run = await host.storage.agents.runs.getById({
1896
- projectId: host.projectId,
1897
- id: anchor.runId
1898
- });
1899
- if (!run)
1900
- return;
1901
- const modelCall = await host.storage.aiUsage.getLatestForExecution({
1902
- projectId: host.projectId,
1903
- executionId: run.executionId
1904
- });
1905
- return modelCall ? { messageId: anchor.id, modelCall } : undefined;
1906
- }
1907
-
1908
2538
  // src/agents/run-session.ts
1909
2539
  async function claimAgentRun2(host, input) {
1910
2540
  const run = await startOrReclaim(host.storage.agents, host.projectId, input);
@@ -2027,7 +2657,11 @@ async function openAgentRunSession2(host, run, cancelWith = [], stop) {
2027
2657
  languageModels.set(key, resolved);
2028
2658
  resolved.catch(() => languageModels.delete(key));
2029
2659
  }
2030
- return (await openedModelCalls()).wrapModel(await resolved);
2660
+ return measuringAgentContextTokenRates2((await openedModelCalls()).wrapModel(await resolved), {
2661
+ tokenRates: agents.tokenRates,
2662
+ projectId: host.projectId,
2663
+ runId: run.id
2664
+ });
2031
2665
  }
2032
2666
  },
2033
2667
  async renewLease(leaseExpiresAt) {
@@ -2058,7 +2692,7 @@ async function openAgentRunSession2(host, run, cancelWith = [], stop) {
2058
2692
  threads,
2059
2693
  artifacts: agentRunArtifacts2(host, run, executionToken, runSdk),
2060
2694
  files,
2061
- async callTool(call, { signal, maxFileBytes }) {
2695
+ async callTool(call, { signal, maxFileBytes, contextDirectory }) {
2062
2696
  const offered = run.kind === "subagent" ? run.spec.toolNames : undefined;
2063
2697
  const definition = offered === undefined || offered.includes(call.toolName) ? host.definitions.tools.getByName(call.toolName) : null;
2064
2698
  if (!definition) {
@@ -2079,7 +2713,8 @@ async function openAgentRunSession2(host, run, cancelWith = [], stop) {
2079
2713
  files
2080
2714
  }),
2081
2715
  files,
2082
- ...maxFileBytes === undefined ? {} : { maxFileBytes }
2716
+ ...maxFileBytes === undefined ? {} : { maxFileBytes },
2717
+ ...contextDirectory === undefined ? {} : { contextDirectory }
2083
2718
  });
2084
2719
  },
2085
2720
  authorization: (ref) => resolveInheritedAgentExecutionAuthorization2({
@@ -2091,10 +2726,16 @@ async function openAgentRunSession2(host, run, cancelWith = [], stop) {
2091
2726
  async plan() {
2092
2727
  const { sixb, authorization } = await bind();
2093
2728
  const propertyClearance = resolveAgentPropertyClearance2(host.definitions.ontology, authorization);
2094
- return readAgentRunPlan2(host.definitions, run, {
2729
+ const plan = readAgentRunPlan2(host.definitions, run, {
2095
2730
  sixb,
2096
2731
  ...propertyClearance === undefined ? {} : { propertyClearance }
2097
2732
  });
2733
+ const tokenRates = await readAgentContextTokenRates2({
2734
+ tokenRates: agents.tokenRates,
2735
+ projectId: host.projectId,
2736
+ model: { providerId: plan.model.provider, modelId: plan.model.modelId }
2737
+ });
2738
+ return Object.freeze({ ...plan, tokenRates });
2098
2739
  },
2099
2740
  async memory({ asOf }) {
2100
2741
  const participants = run.kind === "conversation" ? await agents.threads.listParticipants({
@@ -2236,7 +2877,13 @@ async function startOrReclaim(agents, projectId, input) {
2236
2877
  if (run.status !== "queued" && run.status !== "running")
2237
2878
  return null;
2238
2879
  try {
2239
- return run.status === "queued" ? sameKind(run, await agents.runs.start({ projectId, id: run.id, modelId: input.modelId, execution }), "starting") : sameKind(run, await agents.runs.reclaim({ projectId, id: run.id, execution, ifLapsedBy: new Date }), "reclaiming");
2880
+ return run.status === "queued" ? sameKind(run, await agents.runs.start({
2881
+ projectId,
2882
+ id: run.id,
2883
+ modelId: input.modelId,
2884
+ execution,
2885
+ ...input.onComputer ? { onComputer: input.onComputer } : {}
2886
+ }), "starting") : sameKind(run, await agents.runs.reclaim({ projectId, id: run.id, execution, ifLapsedBy: new Date }), "reclaiming");
2240
2887
  } catch (error) {
2241
2888
  if (error instanceof AgentStorageError2 && error.code === "invalid_state")
2242
2889
  return null;
@@ -2584,7 +3231,7 @@ function createHttpAgentRunSession2(input) {
2584
3231
  message: (messageId) => call("threads.message", [messageId]),
2585
3232
  messages: (query) => call("threads.messages", [query])
2586
3233
  },
2587
- callTool: (toolCall, { signal, maxFileBytes }) => call("callTool", [toolCall, maxFileBytes === undefined ? {} : { maxFileBytes }], signal),
3234
+ callTool: (toolCall, { signal, ...options }) => call("callTool", [toolCall, options], signal),
2588
3235
  artifacts: {
2589
3236
  list: (query) => call("artifacts.list", [query]),
2590
3237
  getVersion: (...args) => call("artifacts.getVersion", args),
@@ -2639,7 +3286,7 @@ async function claimAgentRunOverHttp2(input) {
2639
3286
  headers: { authorization: input.authorization, "content-type": "application/json" },
2640
3287
  body: encodeWireValue2({
2641
3288
  leaseExpiresAt: input.leaseExpiresAt,
2642
- ...input.computerId === undefined ? {} : { computerId: input.computerId }
3289
+ ...input.computer === undefined ? {} : { computer: input.computer }
2643
3290
  })
2644
3291
  }));
2645
3292
  const claimed = await result(response);
@@ -2822,6 +3469,7 @@ function isValidToken(kind, input) {
2822
3469
  }
2823
3470
 
2824
3471
  // src/agents/run-session-serve.ts
3472
+ var AGENT_RUN_SESSION_BODY_MAX_BYTES = AGENT_INLINE_IMAGE_LIMITS2.maxBytes + 24 * 1024 * 1024;
2825
3473
  var OPERATIONS = {
2826
3474
  plan: (session) => session.plan(),
2827
3475
  memory: (session, [input]) => session.memory(input),
@@ -2861,13 +3509,14 @@ var OPERATIONS = {
2861
3509
  },
2862
3510
  "files.stat": (session, [blobId]) => session.files.stat(blobId)
2863
3511
  };
2864
- async function serveAgentRunSession2(host, request) {
3512
+ async function serveAgentRunSession2(host, request, options = {}) {
2865
3513
  const target = parseAgentRunSessionPath(new URL(request.url).pathname);
2866
3514
  if (!target)
2867
3515
  return null;
2868
3516
  const admitted = await admitRunner(host, request, target.runId);
2869
3517
  if (admitted instanceof Response)
2870
3518
  return admitted;
3519
+ options.admitted?.();
2871
3520
  if (!await stopRecorded(host, admitted)) {
2872
3521
  return serveOperation(host, admitted, target.operation, request);
2873
3522
  }
@@ -2909,9 +3558,12 @@ async function serveOperation(host, admitted, operation, request) {
2909
3558
  if (!run || request.method !== "POST") {
2910
3559
  return json({ error: { kind: "Error", message: `[Sixb] No session operation '${operation}'.` } }, 404);
2911
3560
  }
2912
- const { args } = decodeWireValue2(await request.text());
3561
+ const { args } = decodeWireValue2(await readBodyText(request));
2913
3562
  return json({ result: await run(session, args ?? [], request.signal) });
2914
3563
  } catch (error) {
3564
+ streaming = false;
3565
+ if (error instanceof SessionBodyTooLargeError)
3566
+ return await failTooLarge(session, operation);
2915
3567
  const wire = encodeWireError2(error);
2916
3568
  return json({ error: wire }, wireErrorStatus(wire));
2917
3569
  } finally {
@@ -2929,6 +3581,7 @@ async function claimAgentRunForRunner2(host, input) {
2929
3581
  const session = await claimAgentRun2(host, {
2930
3582
  run: input.run,
2931
3583
  leaseExpiresAt: capLease(input.leaseExpiresAt),
3584
+ ...input.onComputer ? { onComputer: input.onComputer } : {},
2932
3585
  ...input.run.kind === "subagent" ? { cancelWith: [input.run.parentRunId] } : {}
2933
3586
  });
2934
3587
  if (!session)
@@ -2950,7 +3603,7 @@ function capLease(leaseExpiresAt) {
2950
3603
  return new Date(Number.isFinite(requested) ? Math.min(requested, latest) : latest).toISOString();
2951
3604
  }
2952
3605
  async function claimChild(host, session, request) {
2953
- const { args } = decodeWireValue2(await request.text());
3606
+ const { args } = decodeWireValue2(await readBodyText(request));
2954
3607
  const [childRunId, leaseExpiresAt] = args ?? [];
2955
3608
  const child = await session.children.get(childRunId);
2956
3609
  if (child?.kind !== "subagent" || child.parentRunId !== session.run.id) {
@@ -3011,13 +3664,23 @@ async function finish(session, outcome, messages) {
3011
3664
  function ownMessages(run, messages) {
3012
3665
  return messages?.map(({ authorPrincipal: _author, ...message }) => ({
3013
3666
  ...message,
3667
+ parts: message.parts.map(withSavedOutputChecked),
3014
3668
  projectId: run.projectId,
3015
3669
  threadId: run.threadId,
3016
3670
  runId: run.id
3017
3671
  }));
3018
3672
  }
3673
+ function withSavedOutputChecked(part) {
3674
+ if (part.type !== "tool-call" || part.state !== "output-available")
3675
+ return part;
3676
+ if (part.outputFile === undefined || isAgentToolOutputFile2(part.outputFile))
3677
+ return part;
3678
+ console.warn(`[Sixb] A runner's saved output for call '${part.toolCallId}' names no file of its own: its message keeps the output without it.`);
3679
+ const { outputFile: _outputFile, ...rest } = part;
3680
+ return rest;
3681
+ }
3019
3682
  async function streamModelCall(session, request) {
3020
- const { ref, call } = decodeWireValue2(await request.text());
3683
+ const { ref, call } = decodeWireValue2(await readBodyText(request));
3021
3684
  const model = await session.models.language(ref);
3022
3685
  const opened = await model.stream({ ...call, signal: request.signal });
3023
3686
  const encoder = new TextEncoder;
@@ -3048,7 +3711,7 @@ async function streamModelCall(session, request) {
3048
3711
  return new Response(body, { headers: { "content-type": "application/x-ndjson" } });
3049
3712
  }
3050
3713
  async function publishEvents(session, request) {
3051
- const { events } = decodeWireValue2(await request.text());
3714
+ const { events } = decodeWireValue2(await readBodyText(request));
3052
3715
  const sink = session.events;
3053
3716
  for (const { method, input } of events) {
3054
3717
  if (!EVENT_METHODS.has(method))
@@ -3076,7 +3739,7 @@ async function putFile(session, request) {
3076
3739
  const url = new URL(request.url);
3077
3740
  const size = url.searchParams.get("size");
3078
3741
  const fileRef = await session.files.put({
3079
- body: new Uint8Array(await request.arrayBuffer()),
3742
+ body: await readBody(request),
3080
3743
  ...size === null ? {} : { expectedSizeBytes: Number(size) },
3081
3744
  ...optionalParam(url, "fileName"),
3082
3745
  ...optionalParam(url, "mediaType"),
@@ -3095,69 +3758,61 @@ function optionalParam(url, name) {
3095
3758
  const value = url.searchParams.get(name);
3096
3759
  return value === null ? {} : { [name]: value };
3097
3760
  }
3761
+
3762
+ class SessionBodyTooLargeError extends Error {
3763
+ name = "SessionBodyTooLargeError";
3764
+ }
3765
+ async function readBody(request) {
3766
+ const declared = Number(request.headers.get("content-length") ?? Number.NaN);
3767
+ if (declared > AGENT_RUN_SESSION_BODY_MAX_BYTES)
3768
+ throw new SessionBodyTooLargeError;
3769
+ if (!request.body)
3770
+ return new Uint8Array;
3771
+ const chunks = [];
3772
+ let total = 0;
3773
+ for await (const chunk of request.body) {
3774
+ total += chunk.byteLength;
3775
+ if (total > AGENT_RUN_SESSION_BODY_MAX_BYTES)
3776
+ throw new SessionBodyTooLargeError;
3777
+ chunks.push(chunk);
3778
+ }
3779
+ const body = new Uint8Array(total);
3780
+ let offset = 0;
3781
+ for (const chunk of chunks) {
3782
+ body.set(chunk, offset);
3783
+ offset += chunk.byteLength;
3784
+ }
3785
+ return body;
3786
+ }
3787
+ async function readBodyText(request) {
3788
+ return new TextDecoder().decode(await readBody(request));
3789
+ }
3790
+ async function failTooLarge(session, operation) {
3791
+ const { run } = session;
3792
+ const megabytes = AGENT_RUN_SESSION_BODY_MAX_BYTES / (1024 * 1024);
3793
+ const completedAt = new Date;
3794
+ const error = captureSixbFailure2(withFailureMessage2(createSixbError2("agent.execution_failed", `[Sixb] Agent run '${run.id}' sent its session more than ${megabytes} MiB in one request (${operation}).`), `The conversation grew past the ${megabytes} MiB a computer run can send at once. Start a new conversation, or ask for less in one message.`), {
3795
+ allowedCodes: AGENT_RUN_FAILURE_CODES2,
3796
+ defaultCode: "agent.execution_failed",
3797
+ details: run.kind === "conversation" ? { runId: run.id, threadId: run.threadId } : { parentRunId: run.parentRunId, runId: run.id },
3798
+ at: completedAt
3799
+ });
3800
+ try {
3801
+ const ended = await session.finish({ status: "failed", error, completedAt });
3802
+ await session.events.publishRunFinished(ended);
3803
+ } catch (failure) {
3804
+ if (!(failure instanceof AgentExecutionLostError2))
3805
+ throw failure;
3806
+ }
3807
+ const wire = encodeWireError2(new AgentExecutionLostError2(run.id));
3808
+ return json({ error: wire }, wireErrorStatus(wire));
3809
+ }
3098
3810
  function json(body, status = 200) {
3099
3811
  return new Response(encodeWireValue2(body), {
3100
3812
  status,
3101
3813
  headers: { "content-type": "application/json" }
3102
3814
  });
3103
3815
  }
3104
- // src/agents/thread-context-projection.ts
3105
- function projectAgentThreadModelContext2(input) {
3106
- const { checkpoint, messages } = input;
3107
- if (!checkpoint)
3108
- return messages;
3109
- assertConsistentCheckpointProjection(checkpoint, messages);
3110
- return [
3111
- {
3112
- role: "user",
3113
- parts: [{ type: "text", text: serializeThreadSummary(checkpoint.summary) }]
3114
- },
3115
- ...messages
3116
- ];
3117
- }
3118
- function assertConsistentCheckpointProjection(checkpoint, messages) {
3119
- if (checkpoint.summaryFormatVersion !== 1 || checkpoint.summary.trim().length === 0) {
3120
- throw projectionError(checkpoint, "has an invalid summary");
3121
- }
3122
- if (checkpoint.summarizedThroughSeq >= checkpoint.observedHeadSeq) {
3123
- throw projectionError(checkpoint, "does not retain its observed head");
3124
- }
3125
- if (messages.length === 0) {
3126
- throw projectionError(checkpoint, "has no retained messages");
3127
- }
3128
- let expectedSeq = checkpoint.summarizedThroughSeq + 1;
3129
- for (const message of messages) {
3130
- if (message.projectId !== checkpoint.projectId || message.threadId !== checkpoint.threadId) {
3131
- throw projectionError(checkpoint, "contains a message from another thread");
3132
- }
3133
- if (message.seq !== expectedSeq) {
3134
- throw projectionError(checkpoint, `has a sequence gap before message '${message.id}'`);
3135
- }
3136
- expectedSeq += 1;
3137
- }
3138
- if (messages[0]?.role !== "user") {
3139
- throw projectionError(checkpoint, "does not begin at a user turn boundary");
3140
- }
3141
- if ((messages.at(-1)?.seq ?? 0) < checkpoint.observedHeadSeq) {
3142
- throw projectionError(checkpoint, "ends before the checkpoint's observed head");
3143
- }
3144
- }
3145
- function serializeThreadSummary(summary) {
3146
- return [
3147
- "The earlier conversation was compacted into this continuation summary.",
3148
- "",
3149
- "<sixb_thread_summary>",
3150
- escapeXml3(summary),
3151
- "</sixb_thread_summary>"
3152
- ].join(`
3153
- `);
3154
- }
3155
- function projectionError(checkpoint, detail) {
3156
- return new Error(`[Sixb] Agent context checkpoint '${checkpoint.id}' for thread '${checkpoint.threadId}' ${detail}.`);
3157
- }
3158
- function escapeXml3(value) {
3159
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
3160
- }
3161
3816
  // src/agents/workflow-node-session.ts
3162
3817
  class WorkflowResumeDispatchError2 extends Error {
3163
3818
  nodeRunId;
@@ -3389,6 +4044,6 @@ function requireFinishedAt(record) {
3389
4044
  }
3390
4045
  return record.finishedAt;
3391
4046
  }
3392
- export { serializeAgentContextForModel2, isAgentToolResult2, toModelMessages2, attachmentKey2, toolResultAttachmentKey2, attachmentKeyMessageId2, findMessageAttachment2, listMessageAttachments2, AGENT_RESERVED_TOOL_NAMES2, isAgentToolDefinition2, validateAndNormalizeAgentToolInput2, toolsFromProjectConfig, defineAgentTool2, AGENT_CONTEXT_ESTIMATOR_VERSION2, shouldCompactAgentContext2, estimateAgentContextRequestTokens2, estimateAgentContextMessagesTokens2, selectAgentContextCompactionBoundary2, serializeAgentMessagesForSummary2, agent2, afterAgentRunFinished2, stopAgentRunChild2, AgentExecutionLostError2, AgentRunRefusedError2, isTerminalOrExecutionGone2, agentRunArtifacts2, NOOP_STREAM_SINK2, createBrokerStreamSink2, isolateStreamSink2, withAgentActivityStream2, SANDBOX_CONTEXT_DIRECTORY2, AGENT_FILE_MAX_BYTES2, storeAgentToolFile2, agentToolSpec2, runAgentTool2, threadToolAttachments2, readAgentRunPlan2, listSandboxModels2, readAgentRunMemory2, renderAgentRunOntologyDocs2, readAgentRunDelegation2, claimAgentRun2, openAgentRunSession2, agentRunPeople2, watchAgentRunCancel2, AgentFinalizationError2, AgentTurnInterruptedError2, interruptedError2, agentRunLeaseLapsed2, endInterruptedAgentRun2, endLapsedAgentRuns2, encodeWireValue2, decodeWireValue2, encodeWireError2, createHttpAgentRunSession2, claimAgentRunOverHttp2, claimAgentRunChildOverHttp2, AGENT_API_ROUTES2, createAgentRunToken2, isAgentRunToken2, agentRunTokenRunId2, isValidAgentRunToken2, createAgentRunnerToken2, isAgentRunnerToken2, isAllowedAgentApiRequest2, findAgentApiRoute2, serveAgentRunSession2, claimAgentRunForRunner2, projectAgentThreadModelContext2, WorkflowResumeDispatchError2, claimWorkflowAgentNode2, enqueueWorkflowAgentNodeResume2 };
4047
+ export { serializeAgentContextForModel2, isAgentToolResult2, toModelMessages2, agentMessageSteps2, attachmentKey2, toolResultAttachmentKey2, attachmentKeyMessageId2, findMessageAttachment2, listMessageAttachments2, AGENT_RESERVED_TOOL_NAMES2, isAgentToolDefinition2, validateAndNormalizeAgentToolInput2, toolsFromProjectConfig, defineAgentTool2, AGENT_INLINE_IMAGE_LIMITS2, AGENT_IMAGE_INPUT_TOKENS2, projectAgentThreadModelContext2, AGENT_CONTEXT_ESTIMATOR_VERSION2, shouldCompactAgentContext2, estimateAgentContextRequestTokens2, estimateAgentContextMessagesTokens2, agentContextSizeTokens2, measureAgentModelRequest2, measureModelRequest2, selectAgentContextCompactionBoundary2, measureAgentContextTokenRate2, calibrateAgentContextBytesPerToken2, learnedAgentContextBytesPerToken2, readAgentContextTokenRates2, measuringAgentContextTokenRates2, DEFAULT_AGENT_CONTEXT_WINDOW_TOKENS2, AGENT_CONTEXT_COMPACTED_SHARE2, AGENT_IDLE_COMPACTION_TOKENS2, agentOutputCapTokens2, resolveAgentContextBudget2, contextSummaryOutputTokens2, measureAgentStepRequest2, estimateAgentThreadRequest2, readAgentThreadContextUse2, agent2, afterAgentRunFinished2, stopAgentRunChild2, AgentExecutionLostError2, AgentRunRefusedError2, isTerminalOrExecutionGone2, agentRunArtifacts2, NOOP_STREAM_SINK2, createBrokerStreamSink2, isolateStreamSink2, withAgentActivityStream2, SANDBOX_CONTEXT_DIRECTORY2, AGENT_FILE_MAX_BYTES2, storeAgentToolFile2, agentToolFilePath2, agentToolOutputPath2, AGENT_TOOL_OUTPUTS_DIRECTORY2, isAgentToolOutputFile2, agentToolSpec2, runAgentTool2, threadToolAttachments2, UNATTENDED_AGENT_MAX_STEPS2, assertMaxSteps, readAgentRunPlan2, listSandboxModels2, readAgentRunMemory2, renderAgentRunOntologyDocs2, readAgentRunDelegation2, claimAgentRun2, openAgentRunSession2, agentRunPeople2, watchAgentRunCancel2, AgentFinalizationError2, AgentTurnInterruptedError2, interruptedError2, agentRunLeaseLapsed2, endInterruptedAgentRun2, endLapsedAgentRuns2, encodeWireValue2, decodeWireValue2, encodeWireError2, createHttpAgentRunSession2, claimAgentRunOverHttp2, claimAgentRunChildOverHttp2, AGENT_API_ROUTES2, createAgentRunToken2, isAgentRunToken2, agentRunTokenRunId2, isValidAgentRunToken2, createAgentRunnerToken2, isAgentRunnerToken2, isAllowedAgentApiRequest2, findAgentApiRoute2, serveAgentRunSession2, claimAgentRunForRunner2, WorkflowResumeDispatchError2, claimWorkflowAgentNode2, enqueueWorkflowAgentNodeResume2 };
3393
4048
 
3394
- //# debugId=BA838CF877E05E2964756E2164756E21
4049
+ //# debugId=BC4600024A7A9ABB64756E2164756E21