@sixb/core 0.2.5 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (385) hide show
  1. package/dist/actions/index.js +36 -35
  2. package/dist/actions/index.js.map +1 -1
  3. package/dist/actions/validation.d.ts.map +1 -1
  4. package/dist/agents/errors.d.ts +1 -1
  5. package/dist/agents/errors.d.ts.map +1 -1
  6. package/dist/agents/execution.d.ts +17 -2
  7. package/dist/agents/execution.d.ts.map +1 -1
  8. package/dist/agents/index.d.ts +2 -2
  9. package/dist/agents/index.d.ts.map +1 -1
  10. package/dist/agents/index.js +50 -44
  11. package/dist/agents/index.js.map +1 -1
  12. package/dist/agents/model-routing.d.ts +5 -2
  13. package/dist/agents/model-routing.d.ts.map +1 -1
  14. package/dist/agents/request.d.ts +45 -4
  15. package/dist/agents/request.d.ts.map +1 -1
  16. package/dist/agents/run-events.d.ts +4 -0
  17. package/dist/agents/run-events.d.ts.map +1 -1
  18. package/dist/agents/run-session-children.d.ts.map +1 -1
  19. package/dist/agents/run-turn.d.ts +9 -1
  20. package/dist/agents/run-turn.d.ts.map +1 -1
  21. package/dist/agents/streams/index.d.ts +1 -1
  22. package/dist/agents/streams/index.d.ts.map +1 -1
  23. package/dist/agents/streams/index.js +1 -1
  24. package/dist/agents/streams/internal.d.ts +2 -1
  25. package/dist/agents/streams/internal.d.ts.map +1 -1
  26. package/dist/agents/streams/internal.js +22 -2
  27. package/dist/agents/streams/internal.js.map +1 -1
  28. package/dist/agents/streams/protocol.d.ts +37 -0
  29. package/dist/agents/streams/protocol.d.ts.map +1 -1
  30. package/dist/agents/streams/steps.d.ts +24 -0
  31. package/dist/agents/streams/steps.d.ts.map +1 -0
  32. package/dist/agents/thread-access.d.ts +44 -2
  33. package/dist/agents/thread-access.d.ts.map +1 -1
  34. package/dist/artifacts/live/server.js +19 -18
  35. package/dist/artifacts/live/server.js.map +1 -1
  36. package/dist/artifacts/publish/index.js +18 -17
  37. package/dist/artifacts/publish/index.js.map +1 -1
  38. package/dist/artifacts/publish/merge.d.ts +2 -1
  39. package/dist/artifacts/publish/merge.d.ts.map +1 -1
  40. package/dist/artifacts/run-query.d.ts.map +1 -1
  41. package/dist/auth/index.js +6 -6
  42. package/dist/authorization/index.js +2 -2
  43. package/dist/bootstrap/index.js +40 -38
  44. package/dist/bootstrap/index.js.map +2 -2
  45. package/dist/calendar.d.ts +55 -0
  46. package/dist/calendar.d.ts.map +1 -0
  47. package/dist/calendar.js +19 -0
  48. package/dist/calendar.js.map +9 -0
  49. package/dist/{chunk-5a4a52tq.js → chunk-0pmpwn3g.js} +18 -2
  50. package/dist/chunk-0pmpwn3g.js.map +10 -0
  51. package/dist/{chunk-xcrnrpfh.js → chunk-394zjzjs.js} +20 -10
  52. package/dist/{chunk-xcrnrpfh.js.map → chunk-394zjzjs.js.map} +5 -5
  53. package/dist/{chunk-stmxh0hv.js → chunk-3neam1y5.js} +2 -2
  54. package/dist/{chunk-zeykm8my.js → chunk-3qtk0070.js} +16 -42
  55. package/dist/chunk-3qtk0070.js.map +14 -0
  56. package/dist/{chunk-0mvjpgvm.js → chunk-425ydk65.js} +4 -4
  57. package/dist/{chunk-s5pj68fa.js → chunk-5sswe5ej.js} +2 -2
  58. package/dist/chunk-6hfbz4d0.js +98 -0
  59. package/dist/chunk-6hfbz4d0.js.map +10 -0
  60. package/dist/{chunk-3zagkr6w.js → chunk-7mhbs9yy.js} +4 -4
  61. package/dist/{chunk-3zagkr6w.js.map → chunk-7mhbs9yy.js.map} +1 -1
  62. package/dist/{chunk-fpf57gca.js → chunk-7r9mqpva.js} +273 -66
  63. package/dist/{chunk-fpf57gca.js.map → chunk-7r9mqpva.js.map} +5 -5
  64. package/dist/{chunk-ewqn51gr.js → chunk-88xeh6zx.js} +6 -4
  65. package/dist/{chunk-ewqn51gr.js.map → chunk-88xeh6zx.js.map} +4 -4
  66. package/dist/chunk-90nqenq8.js +386 -0
  67. package/dist/chunk-90nqenq8.js.map +14 -0
  68. package/dist/{chunk-gjhrz66x.js → chunk-9c9yknwt.js} +247 -20
  69. package/dist/{chunk-gjhrz66x.js.map → chunk-9c9yknwt.js.map} +6 -6
  70. package/dist/{chunk-q9nkpr8k.js → chunk-9tpmfh3n.js} +1 -1
  71. package/dist/chunk-9wr3yajk.js.map +2 -2
  72. package/dist/{chunk-z1njfqqs.js → chunk-ats8y3d9.js} +721 -156
  73. package/dist/{chunk-z1njfqqs.js.map → chunk-ats8y3d9.js.map} +13 -13
  74. package/dist/{chunk-68hm50qh.js → chunk-bcz9dxtf.js} +16 -46
  75. package/dist/chunk-bcz9dxtf.js.map +12 -0
  76. package/dist/{chunk-naxjka9v.js → chunk-brhp9d97.js} +2 -2
  77. package/dist/{chunk-8a8k38tz.js → chunk-brybqw5k.js} +1 -1
  78. package/dist/{chunk-s1mqyqmm.js → chunk-bs1sd0e0.js} +12 -8
  79. package/dist/chunk-bs1sd0e0.js.map +18 -0
  80. package/dist/{chunk-vehcr9eb.js → chunk-cg7cygfj.js} +1 -1
  81. package/dist/chunk-dq3t5sr3.js +114 -0
  82. package/dist/chunk-dq3t5sr3.js.map +11 -0
  83. package/dist/{chunk-r2psmn42.js → chunk-eg6xqef7.js} +1 -1
  84. package/dist/{chunk-zxhym8tr.js → chunk-f05994as.js} +1 -1
  85. package/dist/{chunk-5t9gm5tt.js → chunk-fmgf9h5e.js} +38 -14
  86. package/dist/chunk-fmgf9h5e.js.map +22 -0
  87. package/dist/{chunk-ey1p8w68.js → chunk-gaj8djsw.js} +80 -4
  88. package/dist/chunk-gaj8djsw.js.map +13 -0
  89. package/dist/{chunk-1yh6jgtz.js → chunk-grt2j5vp.js} +2 -2
  90. package/dist/{chunk-zft9bzbc.js → chunk-hkbks1xm.js} +2 -1
  91. package/dist/{chunk-zft9bzbc.js.map → chunk-hkbks1xm.js.map} +3 -3
  92. package/dist/{chunk-rtdrm592.js → chunk-htdzx40w.js} +2 -2
  93. package/dist/{chunk-bc3y6gff.js → chunk-jka26v8c.js} +1 -1
  94. package/dist/{chunk-m3qx2pns.js → chunk-jt012fxq.js} +28 -12
  95. package/dist/{chunk-m3qx2pns.js.map → chunk-jt012fxq.js.map} +5 -5
  96. package/dist/{chunk-k3jh8gsg.js → chunk-kft7mp7z.js} +20 -3
  97. package/dist/chunk-kft7mp7z.js.map +10 -0
  98. package/dist/{chunk-qavwr628.js → chunk-n1hbwc6y.js} +5 -6
  99. package/dist/chunk-n1hbwc6y.js.map +12 -0
  100. package/dist/chunk-nxysqbt0.js.map +2 -2
  101. package/dist/{chunk-pqvvqc65.js → chunk-pqj8vff9.js} +3 -3
  102. package/dist/{chunk-wqe9shx2.js → chunk-qbd282aa.js} +2 -2
  103. package/dist/{chunk-e91fmg6t.js → chunk-qsa7nw6f.js} +2 -1
  104. package/dist/{chunk-e91fmg6t.js.map → chunk-qsa7nw6f.js.map} +3 -3
  105. package/dist/{chunk-rg725hry.js → chunk-s8xxef60.js} +83 -33
  106. package/dist/{chunk-rg725hry.js.map → chunk-s8xxef60.js.map} +5 -5
  107. package/dist/{chunk-fzae1jpq.js → chunk-t19wjmnc.js} +5 -5
  108. package/dist/{chunk-paxabbqd.js → chunk-tapdssb5.js} +1 -1
  109. package/dist/{chunk-dhkc9b23.js → chunk-v8a1qjzp.js} +1 -1
  110. package/dist/{chunk-q8d9p0tb.js → chunk-wzcjhv54.js} +8 -1
  111. package/dist/{chunk-q8d9p0tb.js.map → chunk-wzcjhv54.js.map} +3 -3
  112. package/dist/{chunk-pc7kra3k.js → chunk-xavet0qs.js} +1 -1
  113. package/dist/{chunk-0hkdtwqk.js → chunk-xf76csps.js} +5 -5
  114. package/dist/{chunk-m9ketb51.js → chunk-ygvay56w.js} +1 -1
  115. package/dist/{chunk-b4escq4c.js → chunk-ykchk644.js} +6 -6
  116. package/dist/{chunk-k29n4176.js → chunk-ym1bqd98.js} +6 -6
  117. package/dist/connectors/connections/capability.d.ts +11 -0
  118. package/dist/connectors/connections/capability.d.ts.map +1 -1
  119. package/dist/connectors/connections/internal.d.ts +2 -1
  120. package/dist/connectors/connections/internal.d.ts.map +1 -1
  121. package/dist/connectors/connections/internal.js +8 -4
  122. package/dist/connectors/connections/internal.js.map +1 -1
  123. package/dist/connectors/connections/service.d.ts +9 -1
  124. package/dist/connectors/connections/service.d.ts.map +1 -1
  125. package/dist/connectors/execution.d.ts +7 -1
  126. package/dist/connectors/execution.d.ts.map +1 -1
  127. package/dist/connectors/service.d.ts +5 -1
  128. package/dist/connectors/service.d.ts.map +1 -1
  129. package/dist/deploy/types.d.ts +4 -1
  130. package/dist/deploy/types.d.ts.map +1 -1
  131. package/dist/events/execution.d.ts +8 -1
  132. package/dist/events/execution.d.ts.map +1 -1
  133. package/dist/events/types/syncs.d.ts +4 -0
  134. package/dist/events/types/syncs.d.ts.map +1 -1
  135. package/dist/execution/agent.js +37 -36
  136. package/dist/execution/agent.js.map +1 -1
  137. package/dist/execution/authorized-object-reader.d.ts +4 -0
  138. package/dist/execution/authorized-object-reader.d.ts.map +1 -1
  139. package/dist/execution/object-reader-ontology.d.ts +3 -0
  140. package/dist/execution/object-reader-ontology.d.ts.map +1 -1
  141. package/dist/execution/primitive.js +36 -35
  142. package/dist/execution/primitive.js.map +1 -1
  143. package/dist/execution/request.d.ts +1 -1
  144. package/dist/execution/request.d.ts.map +1 -1
  145. package/dist/execution/request.js +33 -32
  146. package/dist/execution/request.js.map +3 -3
  147. package/dist/http/api-routes.d.ts.map +1 -1
  148. package/dist/http/index.js +1 -1
  149. package/dist/index.d.ts +5 -5
  150. package/dist/index.d.ts.map +1 -1
  151. package/dist/index.js +61 -59
  152. package/dist/index.js.map +1 -1
  153. package/dist/maintenance/index.js +1 -1
  154. package/dist/materializer/index.js +22 -21
  155. package/dist/materializer/index.js.map +1 -1
  156. package/dist/models/audio/runtime.d.ts.map +1 -1
  157. package/dist/models/audio/types.d.ts +19 -0
  158. package/dist/models/audio/types.d.ts.map +1 -1
  159. package/dist/models/execution/index.js +20 -19
  160. package/dist/models/execution/index.js.map +1 -1
  161. package/dist/models/index.d.ts +1 -1
  162. package/dist/models/index.d.ts.map +1 -1
  163. package/dist/objects/index.js +36 -35
  164. package/dist/objects/index.js.map +1 -1
  165. package/dist/objects/query/executor.d.ts +3 -1
  166. package/dist/objects/query/executor.d.ts.map +1 -1
  167. package/dist/objects/query/explain.d.ts +3 -1
  168. package/dist/objects/query/explain.d.ts.map +1 -1
  169. package/dist/objects/query/index.d.ts +1 -1
  170. package/dist/objects/query/index.d.ts.map +1 -1
  171. package/dist/objects/query/index.js +19 -18
  172. package/dist/objects/query/index.js.map +1 -1
  173. package/dist/objects/query/link-query-clearance.d.ts +3 -0
  174. package/dist/objects/query/link-query-clearance.d.ts.map +1 -1
  175. package/dist/objects/query/links.d.ts +1 -1
  176. package/dist/objects/query/links.d.ts.map +1 -1
  177. package/dist/objects/query/validate.d.ts +17 -0
  178. package/dist/objects/query/validate.d.ts.map +1 -1
  179. package/dist/objects/sdk/runtime-query-executor.d.ts +1 -1
  180. package/dist/objects/sdk/runtime-query-executor.d.ts.map +1 -1
  181. package/dist/ontology/index.js +3 -3
  182. package/dist/ontology/internal.js +3 -3
  183. package/dist/pipelines/index.js +21 -20
  184. package/dist/pipelines/index.js.map +1 -1
  185. package/dist/projections/internal.js +20 -19
  186. package/dist/projections/internal.js.map +1 -1
  187. package/dist/queues/in-memory.d.ts +1 -1
  188. package/dist/queues/in-memory.d.ts.map +1 -1
  189. package/dist/runtime/host.d.ts.map +1 -1
  190. package/dist/runtime/internal.js +24 -23
  191. package/dist/runtime/internal.js.map +2 -2
  192. package/dist/runtime/locale.d.ts +0 -2
  193. package/dist/runtime/locale.d.ts.map +1 -1
  194. package/dist/runtime/sixb.d.ts.map +1 -1
  195. package/dist/sandboxes/auth.d.ts +26 -4
  196. package/dist/sandboxes/auth.d.ts.map +1 -1
  197. package/dist/sandboxes/index.d.ts +3 -1
  198. package/dist/sandboxes/index.d.ts.map +1 -1
  199. package/dist/sandboxes/index.js +5 -5
  200. package/dist/security/view-conditions.d.ts.map +1 -1
  201. package/dist/shares/internal.js +16 -15
  202. package/dist/shares/internal.js.map +2 -2
  203. package/dist/storage/agents/in-memory.d.ts +18 -1
  204. package/dist/storage/agents/in-memory.d.ts.map +1 -1
  205. package/dist/storage/agents/index.d.ts +1 -1
  206. package/dist/storage/agents/index.d.ts.map +1 -1
  207. package/dist/storage/agents/provider.d.ts +43 -9
  208. package/dist/storage/agents/provider.d.ts.map +1 -1
  209. package/dist/storage/agents/provider.js +18 -2
  210. package/dist/storage/agents/provider.js.map +1 -1
  211. package/dist/storage/agents/types.d.ts +136 -3
  212. package/dist/storage/agents/types.d.ts.map +1 -1
  213. package/dist/storage/ai-cost/analytics.d.ts +3 -2
  214. package/dist/storage/ai-cost/analytics.d.ts.map +1 -1
  215. package/dist/storage/ai-cost/provider.js +4 -3
  216. package/dist/storage/ai-cost/provider.js.map +1 -1
  217. package/dist/storage/ai-cost/types.d.ts +5 -1
  218. package/dist/storage/ai-cost/types.d.ts.map +1 -1
  219. package/dist/storage/artifacts/in-memory.d.ts.map +1 -1
  220. package/dist/storage/artifacts/record.d.ts +3 -1
  221. package/dist/storage/artifacts/record.d.ts.map +1 -1
  222. package/dist/storage/artifacts/types.d.ts +7 -0
  223. package/dist/storage/artifacts/types.d.ts.map +1 -1
  224. package/dist/storage/file-upload-sessions/provider.js +7 -7
  225. package/dist/storage/index.d.ts +2 -2
  226. package/dist/storage/index.d.ts.map +1 -1
  227. package/dist/storage/index.js +22 -21
  228. package/dist/storage/index.js.map +1 -1
  229. package/dist/storage/internal.js +8 -8
  230. package/dist/storage/operation-scope.d.ts.map +1 -1
  231. package/dist/storage/operation-scope.js +1 -1
  232. package/dist/storage/sync-runs/idempotency.d.ts.map +1 -1
  233. package/dist/storage/sync-runs/in-memory.d.ts +2 -1
  234. package/dist/storage/sync-runs/in-memory.d.ts.map +1 -1
  235. package/dist/storage/sync-runs/index.d.ts +1 -1
  236. package/dist/storage/sync-runs/index.d.ts.map +1 -1
  237. package/dist/storage/sync-runs/types.d.ts +27 -2
  238. package/dist/storage/sync-runs/types.d.ts.map +1 -1
  239. package/dist/storage/workflow-runs/provider.js +7 -7
  240. package/dist/syncs/accounts.d.ts +36 -0
  241. package/dist/syncs/accounts.d.ts.map +1 -0
  242. package/dist/syncs/builders.d.ts.map +1 -1
  243. package/dist/syncs/connections.d.ts +36 -0
  244. package/dist/syncs/connections.d.ts.map +1 -0
  245. package/dist/syncs/execution.d.ts +14 -4
  246. package/dist/syncs/execution.d.ts.map +1 -1
  247. package/dist/syncs/index.d.ts +2 -1
  248. package/dist/syncs/index.d.ts.map +1 -1
  249. package/dist/syncs/index.js +22 -21
  250. package/dist/syncs/index.js.map +1 -1
  251. package/dist/syncs/request.d.ts +16 -2
  252. package/dist/syncs/request.d.ts.map +1 -1
  253. package/dist/syncs/run-dispatch.d.ts +14 -2
  254. package/dist/syncs/run-dispatch.d.ts.map +1 -1
  255. package/dist/testing/agent-approval-storage-contract.d.ts.map +1 -1
  256. package/dist/testing/agent-inbox-storage-contract.d.ts.map +1 -1
  257. package/dist/testing/agent-storage-contract.d.ts.map +1 -1
  258. package/dist/testing/ai-cost-storage-contract.d.ts.map +1 -1
  259. package/dist/testing/artifact-storage-contract.d.ts.map +1 -1
  260. package/dist/testing/index.js +1051 -58
  261. package/dist/testing/index.js.map +8 -8
  262. package/dist/testing/run-claim-storage-contract.d.ts.map +1 -1
  263. package/dist/webhooks/internal.js +17 -16
  264. package/dist/webhooks/internal.js.map +2 -2
  265. package/dist/workers/index.js +66 -13
  266. package/dist/workers/index.js.map +4 -4
  267. package/dist/workers/queue-worker.d.ts +5 -0
  268. package/dist/workers/queue-worker.d.ts.map +1 -1
  269. package/dist/workers/worker.d.ts +8 -0
  270. package/dist/workers/worker.d.ts.map +1 -1
  271. package/dist/workflows/index.js +42 -40
  272. package/dist/workflows/index.js.map +1 -1
  273. package/package.json +7 -1
  274. package/src/actions/validation.ts +3 -1
  275. package/src/agents/children.ts +6 -0
  276. package/src/agents/errors.ts +3 -0
  277. package/src/agents/execution.ts +170 -20
  278. package/src/agents/index.ts +4 -0
  279. package/src/agents/model-routing.ts +25 -9
  280. package/src/agents/request.ts +759 -40
  281. package/src/agents/run-events.ts +235 -38
  282. package/src/agents/run-session-children.ts +13 -2
  283. package/src/agents/run-turn.ts +140 -23
  284. package/src/agents/streams/index.ts +2 -0
  285. package/src/agents/streams/internal.ts +12 -0
  286. package/src/agents/streams/protocol.ts +69 -1
  287. package/src/agents/streams/steps.ts +131 -0
  288. package/src/agents/thread-access.ts +57 -2
  289. package/src/artifacts/publish/merge.ts +14 -3
  290. package/src/artifacts/run-query.ts +5 -2
  291. package/src/calendar.ts +195 -0
  292. package/src/connectors/connections/capability.ts +40 -0
  293. package/src/connectors/connections/internal.ts +3 -0
  294. package/src/connectors/connections/service.ts +74 -5
  295. package/src/connectors/execution.ts +5 -6
  296. package/src/connectors/service.ts +23 -0
  297. package/src/deploy/types.ts +4 -1
  298. package/src/events/execution.ts +42 -2
  299. package/src/events/types/syncs.ts +4 -0
  300. package/src/execution/authorized-object-reader.ts +33 -5
  301. package/src/execution/object-reader-ontology.ts +6 -0
  302. package/src/execution/request.ts +1 -0
  303. package/src/http/api-routes.ts +8 -0
  304. package/src/index.ts +18 -2
  305. package/src/models/audio/runtime.ts +57 -14
  306. package/src/models/audio/types.ts +20 -0
  307. package/src/models/index.ts +1 -0
  308. package/src/objects/query/executor.ts +4 -0
  309. package/src/objects/query/explain.ts +5 -0
  310. package/src/objects/query/index.ts +1 -0
  311. package/src/objects/query/link-query-clearance.ts +4 -1
  312. package/src/objects/query/links.ts +5 -1
  313. package/src/objects/query/validate.ts +33 -1
  314. package/src/objects/sdk/runtime-query-executor.ts +7 -3
  315. package/src/runtime/host.ts +13 -7
  316. package/src/runtime/locale.ts +0 -10
  317. package/src/runtime/sixb.ts +12 -2
  318. package/src/sandboxes/README.md +3 -1
  319. package/src/sandboxes/auth.ts +32 -4
  320. package/src/sandboxes/index.ts +15 -1
  321. package/src/security/view-conditions.ts +2 -1
  322. package/src/storage/agents/in-memory.ts +271 -6
  323. package/src/storage/agents/index.ts +10 -0
  324. package/src/storage/agents/provider.ts +170 -13
  325. package/src/storage/agents/types.ts +148 -3
  326. package/src/storage/ai-cost/analytics.ts +22 -43
  327. package/src/storage/ai-cost/types.ts +5 -1
  328. package/src/storage/artifacts/in-memory.ts +20 -5
  329. package/src/storage/artifacts/record.ts +8 -2
  330. package/src/storage/artifacts/types.ts +7 -0
  331. package/src/storage/index.ts +11 -0
  332. package/src/storage/operation-scope.ts +1 -0
  333. package/src/storage/sync-runs/idempotency.ts +1 -0
  334. package/src/storage/sync-runs/in-memory.ts +43 -1
  335. package/src/storage/sync-runs/index.ts +1 -0
  336. package/src/storage/sync-runs/types.ts +30 -1
  337. package/src/syncs/accounts.ts +85 -0
  338. package/src/syncs/builders.ts +18 -1
  339. package/src/syncs/connections.ts +123 -0
  340. package/src/syncs/execution.ts +64 -22
  341. package/src/syncs/index.ts +3 -0
  342. package/src/syncs/request.ts +81 -23
  343. package/src/syncs/run-dispatch.ts +69 -7
  344. package/src/testing/agent-approval-storage-contract.ts +123 -0
  345. package/src/testing/agent-inbox-storage-contract.ts +59 -0
  346. package/src/testing/agent-storage-contract.ts +767 -8
  347. package/src/testing/ai-cost-storage-contract.ts +80 -0
  348. package/src/testing/artifact-storage-contract.ts +129 -0
  349. package/src/testing/run-claim-storage-contract.ts +116 -0
  350. package/src/workers/README.md +4 -1
  351. package/src/workers/lost-runs.ts +1 -0
  352. package/src/workers/queue-worker.ts +16 -5
  353. package/src/workers/worker.ts +67 -7
  354. package/dist/chunk-5a4a52tq.js.map +0 -10
  355. package/dist/chunk-5t9gm5tt.js.map +0 -22
  356. package/dist/chunk-68hm50qh.js.map +0 -13
  357. package/dist/chunk-aw1z0gre.js +0 -234
  358. package/dist/chunk-aw1z0gre.js.map +0 -12
  359. package/dist/chunk-ey1p8w68.js.map +0 -13
  360. package/dist/chunk-k3jh8gsg.js.map +0 -10
  361. package/dist/chunk-qavwr628.js.map +0 -12
  362. package/dist/chunk-s1mqyqmm.js.map +0 -18
  363. package/dist/chunk-zeykm8my.js.map +0 -14
  364. /package/dist/{chunk-stmxh0hv.js.map → chunk-3neam1y5.js.map} +0 -0
  365. /package/dist/{chunk-0mvjpgvm.js.map → chunk-425ydk65.js.map} +0 -0
  366. /package/dist/{chunk-s5pj68fa.js.map → chunk-5sswe5ej.js.map} +0 -0
  367. /package/dist/{chunk-q9nkpr8k.js.map → chunk-9tpmfh3n.js.map} +0 -0
  368. /package/dist/{chunk-naxjka9v.js.map → chunk-brhp9d97.js.map} +0 -0
  369. /package/dist/{chunk-8a8k38tz.js.map → chunk-brybqw5k.js.map} +0 -0
  370. /package/dist/{chunk-vehcr9eb.js.map → chunk-cg7cygfj.js.map} +0 -0
  371. /package/dist/{chunk-r2psmn42.js.map → chunk-eg6xqef7.js.map} +0 -0
  372. /package/dist/{chunk-zxhym8tr.js.map → chunk-f05994as.js.map} +0 -0
  373. /package/dist/{chunk-1yh6jgtz.js.map → chunk-grt2j5vp.js.map} +0 -0
  374. /package/dist/{chunk-rtdrm592.js.map → chunk-htdzx40w.js.map} +0 -0
  375. /package/dist/{chunk-bc3y6gff.js.map → chunk-jka26v8c.js.map} +0 -0
  376. /package/dist/{chunk-pqvvqc65.js.map → chunk-pqj8vff9.js.map} +0 -0
  377. /package/dist/{chunk-wqe9shx2.js.map → chunk-qbd282aa.js.map} +0 -0
  378. /package/dist/{chunk-fzae1jpq.js.map → chunk-t19wjmnc.js.map} +0 -0
  379. /package/dist/{chunk-paxabbqd.js.map → chunk-tapdssb5.js.map} +0 -0
  380. /package/dist/{chunk-dhkc9b23.js.map → chunk-v8a1qjzp.js.map} +0 -0
  381. /package/dist/{chunk-pc7kra3k.js.map → chunk-xavet0qs.js.map} +0 -0
  382. /package/dist/{chunk-0hkdtwqk.js.map → chunk-xf76csps.js.map} +0 -0
  383. /package/dist/{chunk-m9ketb51.js.map → chunk-ygvay56w.js.map} +0 -0
  384. /package/dist/{chunk-b4escq4c.js.map → chunk-ykchk644.js.map} +0 -0
  385. /package/dist/{chunk-k29n4176.js.map → chunk-ym1bqd98.js.map} +0 -0
@@ -20,6 +20,10 @@ var DEFAULT_AGENT_RUN_STREAM_RETENTION2 = {
20
20
  maxAgeMs: 2 * 60 * 60 * 1000,
21
21
  maxRecords: 5000
22
22
  };
23
+ var DEFAULT_AGENT_RUN_STEPS_RETENTION2 = {
24
+ maxAgeMs: 24 * 60 * 60 * 1000,
25
+ maxBytes: 64 * 1024 * 1024
26
+ };
23
27
  var AGENT_ACTIVITY_STREAM_SCHEMA_VERSION2 = 1;
24
28
  var AGENT_ACTIVITY_STREAM_ID2 = "agents.activity";
25
29
  var DEFAULT_AGENT_ACTIVITY_STREAM_RETENTION2 = {
@@ -156,6 +160,12 @@ function agentRunStreamDefinition2(runId) {
156
160
  retention: DEFAULT_AGENT_RUN_STREAM_RETENTION2
157
161
  };
158
162
  }
163
+ function agentRunStepsStreamId2(runId) {
164
+ return `agents.runs.${runId}.steps`;
165
+ }
166
+ function agentRunStepsStreamDefinition2(runId) {
167
+ return { id: agentRunStepsStreamId2(runId), retention: DEFAULT_AGENT_RUN_STEPS_RETENTION2 };
168
+ }
159
169
  function agentRunControlStreamId2(runId) {
160
170
  return `agents.runs.${runId}.control`;
161
171
  }
@@ -241,7 +251,9 @@ function isAgentRunStreamEvent2(value) {
241
251
  case "agent.ui.chunk":
242
252
  return Number.isInteger(value.chunkIndex) && isModelUiChunk(value.chunk);
243
253
  case "agent.inbox.read":
244
- return Array.isArray(value.messages) && value.messages.length > 0 && value.messages.every(isAgentInboxReadMessage);
254
+ return Array.isArray(value.messages) && value.messages.length > 0 && value.messages.every(isAgentInboxReadMessage) && (value.afterChunkIndex === undefined || Number.isInteger(value.afterChunkIndex));
255
+ case "agent.ui.steps":
256
+ return Number.isInteger(value.throughChunkIndex) && Array.isArray(value.chunks) && value.chunks.every(isModelUiChunk) && (value.reads === undefined || Array.isArray(value.reads) && value.reads.every(isAgentRunStepsRead));
245
257
  case "agent.message.finalized":
246
258
  return typeof value.messageId === "string";
247
259
  case "agent.run.finished":
@@ -253,6 +265,9 @@ function isAgentRunStreamEvent2(value) {
253
265
  function isAgentInboxReadMessage(value) {
254
266
  return isPlainRecord(value) && typeof value.id === "string" && isPlainRecord(value.authorPrincipal) && typeof value.authorPrincipal.type === "string" && typeof value.authorPrincipal.id === "string" && Array.isArray(value.parts) && value.parts.every((part) => isPlainRecord(part) && typeof part.type === "string") && isJsonValue2(value.parts) && typeof value.createdAt === "string";
255
267
  }
268
+ function isAgentRunStepsRead(value) {
269
+ return isPlainRecord(value) && Number.isInteger(value.at) && value.at >= 0 && Array.isArray(value.messages) && value.messages.length > 0 && value.messages.every(isAgentInboxReadMessage);
270
+ }
256
271
  function isAgentContextCheckpointReason(value) {
257
272
  return value === "threshold" || value === "overflow";
258
273
  }
@@ -289,6 +304,8 @@ function agentRunStreamIdempotencyKey2(event) {
289
304
  return `${event.runId}:${event.attempt}:chunk:${event.chunkIndex}`;
290
305
  case "agent.inbox.read":
291
306
  return `${event.runId}:${event.attempt}:inbox:${event.messages.map((message) => message.id).join(",")}:read`;
307
+ case "agent.ui.steps":
308
+ return `${event.runId}:${event.attempt}:steps:${event.throughChunkIndex}`;
292
309
  case "agent.message.finalized":
293
310
  return `${event.runId}:${event.attempt}:message:${event.messageId}:finalized`;
294
311
  case "agent.run.finished":
@@ -317,6 +334,6 @@ async function publishAgentRunFinished2(broker, run) {
317
334
  await publishAgentRunActivity2(broker, run);
318
335
  }
319
336
 
320
- export { AGENT_RUN_STREAM_SCHEMA_VERSION2, DEFAULT_AGENT_RUN_STREAM_RETENTION2, AGENT_ACTIVITY_STREAM_SCHEMA_VERSION2, AGENT_ACTIVITY_STREAM_ID2, DEFAULT_AGENT_ACTIVITY_STREAM_RETENTION2, agentActivityStreamDefinition2, agentRunActivityEvent2, isAgentRunActivityEvent2, isAgentApprovalActivityEvent2, isAgentActivityEvent2, publishAgentComputerActivity2, publishAgentThreadMoved2, publishAgentApprovalActivity, publishAgentRunActivity2, agentRunStreamId2, agentRunStreamDefinition2, agentRunControlStreamId2, AGENT_RUN_CANCEL_RECORD2, agentRunControlStreamDefinition2, publishAgentRunCancel2, subscribeAgentRunCancel2, AGENT_COMPACTION_FAILURE_CODES2, agentRunFinishedEvent2, agentRunStreamEventBase2, isAgentRunStreamEvent2, agentRunStreamIdempotencyKey2, publishAgentRunFinished2 };
337
+ export { AGENT_RUN_STREAM_SCHEMA_VERSION2, DEFAULT_AGENT_RUN_STREAM_RETENTION2, DEFAULT_AGENT_RUN_STEPS_RETENTION2, AGENT_ACTIVITY_STREAM_SCHEMA_VERSION2, AGENT_ACTIVITY_STREAM_ID2, DEFAULT_AGENT_ACTIVITY_STREAM_RETENTION2, agentActivityStreamDefinition2, agentRunActivityEvent2, isAgentRunActivityEvent2, isAgentApprovalActivityEvent2, isAgentActivityEvent2, publishAgentComputerActivity2, publishAgentThreadMoved2, publishAgentApprovalActivity, publishAgentRunActivity2, agentRunStreamId2, agentRunStreamDefinition2, agentRunStepsStreamId2, agentRunStepsStreamDefinition2, agentRunControlStreamId2, AGENT_RUN_CANCEL_RECORD2, agentRunControlStreamDefinition2, publishAgentRunCancel2, subscribeAgentRunCancel2, AGENT_COMPACTION_FAILURE_CODES2, agentRunFinishedEvent2, agentRunStreamEventBase2, isAgentRunStreamEvent2, agentRunStreamIdempotencyKey2, publishAgentRunFinished2 };
321
338
 
322
- //# debugId=28512A16AF9152FA64756E2164756E21
339
+ //# debugId=1DEC49E9C4790BC864756E2164756E21
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/agents/streams/protocol.ts"],
4
+ "sourcesContent": [
5
+ "import type { Principal } from \"../../auth\"\nimport type { Broker, BrokerStreamDefinition } from \"../../broker\"\nimport { parseSixbFailure } from \"../../errors/internal\"\nimport type { SixbFailure } from \"../../errors/types\"\nimport { isJsonValue, isPlainRecord, type JsonValue } from \"../../json\"\nimport { isModelUiChunk, type ModelUiChunk } from \"../../models/events\"\nimport {\n AGENT_APPROVAL_STATUSES,\n AGENT_RUN_FAILURE_CODES,\n type AgentApprovalRecord,\n type AgentApprovalStatus,\n type AgentContextCheckpointReason,\n type AgentRunFailureCode,\n type AgentRunRecord,\n type ConversationAgentRunRecord,\n} from \"../../storage/agents/types\"\nimport type { AgentMessagePart } from \"../message\"\n\nexport const AGENT_RUN_STREAM_SCHEMA_VERSION = 1 as const\nexport const DEFAULT_AGENT_RUN_STREAM_RETENTION = {\n maxAgeMs: 2 * 60 * 60 * 1000, // 2 hours\n maxRecords: 5_000,\n} as const\n\n/**\n * A run's finished steps, kept apart from its live stream: the live stream drops its oldest records,\n * and a long turn outgrows it, so whoever opens a turn late reads what it did here. Records last as\n * long as the longest turn, and the run's whole answer fits well within the byte limit.\n */\nexport const DEFAULT_AGENT_RUN_STEPS_RETENTION = {\n maxAgeMs: 24 * 60 * 60 * 1000, // 24 hours\n maxBytes: 64 * 1024 * 1024,\n} as const\n\nexport const AGENT_ACTIVITY_STREAM_SCHEMA_VERSION = 1 as const\nexport const AGENT_ACTIVITY_STREAM_ID = \"agents.activity\" as const\nexport const DEFAULT_AGENT_ACTIVITY_STREAM_RETENTION = {\n maxAgeMs: 24 * 60 * 60 * 1000, // 24 hours\n maxRecords: 10_000,\n} as const\n\nexport interface AgentRunActivityEvent {\n readonly schemaVersion: typeof AGENT_ACTIVITY_STREAM_SCHEMA_VERSION\n readonly type: \"agent.run.activity\"\n readonly projectId: string\n readonly runId: string\n readonly threadId: string\n readonly status: AgentRunRecord[\"status\"]\n readonly attempt: number\n /** Set on a computer's turn: a `sixb` hearing of any other has nothing to read about it. */\n readonly runsOn?: \"computer\"\n /** A stop was asked for: whatever runs it hears at its next lease renewal, or now, on this. */\n readonly cancelRequested?: true\n readonly occurredAt: string\n}\n\nexport function agentActivityStreamDefinition(): BrokerStreamDefinition {\n return {\n id: AGENT_ACTIVITY_STREAM_ID,\n retention: DEFAULT_AGENT_ACTIVITY_STREAM_RETENTION,\n }\n}\n\nexport function agentRunActivityEvent(\n run: ConversationAgentRunRecord,\n occurredAt: Date = new Date()\n): AgentRunActivityEvent {\n return {\n schemaVersion: AGENT_ACTIVITY_STREAM_SCHEMA_VERSION,\n type: \"agent.run.activity\",\n projectId: run.projectId,\n runId: run.id,\n threadId: run.threadId,\n status: run.status,\n attempt: run.attempt,\n ...(run.spec?.runsOn === \"computer\" ? { runsOn: \"computer\" as const } : {}),\n occurredAt: occurredAt.toISOString(),\n }\n}\n\nexport function isAgentRunActivityEvent(value: unknown): value is AgentRunActivityEvent {\n return (\n isPlainRecord(value) &&\n value.schemaVersion === AGENT_ACTIVITY_STREAM_SCHEMA_VERSION &&\n value.type === \"agent.run.activity\" &&\n typeof value.projectId === \"string\" &&\n typeof value.runId === \"string\" &&\n typeof value.threadId === \"string\" &&\n isAgentRunStatus(value.status) &&\n typeof value.attempt === \"number\" &&\n Number.isFinite(value.attempt) &&\n (value.runsOn === undefined || value.runsOn === \"computer\") &&\n typeof value.occurredAt === \"string\"\n )\n}\n\n/**\n * A held call of a thread's turn changed: it was held, decided, ran, or was set aside. Clients read\n * the thread's approvals again.\n */\nexport interface AgentApprovalActivityEvent {\n readonly schemaVersion: typeof AGENT_ACTIVITY_STREAM_SCHEMA_VERSION\n readonly type: \"agent.approval.activity\"\n readonly projectId: string\n readonly approvalId: string\n readonly threadId: string\n /** The conversation turn the call belongs to. */\n readonly runId: string\n readonly status: AgentApprovalStatus\n /** Whether the approved call ran and has its outcome. */\n readonly hasOutcome: boolean\n readonly occurredAt: string\n}\n\n/**\n * An open `sixb` on its owner's computer came or went: the threads that run on that computer in\n * that folder are reachable now, or not. Also said, `online`, as the background commands it runs\n * start or end, and as its owner asks it to stop one, which it hears and renews its session for.\n * Only its owner hears it.\n */\nexport interface AgentComputerActivityEvent {\n readonly schemaVersion: typeof AGENT_ACTIVITY_STREAM_SCHEMA_VERSION\n readonly type: \"agent.computer.activity\"\n readonly projectId: string\n readonly ownerPrincipal: { readonly type: string; readonly id: string }\n readonly computerId: string\n readonly folder: string\n readonly online: boolean\n readonly occurredAt: string\n}\n\n/** A thread moved to another folder or computer, or to the cloud. Its owner alone hears it. */\nexport interface AgentThreadMovedEvent {\n readonly schemaVersion: typeof AGENT_ACTIVITY_STREAM_SCHEMA_VERSION\n readonly type: \"agent.thread.moved\"\n readonly projectId: string\n readonly ownerPrincipal: { readonly type: string; readonly id: string }\n readonly threadId: string\n readonly occurredAt: string\n}\n\n/** Everything the project's activity feed carries. */\nexport type AgentActivityEvent =\n | AgentRunActivityEvent\n | AgentApprovalActivityEvent\n | AgentComputerActivityEvent\n | AgentThreadMovedEvent\n\nexport function agentApprovalActivityEvent(\n approval: AgentApprovalRecord,\n occurredAt: Date = new Date()\n): AgentApprovalActivityEvent {\n return {\n schemaVersion: AGENT_ACTIVITY_STREAM_SCHEMA_VERSION,\n type: \"agent.approval.activity\",\n projectId: approval.projectId,\n approvalId: approval.id,\n threadId: approval.threadId,\n runId: approval.runId,\n status: approval.status,\n hasOutcome: approval.outcome !== undefined,\n occurredAt: occurredAt.toISOString(),\n }\n}\n\nexport function isAgentApprovalActivityEvent(value: unknown): value is AgentApprovalActivityEvent {\n return (\n isPlainRecord(value) &&\n value.schemaVersion === AGENT_ACTIVITY_STREAM_SCHEMA_VERSION &&\n value.type === \"agent.approval.activity\" &&\n typeof value.projectId === \"string\" &&\n typeof value.approvalId === \"string\" &&\n typeof value.threadId === \"string\" &&\n typeof value.runId === \"string\" &&\n (AGENT_APPROVAL_STATUSES as readonly unknown[]).includes(value.status) &&\n typeof value.hasOutcome === \"boolean\" &&\n typeof value.occurredAt === \"string\"\n )\n}\n\nfunction isAgentComputerActivityEvent(value: unknown): value is AgentComputerActivityEvent {\n return (\n isPlainRecord(value) &&\n value.schemaVersion === AGENT_ACTIVITY_STREAM_SCHEMA_VERSION &&\n value.type === \"agent.computer.activity\" &&\n typeof value.projectId === \"string\" &&\n isPlainRecord(value.ownerPrincipal) &&\n typeof value.ownerPrincipal.type === \"string\" &&\n typeof value.ownerPrincipal.id === \"string\" &&\n typeof value.computerId === \"string\" &&\n typeof value.folder === \"string\" &&\n typeof value.online === \"boolean\" &&\n typeof value.occurredAt === \"string\"\n )\n}\n\nfunction isAgentThreadMovedEvent(value: unknown): value is AgentThreadMovedEvent {\n return (\n isPlainRecord(value) &&\n value.schemaVersion === AGENT_ACTIVITY_STREAM_SCHEMA_VERSION &&\n value.type === \"agent.thread.moved\" &&\n typeof value.projectId === \"string\" &&\n isPlainRecord(value.ownerPrincipal) &&\n typeof value.ownerPrincipal.type === \"string\" &&\n typeof value.ownerPrincipal.id === \"string\" &&\n typeof value.threadId === \"string\" &&\n typeof value.occurredAt === \"string\"\n )\n}\n\nexport function isAgentActivityEvent(value: unknown): value is AgentActivityEvent {\n return (\n isAgentRunActivityEvent(value) ||\n isAgentApprovalActivityEvent(value) ||\n isAgentComputerActivityEvent(value) ||\n isAgentThreadMovedEvent(value)\n )\n}\n\n/** Announce that the owner's computer is reachable, or no longer, in a folder. */\nexport async function publishAgentComputerActivity(\n broker: Broker,\n input: Omit<AgentComputerActivityEvent, \"schemaVersion\" | \"type\" | \"occurredAt\">\n): Promise<void> {\n const event: AgentComputerActivityEvent = {\n schemaVersion: AGENT_ACTIVITY_STREAM_SCHEMA_VERSION,\n type: \"agent.computer.activity\",\n ...input,\n occurredAt: new Date().toISOString(),\n }\n await appendActivity(broker, event, event.computerId)\n}\n\n/** Announce that a thread moved, so whatever has it open follows. */\nexport async function publishAgentThreadMoved(\n broker: Broker,\n input: Omit<AgentThreadMovedEvent, \"schemaVersion\" | \"type\" | \"occurredAt\">\n): Promise<void> {\n const event: AgentThreadMovedEvent = {\n schemaVersion: AGENT_ACTIVITY_STREAM_SCHEMA_VERSION,\n type: \"agent.thread.moved\",\n ...input,\n occurredAt: new Date().toISOString(),\n }\n await appendActivity(broker, event, event.threadId)\n}\n\nasync function appendActivity(\n broker: Broker,\n event: AgentComputerActivityEvent | AgentThreadMovedEvent,\n key: string\n): Promise<void> {\n await broker.ensureStream({ projectId: event.projectId, stream: agentActivityStreamDefinition() })\n await broker.append({\n projectId: event.projectId,\n streamId: AGENT_ACTIVITY_STREAM_ID,\n records: [\n {\n name: event.type,\n key,\n // The event is composed only of validated JSON primitives.\n payload: event as unknown as JsonValue,\n // Every announcement is a new one, even a second in the same millisecond.\n idempotencyKey: crypto.randomUUID(),\n },\n ],\n })\n}\n\n/** Announce held calls that changed, in one append. Each change is announced once. */\nexport async function publishAgentApprovalActivity(\n broker: Broker,\n approvals: readonly AgentApprovalRecord[]\n): Promise<void> {\n const first = approvals[0]\n if (!first) return\n\n await broker.ensureStream({\n projectId: first.projectId,\n stream: agentActivityStreamDefinition(),\n })\n await broker.append({\n projectId: first.projectId,\n streamId: AGENT_ACTIVITY_STREAM_ID,\n records: approvals.map((approval) => {\n const event = agentApprovalActivityEvent(approval)\n return {\n name: event.type,\n key: event.threadId,\n // The event is composed only of validated JSON primitives.\n payload: event as unknown as JsonValue,\n idempotencyKey: `${event.approvalId}:${event.status}${event.hasOutcome ? \":outcome\" : \"\"}`,\n }\n }),\n })\n}\n\nexport async function publishAgentRunActivity(\n broker: Broker,\n run: ConversationAgentRunRecord,\n options: { readonly cancelRequested?: true } = {}\n): Promise<void> {\n const event = { ...agentRunActivityEvent(run), ...options }\n await broker.ensureStream({\n projectId: run.projectId,\n stream: agentActivityStreamDefinition(),\n })\n await broker.append({\n projectId: run.projectId,\n streamId: AGENT_ACTIVITY_STREAM_ID,\n records: [\n {\n name: event.type,\n key: event.threadId,\n // The event is composed only of validated JSON primitives.\n payload: event as unknown as JsonValue,\n idempotencyKey: `${event.runId}:${event.attempt}:${event.status}${options.cancelRequested ? \":cancel\" : \"\"}`,\n },\n ],\n })\n}\n\nexport type AgentRunStreamId = `agents.runs.${string}`\n\nexport function agentRunStreamId(runId: string): AgentRunStreamId {\n return `agents.runs.${runId}`\n}\n\nexport function agentRunStreamDefinition(runId: string): BrokerStreamDefinition {\n return {\n id: agentRunStreamId(runId),\n retention: DEFAULT_AGENT_RUN_STREAM_RETENTION,\n }\n}\n\nexport type AgentRunStepsStreamId = `agents.runs.${string}.steps`\n\nexport function agentRunStepsStreamId(runId: string): AgentRunStepsStreamId {\n return `agents.runs.${runId}.steps`\n}\n\nexport function agentRunStepsStreamDefinition(runId: string): BrokerStreamDefinition {\n return { id: agentRunStepsStreamId(runId), retention: DEFAULT_AGENT_RUN_STEPS_RETENTION }\n}\n\ntype AgentRunStreamEventBase = {\n readonly schemaVersion: typeof AGENT_RUN_STREAM_SCHEMA_VERSION\n readonly projectId: string\n readonly runId: string\n readonly attempt: number\n readonly occurredAt: string\n} & (\n | {\n readonly threadId: string\n readonly parentRunId?: never\n }\n | {\n readonly parentRunId: string\n readonly threadId?: never\n }\n)\n\n// ── Control stream (worker-inbound) ─────────────────────────────────────────────────────────────\n//\n// A per-run channel the API layer publishes to and the worker subscribes to — the reverse direction\n// of the event stream above. It carries only a cancel signal, and is addressed by `runId` (not a run\n// record), so a cancel works even before the worker has reserved the run. Kept separate from the\n// event stream so control records never reach the browser client.\n\nexport type AgentRunControlStreamId = `agents.runs.${string}.control`\n\nexport function agentRunControlStreamId(runId: string): AgentRunControlStreamId {\n return `agents.runs.${runId}.control`\n}\n\n/** The only control record: a request to stop the run. */\nexport const AGENT_RUN_CANCEL_RECORD = \"agent.run.cancel\"\n\n// A cancel only needs to outlive the queue wait plus one turn, so retention is short and tiny.\nconst AGENT_RUN_CONTROL_RETENTION = { maxAgeMs: 30 * 60 * 1000, maxRecords: 16 } as const\n\nexport function agentRunControlStreamDefinition(runId: string): BrokerStreamDefinition {\n return { id: agentRunControlStreamId(runId), retention: AGENT_RUN_CONTROL_RETENTION }\n}\n\n/**\n * Signal a run to stop. Publishing is addressed by `runId`, so it works whether the run is queued,\n * reserved, or being drained — the worker picks the record up when it subscribes.\n */\nexport async function publishAgentRunCancel(\n broker: Broker,\n params: { readonly projectId: string; readonly runId: string }\n): Promise<void> {\n await broker.ensureStream({\n projectId: params.projectId,\n stream: agentRunControlStreamDefinition(params.runId),\n })\n await broker.append({\n projectId: params.projectId,\n streamId: agentRunControlStreamId(params.runId),\n records: [\n {\n name: AGENT_RUN_CANCEL_RECORD,\n key: params.runId,\n payload: { runId: params.runId },\n idempotencyKey: `${params.runId}:cancel`,\n },\n ],\n })\n}\n\n/**\n * Watch a run's control stream and invoke `onCancel` when a cancel arrives. Reads from `earliest` so\n * a cancel published before the worker subscribed (a run stopped while still queued) is still seen.\n * Returns the unsubscribe handle.\n */\nexport async function subscribeAgentRunCancel(\n broker: Broker,\n params: { readonly projectId: string; readonly runId: string },\n onCancel: () => void\n): Promise<() => void> {\n await broker.ensureStream({\n projectId: params.projectId,\n stream: agentRunControlStreamDefinition(params.runId),\n })\n return broker.subscribe(\n {\n projectId: params.projectId,\n streamId: agentRunControlStreamId(params.runId),\n from: \"earliest\",\n names: [AGENT_RUN_CANCEL_RECORD],\n },\n () => onCancel()\n )\n}\n\n/** Exact portable failure exposed by a terminal Agent run stream event. */\nexport type AgentRunFailure = SixbFailure<AgentRunFailureCode>\n\nexport const AGENT_COMPACTION_FAILURE_CODES = [\n \"context_limit_exceeded\",\n \"summary_failed\",\n \"checkpoint_failed\",\n] as const\nexport type AgentCompactionFailureCode = (typeof AGENT_COMPACTION_FAILURE_CODES)[number]\n\n/**\n * A message a turn read from its thread's inbox as it answered. The conversation holds it as a user\n * message, with this id, where the turn read it: after what the run streamed before this record.\n */\nexport interface AgentInboxReadMessage {\n /** The id the message is saved with once the turn ends. */\n readonly id: string\n readonly authorPrincipal: Principal\n readonly parts: readonly AgentMessagePart[]\n readonly createdAt: string\n}\n\n/** Messages a turn read in its finished steps, after the first `at` of their chunks. */\nexport interface AgentRunStepsRead {\n readonly at: number\n readonly messages: readonly AgentInboxReadMessage[]\n}\n\nexport type AgentRunStreamEvent =\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.run.started\"\n readonly modelId?: string\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.compaction.started\"\n readonly reason: AgentContextCheckpointReason\n readonly estimatedInputTokensBefore: number\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.compaction.completed\"\n readonly reason: AgentContextCheckpointReason\n readonly checkpointId: string\n readonly estimatedInputTokensBefore: number\n readonly estimatedInputTokensAfter: number\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.compaction.failed\"\n readonly reason: AgentContextCheckpointReason\n readonly errorCode: AgentCompactionFailureCode\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.ui.chunk\"\n readonly chunkIndex: number\n readonly chunk: ModelUiChunk\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.inbox.read\"\n readonly messages: readonly AgentInboxReadMessage[]\n /**\n * The last live chunk published before the turn read them, absent before the first: the\n * finished steps that cover it hold this read too, where it happened.\n */\n readonly afterChunkIndex?: number\n })\n | (AgentRunStreamEventBase & {\n /**\n * The turn's finished steps, as the chunks that rebuild them. Never a live record: the server\n * sends it first to a reader who opens the turn late, and that reader then skips the live\n * records it covers. It replaces whatever the reader rebuilt before.\n */\n readonly type: \"agent.ui.steps\"\n /** The last live chunk it covers. */\n readonly throughChunkIndex: number\n readonly chunks: readonly ModelUiChunk[]\n /** What the turn read from its inbox in those steps, each after the first `at` chunks. */\n readonly reads?: readonly AgentRunStepsRead[]\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.message.finalized\"\n readonly messageId: string\n })\n | (AgentRunStreamEventBase & {\n readonly type: \"agent.run.finished\"\n readonly status: \"succeeded\" | \"failed\" | \"cancelled\"\n readonly finishReason?: string\n readonly error?: AgentRunFailure\n })\n\nexport type AgentRunFinishedEvent = Extract<AgentRunStreamEvent, { type: \"agent.run.finished\" }>\nexport type AgentRunStepsEvent = Extract<AgentRunStreamEvent, { type: \"agent.ui.steps\" }>\n\n// ── Record construction ──────────────────────────────────────────────────────────────────────────\n//\n// The wire format of run stream records — event shape, record name/key, and the idempotency-key\n// vocabulary — is owned here so every producer (the worker's stream sink, the server's queued\n// cancellation) shares one definition and cannot drift.\n\n/** Build the terminal stream event for a finished run. Throws if the run is not terminal. */\nexport function agentRunFinishedEvent(\n run: AgentRunRecord,\n occurredAt: Date = new Date()\n): AgentRunFinishedEvent {\n if (run.status === \"queued\" || run.status === \"running\") {\n throw new Error(\n `[Sixb] Agent run '${run.id}' is not terminal (status '${run.status}'), so it has no finished event.`\n )\n }\n return {\n ...agentRunStreamEventBase(run, occurredAt),\n type: \"agent.run.finished\",\n status: run.status,\n ...(run.finishReason === undefined ? {} : { finishReason: run.finishReason }),\n ...(run.error === undefined ? {} : { error: run.error }),\n }\n}\n\n/** Shared lineage for stream records emitted by conversational and headless runs. */\nexport function agentRunStreamEventBase(\n run: AgentRunRecord,\n occurredAt: Date = new Date()\n): AgentRunStreamEventBase {\n const common = {\n schemaVersion: AGENT_RUN_STREAM_SCHEMA_VERSION,\n projectId: run.projectId,\n runId: run.id,\n attempt: run.attempt,\n occurredAt: occurredAt.toISOString(),\n }\n return run.kind === \"conversation\"\n ? { ...common, threadId: run.threadId }\n : { ...common, parentRunId: run.parentRunId }\n}\n\n/** Validate an Agent stream payload using the same contract its producers use. */\nexport function isAgentRunStreamEvent(value: unknown): value is AgentRunStreamEvent {\n if (\n !isPlainRecord(value) ||\n value.schemaVersion !== AGENT_RUN_STREAM_SCHEMA_VERSION ||\n typeof value.projectId !== \"string\" ||\n typeof value.runId !== \"string\" ||\n typeof value.attempt !== \"number\" ||\n !Number.isFinite(value.attempt) ||\n typeof value.occurredAt !== \"string\" ||\n typeof value.type !== \"string\"\n ) {\n return false\n }\n const hasConversationLineage =\n typeof value.threadId === \"string\" && value.parentRunId === undefined\n const hasSubagentLineage = typeof value.parentRunId === \"string\" && value.threadId === undefined\n if (!hasConversationLineage && !hasSubagentLineage) return false\n\n switch (value.type) {\n case \"agent.run.started\":\n return value.modelId === undefined || typeof value.modelId === \"string\"\n case \"agent.compaction.started\":\n return (\n isAgentContextCheckpointReason(value.reason) &&\n isTokenEstimate(value.estimatedInputTokensBefore)\n )\n case \"agent.compaction.completed\":\n return (\n isAgentContextCheckpointReason(value.reason) &&\n typeof value.checkpointId === \"string\" &&\n isTokenEstimate(value.estimatedInputTokensBefore) &&\n isTokenEstimate(value.estimatedInputTokensAfter)\n )\n case \"agent.compaction.failed\":\n return (\n isAgentContextCheckpointReason(value.reason) &&\n AGENT_COMPACTION_FAILURE_CODES.includes(value.errorCode as AgentCompactionFailureCode)\n )\n case \"agent.ui.chunk\":\n // A chunk type this reader does not know fails here, so a newer producer's chunk is skipped.\n return Number.isInteger(value.chunkIndex) && isModelUiChunk(value.chunk)\n case \"agent.inbox.read\":\n return (\n Array.isArray(value.messages) &&\n value.messages.length > 0 &&\n value.messages.every(isAgentInboxReadMessage) &&\n (value.afterChunkIndex === undefined || Number.isInteger(value.afterChunkIndex))\n )\n case \"agent.ui.steps\":\n // As for one chunk: steps holding a chunk this reader does not know are skipped whole.\n return (\n Number.isInteger(value.throughChunkIndex) &&\n Array.isArray(value.chunks) &&\n value.chunks.every(isModelUiChunk) &&\n (value.reads === undefined ||\n (Array.isArray(value.reads) && value.reads.every(isAgentRunStepsRead)))\n )\n case \"agent.message.finalized\":\n return typeof value.messageId === \"string\"\n case \"agent.run.finished\":\n return (\n isTerminalAgentRunStatus(value.status) &&\n (value.finishReason === undefined || typeof value.finishReason === \"string\") &&\n (value.error === undefined || isAgentRunFailure(value.error))\n )\n default:\n return false\n }\n}\n\nfunction isAgentInboxReadMessage(value: unknown): value is AgentInboxReadMessage {\n return (\n isPlainRecord(value) &&\n typeof value.id === \"string\" &&\n isPlainRecord(value.authorPrincipal) &&\n typeof value.authorPrincipal.type === \"string\" &&\n typeof value.authorPrincipal.id === \"string\" &&\n Array.isArray(value.parts) &&\n value.parts.every((part) => isPlainRecord(part) && typeof part.type === \"string\") &&\n isJsonValue(value.parts) &&\n typeof value.createdAt === \"string\"\n )\n}\n\nfunction isAgentRunStepsRead(value: unknown): value is AgentRunStepsRead {\n return (\n isPlainRecord(value) &&\n Number.isInteger(value.at) &&\n (value.at as number) >= 0 &&\n Array.isArray(value.messages) &&\n value.messages.length > 0 &&\n value.messages.every(isAgentInboxReadMessage)\n )\n}\n\nfunction isAgentContextCheckpointReason(value: unknown): value is AgentContextCheckpointReason {\n return value === \"threshold\" || value === \"overflow\"\n}\n\nfunction isTokenEstimate(value: unknown): value is number {\n return Number.isSafeInteger(value) && (value as number) >= 0\n}\n\nfunction isTerminalAgentRunStatus(value: unknown): value is \"succeeded\" | \"failed\" | \"cancelled\" {\n return value === \"succeeded\" || value === \"failed\" || value === \"cancelled\"\n}\n\nfunction isAgentRunStatus(value: unknown): value is AgentRunRecord[\"status\"] {\n return value === \"queued\" || value === \"running\" || isTerminalAgentRunStatus(value)\n}\n\nfunction isAgentRunFailure(value: unknown): value is AgentRunFailure {\n if (!isPlainRecord(value)) return false\n try {\n parseSixbFailure(value, AGENT_RUN_FAILURE_CODES)\n return true\n } catch {\n return false\n }\n}\n\n/** Single owner of the idempotency-key vocabulary for agent run stream records. */\nexport function agentRunStreamIdempotencyKey(event: AgentRunStreamEvent): string {\n switch (event.type) {\n case \"agent.run.started\":\n return `${event.runId}:${event.attempt}:started`\n case \"agent.compaction.started\":\n return `${event.runId}:${event.attempt}:compaction:${event.reason}:started`\n case \"agent.compaction.completed\":\n return `${event.runId}:${event.attempt}:compaction:${event.checkpointId}:completed`\n case \"agent.compaction.failed\":\n return `${event.runId}:${event.attempt}:compaction:${event.reason}:failed:${event.errorCode}`\n case \"agent.ui.chunk\":\n return `${event.runId}:${event.attempt}:chunk:${event.chunkIndex}`\n case \"agent.inbox.read\":\n return `${event.runId}:${event.attempt}:inbox:${event.messages.map((message) => message.id).join(\",\")}:read`\n case \"agent.ui.steps\":\n return `${event.runId}:${event.attempt}:steps:${event.throughChunkIndex}`\n case \"agent.message.finalized\":\n return `${event.runId}:${event.attempt}:message:${event.messageId}:finalized`\n case \"agent.run.finished\":\n return `${event.runId}:${event.attempt}:finished:${event.status}`\n }\n}\n\n/**\n * Ensure the run's stream and append its terminal record — mirrors {@link publishAgentRunCancel}.\n * Used where a terminal transition happens outside the worker (e.g. cancelling a queued run).\n */\nexport async function publishAgentRunFinished(broker: Broker, run: AgentRunRecord): Promise<void> {\n const event = agentRunFinishedEvent(run)\n await broker.ensureStream({\n projectId: run.projectId,\n stream: agentRunStreamDefinition(run.id),\n })\n await broker.append({\n projectId: run.projectId,\n streamId: agentRunStreamId(run.id),\n records: [\n {\n name: event.type,\n key: event.runId,\n // The event is built from JSON primitives only, so the round-trip is a safe narrowing.\n payload: JSON.parse(JSON.stringify(event)) as JsonValue,\n idempotencyKey: agentRunStreamIdempotencyKey(event),\n },\n ],\n })\n if (run.kind === \"conversation\") await publishAgentRunActivity(broker, run)\n}\n"
6
+ ],
7
+ "mappings": ";;;;;;;;;;;;;;;;;AAkBO,IAAM,mCAAkC;AACxC,IAAM,sCAAqC;AAAA,EAChD,UAAU,IAAI,KAAK,KAAK;AAAA,EACxB,YAAY;AACd;AAOO,IAAM,qCAAoC;AAAA,EAC/C,UAAU,KAAK,KAAK,KAAK;AAAA,EACzB,UAAU,KAAK,OAAO;AACxB;AAEO,IAAM,wCAAuC;AAC7C,IAAM,4BAA2B;AACjC,IAAM,2CAA0C;AAAA,EACrD,UAAU,KAAK,KAAK,KAAK;AAAA,EACzB,YAAY;AACd;AAiBO,SAAS,8BAA6B,GAA2B;AAAA,EACtE,OAAO;AAAA,IACL,IAAI;AAAA,IACJ,WAAW;AAAA,EACb;AAAA;AAGK,SAAS,sBAAqB,CACnC,KACA,aAAmB,IAAI,MACA;AAAA,EACvB,OAAO;AAAA,IACL,eAAe;AAAA,IACf,MAAM;AAAA,IACN,WAAW,IAAI;AAAA,IACf,OAAO,IAAI;AAAA,IACX,UAAU,IAAI;AAAA,IACd,QAAQ,IAAI;AAAA,IACZ,SAAS,IAAI;AAAA,OACT,IAAI,MAAM,WAAW,aAAa,EAAE,QAAQ,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 import {
7
7
  resolveExecutionScopeAuthorization,
8
8
  AuthorizationError2,
9
9
  assertProviderAccess2
10
- } from "./chunk-paxabbqd.js";
10
+ } from "./chunk-tapdssb5.js";
11
11
  import {
12
12
  ConnectorConnectionStorageError2
13
13
  } from "./chunk-2c4j899j.js";
@@ -114,7 +114,7 @@ function createConnectorRuntime(runtime, execution, service) {
114
114
  if (!selector) {
115
115
  throw createConnectorCodedError("connector.configuration_invalid", `[Sixb] Connector '${definition.id}' uses persistent connections and requires an explicit owner and slot.`);
116
116
  }
117
- assertPersonalConnectionRequester(definition, execution, selector);
117
+ assertPersonalConnectionRequester(definition, execution.requestedBy, selector);
118
118
  return service.connectConnection(definition, selector);
119
119
  }
120
120
  if (selector) {
@@ -184,9 +184,8 @@ function getConnectorExecutionSourceResolver(connector) {
184
184
  }
185
185
  };
186
186
  }
187
- function assertPersonalConnectionRequester(definition, execution, selector) {
187
+ function assertPersonalConnectionRequester(definition, requester, selector) {
188
188
  const owner = selector.owner;
189
- const requester = execution.requestedBy;
190
189
  if (owner?.type !== "user" || requester === undefined)
191
190
  return;
192
191
  if (requester.type === "user" && requester.id === owner.id)
@@ -203,6 +202,6 @@ function assertConnectorConnectionAccess(runtime, execution) {
203
202
  throw new AuthorizationError2("privileged:connector-connection.connect", "[Sixb] Connector connection clients are restricted to trusted primitive executions.");
204
203
  }
205
204
 
206
- export { ConnectorError2, ConnectorNotFoundError2, ConnectorOAuthError2, createConnectorCodedError, createAmbiguousProviderOperationError, oauthErrorKind, providerFailureCode, providerBoundaryError, isConnectorStorageError, storageBoundaryError, recoverConnectorFailure, createConnectorConnections, createConnectorRuntime, getConnectorExecutionSourceResolver };
205
+ export { ConnectorError2, ConnectorNotFoundError2, ConnectorOAuthError2, createConnectorCodedError, createAmbiguousProviderOperationError, oauthErrorKind, providerFailureCode, providerBoundaryError, isConnectorStorageError, storageBoundaryError, recoverConnectorFailure, createConnectorConnections, createConnectorRuntime, getConnectorExecutionSourceResolver, assertPersonalConnectionRequester };
207
206
 
208
- //# debugId=282C1E0822CA723364756E2164756E21
207
+ //# debugId=A54FC8D36B58AADA64756E2164756E21
@@ -0,0 +1,12 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/connectors/errors.ts", "../src/connectors/connection-handles.ts", "../src/connectors/execution.ts"],
4
+ "sourcesContent": [
5
+ "import {\n createSixbError,\n isSixbError,\n type SixbCodedError,\n type SixbErrorOptions,\n} from \"../errors/internal\"\nimport type { SixbErrorCode } from \"../errors/types\"\nimport { ConnectorConnectionStorageError } from \"../storage/connector-connections/errors\"\n\ntype ConnectorCodedErrorCode = Extract<SixbErrorCode, `connector.${string}`> | \"internal.unexpected\"\n\n/**\n * Legacy authoring error for static connector definitions and lookup.\n *\n * Persistent connection lifecycle failures use the global `SixbErrorCode` contract instead.\n * `ConnectorOAuthError` remains a class because adapters and Core need `instanceof` control flow at\n * the provider-effect boundary.\n */\nexport class ConnectorError extends Error {\n readonly name: string = \"ConnectorError\"\n}\n\nexport class ConnectorNotFoundError extends ConnectorError {\n override readonly name = \"ConnectorNotFoundError\"\n constructor(readonly connectorId: string) {\n super(`Unknown connector '${connectorId}'`)\n }\n}\n\n/**\n * Provider mutation outcome reported by an OAuth adapter.\n *\n * `retryable` guarantees that the provider made no change. `terminal` means the current grant can\n * no longer progress. `ambiguous` means the provider may have changed state; Core fails closed.\n * This classifies the provider effect, not the final Sixb error retry policy: Core also accounts for\n * one-use state, consumed authorization codes, and durable mutation phase before choosing a code.\n */\nexport type ConnectorOAuthErrorKind = \"retryable\" | \"terminal\" | \"ambiguous\"\n\n/** Adapter signal used by Core to decide whether a provider operation can be retried safely. */\nexport class ConnectorOAuthError extends ConnectorError {\n override readonly name = \"ConnectorOAuthError\"\n\n constructor(\n readonly kind: ConnectorOAuthErrorKind,\n message: string,\n options?: ErrorOptions\n ) {\n super(message, options)\n }\n}\n\n/** Internal factory for connector failures that cross a Sixb boundary. */\nexport function createConnectorCodedError(\n code: ConnectorCodedErrorCode,\n message: string,\n options: SixbErrorOptions = {}\n): SixbCodedError {\n return createSixbError(\n code,\n message.startsWith(\"[Sixb]\") ? message : `[Sixb] ${message}`,\n options\n )\n}\n\n/** Internal failure used when a provider operation may have completed after Core lost its fence. */\nexport function createAmbiguousProviderOperationError(\n options: SixbErrorOptions = {}\n): SixbCodedError {\n return createConnectorCodedError(\n \"connector.provider_failed\",\n \"Connector provider operation outcome is ambiguous.\",\n options\n )\n}\n\nexport function oauthErrorKind(error: unknown): ConnectorOAuthErrorKind {\n return error instanceof ConnectorOAuthError ? error.kind : \"ambiguous\"\n}\n\nexport function providerFailureCode(\n error: unknown\n): \"connector.provider_failed\" | \"connector.provider_unavailable\" {\n return oauthErrorKind(error) === \"retryable\"\n ? \"connector.provider_unavailable\"\n : \"connector.provider_failed\"\n}\n\nexport function providerBoundaryError(\n error: unknown,\n code: \"connector.provider_failed\" | \"connector.provider_unavailable\",\n message: string\n): Error {\n if (isSixbError(error) && error.code.startsWith(\"connector.\")) return error\n return createConnectorCodedError(code, message, { cause: error })\n}\n\nexport function isConnectorStorageError(\n error: unknown,\n code?: ConnectorConnectionStorageError[\"code\"]\n): error is ConnectorConnectionStorageError {\n return (\n error instanceof ConnectorConnectionStorageError && (code === undefined || error.code === code)\n )\n}\n\nexport function storageBoundaryError(error: unknown, message: string): SixbCodedError {\n return createConnectorCodedError(\"internal.unexpected\", message, { cause: error })\n}\n\nexport async function recoverConnectorFailure<T>(\n primaryError: unknown,\n message: string,\n recovery: () => Promise<T>\n): Promise<T> {\n try {\n return await recovery()\n } catch (recoveryError) {\n throw createConnectorCodedError(\"internal.unexpected\", message, {\n cause: new AggregateError([primaryError, recoveryError], message),\n })\n }\n}\n",
6
+ "import { createConnectorCodedError } from \"./errors\"\nimport type { ConnectorExecutionSourceResolver } from \"./execution\"\nimport {\n type ConnectorConnectionHandle,\n type ConnectorConnectionMetadata,\n type ConnectorConnections,\n type ConnectorDefinition,\n isOAuthConnectorDefinition,\n} from \"./types\"\n\n/**\n * Handles on the connections of one connector, read through the run's connection resolver. Each\n * call lists again, so a connection that went away since is not handed out. `mayUse` narrows the\n * list to what the run may act with.\n */\nexport function createConnectorConnections<TClient>(\n resolver: ConnectorExecutionSourceResolver,\n definition: ConnectorDefinition,\n mayUse: (connection: ConnectorConnectionMetadata) => boolean\n): ConnectorConnections<TClient> {\n const handles = async (\n matches: (connection: ConnectorConnectionMetadata) => boolean\n ): Promise<readonly ConnectorConnectionHandle<TClient>[]> => {\n if (!isOAuthConnectorDefinition(definition)) {\n throw createConnectorCodedError(\n \"connector.configuration_invalid\",\n `Connector '${definition.id}' has no connections: it is not an OAuth connector.`\n )\n }\n const sources = await resolver.list(definition)\n return sources.flatMap(({ connection }) =>\n connection && mayUse(connection) && matches(connection) ? [handle(connection)] : []\n )\n }\n\n const handle = (connection: ConnectorConnectionMetadata): ConnectorConnectionHandle<TClient> => {\n let clientPromise: Promise<TClient> | undefined\n return {\n connection,\n client() {\n clientPromise ??= (async () => {\n const current = (await resolver.list(definition)).find(\n (candidate) =>\n candidate.connection?.id === connection.id &&\n candidate.connection.account.id === connection.account.id\n )\n if (!current)\n throw createConnectorCodedError(\n \"connector.not_found\",\n \"The connection is no longer active for this account.\"\n )\n return (await current.connect(new AbortController().signal)) as TClient\n })()\n return clientPromise\n },\n }\n }\n\n return {\n list: () => handles(() => true),\n async forAccount(accountId) {\n if (typeof accountId !== \"string\" || !accountId.trim()) {\n throw createConnectorCodedError(\n \"connector.configuration_invalid\",\n \"Account ID must be a non-empty string.\"\n )\n }\n return handles((connection) => connection.account.id === accountId)\n },\n }\n}\n",
7
+ "import { AuthorizationError, assertProviderAccess } from \"../authorization\"\nimport type { AuthorizablePrincipal, ExecutionContext } from \"../execution\"\nimport { resolveExecutionScopeAuthorization } from \"../execution/authorization\"\nimport type { SixbRuntimeContext } from \"../runtime/types\"\nimport { createConnectorConnections } from \"./connection-handles\"\nimport { createConnectorCodedError } from \"./errors\"\nimport type { ConnectorService } from \"./service\"\nimport type {\n AnyConnectorAdapter,\n ConnectorAdapter,\n ConnectorClient,\n ConnectorConnectionMetadata,\n ConnectorConnectionSelector,\n ConnectorConnections,\n ConnectorDefinition,\n OAuthConnectorAdapter,\n} from \"./types\"\nimport { isOAuthConnectorDefinition } from \"./types\"\n\n/** Resolve a registered connector through one authorized execution. */\nexport interface ConnectorRuntime {\n <TAdapter extends ConnectorAdapter>(\n definition: ConnectorDefinition<string, TAdapter>\n ): Promise<ConnectorClient<TAdapter>>\n <TAdapter extends OAuthConnectorAdapter>(\n definition: ConnectorDefinition<string, TAdapter>,\n selector: ConnectorConnectionSelector\n ): Promise<ConnectorClient<TAdapter>>\n /**\n * The connections of an OAuth connector this run may use: a run someone requested gets the\n * project's and their own, and a run no one requested, such as one a schedule started, gets\n * every connected one whose owner isn't suspended.\n */\n connections<TAdapter extends OAuthConnectorAdapter>(\n definition: ConnectorDefinition<string, TAdapter>\n ): ConnectorConnections<ConnectorClient<TAdapter>>\n}\n\nexport interface ConnectorExecutionSource<\n TAdapter extends AnyConnectorAdapter = AnyConnectorAdapter,\n> {\n readonly connection?: ConnectorConnectionMetadata\n connect(signal: AbortSignal): Promise<ConnectorClient<TAdapter>>\n}\n\nexport interface ConnectorExecutionSourceResolver {\n list<TAdapter extends AnyConnectorAdapter>(\n definition: ConnectorDefinition<string, TAdapter>\n ): Promise<readonly ConnectorExecutionSource<TAdapter>[]>\n}\n\nconst sourceResolvers = new WeakMap<ConnectorRuntime, ConnectorExecutionSourceResolver>()\n\nexport function createConnectorRuntime(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext,\n service: ConnectorService\n): ConnectorRuntime {\n const connector = ((definition: ConnectorDefinition, selector?: ConnectorConnectionSelector) => {\n if (isOAuthConnectorDefinition(definition)) {\n assertConnectorConnectionAccess(runtime, execution)\n if (!selector) {\n throw createConnectorCodedError(\n \"connector.configuration_invalid\",\n `[Sixb] Connector '${definition.id}' uses persistent connections and requires an explicit owner and slot.`\n )\n }\n assertPersonalConnectionRequester(definition, execution.requestedBy, selector)\n return service.connectConnection(definition, selector)\n }\n if (selector) {\n throw createConnectorCodedError(\n \"connector.configuration_invalid\",\n `[Sixb] Static connector '${definition.id}' does not accept a connection.`\n )\n }\n assertProviderAccess(runtime, execution, \"connector.connect\")\n return service.connect(definition as ConnectorDefinition<string, ConnectorAdapter>)\n }) as ConnectorRuntime\n\n const resolver: ConnectorExecutionSourceResolver = {\n async list<TAdapter extends AnyConnectorAdapter>(\n definition: ConnectorDefinition<string, TAdapter>\n ): Promise<readonly ConnectorExecutionSource<TAdapter>[]> {\n if (!isOAuthConnectorDefinition(definition)) {\n return [\n {\n connect: (_signal) =>\n connector(definition as ConnectorDefinition<string, ConnectorAdapter>) as Promise<\n ConnectorClient<TAdapter>\n >,\n },\n ]\n }\n\n assertConnectorConnectionAccess(runtime, execution)\n const connections = await service.listExecutionConnections(definition)\n return connections.map((connection) => ({\n connection: {\n id: connection.id,\n connectorId: connection.connectorId,\n owner: connection.owner,\n slot: connection.slot,\n account: connection.account,\n },\n // A grant that can no longer give a token fails here, before anything is read.\n connect: async (signal): Promise<ConnectorClient<TAdapter>> => {\n await service.assertExecutionConnectionUsable(definition, connection)\n return service.connectExecutionConnection(definition, connection, signal) as Promise<\n ConnectorClient<TAdapter>\n >\n },\n }))\n },\n }\n registerConnectorExecutionSourceResolver(connector, resolver)\n connector.connections = <TAdapter extends OAuthConnectorAdapter>(\n definition: ConnectorDefinition<string, TAdapter>\n ) =>\n createConnectorConnections<ConnectorClient<TAdapter>>(resolver, definition, (connection) =>\n mayUsePersonalConnection(execution, connection)\n )\n return connector\n}\n\n/** The rule `assertPersonalConnectionRequester` enforces, as a filter. */\nfunction mayUsePersonalConnection(\n execution: ExecutionContext,\n connection: ConnectorConnectionMetadata\n): boolean {\n const owner = connection.owner\n const requester = execution.requestedBy\n if (owner.type !== \"user\" || requester === undefined) return true\n return requester.type === \"user\" && requester.id === owner.id\n}\n\nfunction registerConnectorExecutionSourceResolver(\n connector: ConnectorRuntime,\n resolver: ConnectorExecutionSourceResolver\n): void {\n const registered = sourceResolvers.get(connector)\n if (registered && registered !== resolver) {\n throw new Error(\"[Sixb] Connector source resolver is already registered for this execution.\")\n }\n sourceResolvers.set(connector, resolver)\n}\n\nexport function getConnectorExecutionSourceResolver(\n connector: ConnectorRuntime\n): ConnectorExecutionSourceResolver {\n const resolver = sourceResolvers.get(connector)\n if (resolver) return resolver\n\n return {\n async list<TAdapter extends AnyConnectorAdapter>(\n definition: ConnectorDefinition<string, TAdapter>\n ): Promise<readonly ConnectorExecutionSource<TAdapter>[]> {\n if (isOAuthConnectorDefinition(definition)) {\n throw createConnectorCodedError(\n \"connector.configuration_invalid\",\n `[Sixb] OAuth connector '${definition.id}' cannot be resolved without the managed connection runtime.`\n )\n }\n return [\n {\n connect: (_signal) =>\n connector(definition as ConnectorDefinition<string, ConnectorAdapter>) as Promise<\n ConnectorClient<TAdapter>\n >,\n },\n ]\n },\n }\n}\n\n/**\n * A run someone requested opens only that person's own connection, so no one can act with another\n * person's account by calling an action, even with can.manage. A run no one requested, such as one\n * an event or a schedule started, picks the owner from its data, as syncs and webhooks do.\n */\nexport function assertPersonalConnectionRequester(\n definition: Pick<ConnectorDefinition, \"id\">,\n requester: AuthorizablePrincipal | undefined,\n selector: ConnectorConnectionSelector\n): void {\n const owner = selector.owner\n if (owner?.type !== \"user\" || requester === undefined) return\n if (requester.type === \"user\" && requester.id === owner.id) return\n throw new AuthorizationError(\n `connection:connector:${definition.id}`,\n `[Sixb] A run requested by someone else can't use a personal connection of connector '${definition.id}'. Only its owner's own runs, or runs no one requested, can.`\n )\n}\n\nfunction assertConnectorConnectionAccess(\n runtime: SixbRuntimeContext,\n execution: ExecutionContext\n): void {\n const resolved = resolveExecutionScopeAuthorization(runtime.projectId, {\n execution,\n authorization: runtime.runtimeAuthorization,\n })\n if (resolved.type === \"unrestricted\" && resolved.ref.type === \"trustedPrimitive\") return\n throw new AuthorizationError(\n \"privileged:connector-connection.connect\",\n \"[Sixb] Connector connection clients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IAAW;AAAA,EACvD,IAAI,UAAU,SAAS,UAAU,UAAU,OAAO,MAAM;AAAA,IAAI;AAAA,EAC5D,MAAM,IAAI,oBACR,wBAAwB,WAAW,MACnC,wFAAwF,WAAW,gEACrG;AAAA;AAGF,SAAS,+BAA+B,CACtC,SACA,WACM;AAAA,EACN,MAAM,WAAW,mCAAmC,QAAQ,WAAW;AAAA,IACrE;AAAA,IACA,eAAe,QAAQ;AAAA,EACzB,CAAC;AAAA,EACD,IAAI,SAAS,SAAS,kBAAkB,SAAS,IAAI,SAAS;AAAA,IAAoB;AAAA,EAClF,MAAM,IAAI,oBACR,2CACA,qFACF;AAAA;",
10
+ "debugId": "A54FC8D36B58AADA64756E2164756E21",
11
+ "names": []
12
+ }
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/storage/agents/types.ts"],
4
4
  "sourcesContent": [
5
- "import type { ActionSubject } from \"../../actions/types\"\nimport type { AgentMessage, AgentMessagePart, AgentMessageRole } from \"../../agents/message\"\nimport type { AgentReasoning } from \"../../agents/types\"\nimport type { Principal, UserPrincipal } from \"../../auth\"\nimport type { FileRef } from \"../../blob-storage/types\"\nimport type { SixbErrorCode, SixbFailure } from \"../../errors/types\"\nimport type { JsonObject, JsonValue } from \"../../json\"\nimport type {\n LanguageModelRef,\n LanguageModelTier,\n LanguageModelTierProbabilities,\n} from \"../../models\"\nimport type { ActionRunFailure, ActionRunParams } from \"../action-runs/types\"\n\n// ── agent_threads — one conversation with an agent ──────────────────────────────────────────────\n\nexport type AgentThreadStatus = \"active\" | \"archived\"\n\n/** Immutable, non-secret application input. Never store resolved env or credentials here. */\nexport type AgentThreadSandboxParams = Readonly<Record<string, JsonValue>>\n\n/** Worker-owned state, independent from the immutable application binding. */\nexport interface AgentThreadSandboxState {\n /** Exact name passed to the provider. Replacements always receive a fresh name. */\n readonly name: string\n readonly status: \"new\" | \"busy\" | \"ready\" | \"blocked\" | \"unavailable\"\n readonly sourceFingerprint?: string\n readonly initialized: boolean\n /** Durable context boundary: local files from before this reset are no longer available. */\n readonly resetAt?: string\n /** Never expires automatically: a delayed provider operation must not reach a successor. */\n readonly owner?: { readonly runId: string; readonly executionToken: string }\n}\n\nexport type TransitionAgentThreadSandboxInput = {\n readonly projectId: string\n readonly id: string\n} & (\n | {\n readonly action: \"acquire\"\n readonly runId: string\n readonly executionToken: string\n readonly name: string\n readonly sourceFingerprint: string\n }\n | {\n readonly action: \"replace\"\n readonly runId: string\n readonly executionToken: string\n readonly name: string\n readonly nextName: string\n }\n | {\n readonly action: \"settle\"\n readonly runId: string\n readonly executionToken: string\n readonly name: string\n readonly status: \"ready\" | \"blocked\" | \"unavailable\"\n readonly initialized: boolean\n }\n | {\n readonly action: \"recreate\"\n readonly expectedSandboxName: string\n readonly name: string\n }\n | {\n /** Go on in the sandbox a failed save left, as its owner chose: the one named `name`. */\n readonly action: \"restore\"\n readonly name: string\n }\n)\n\n/**\n * A conversation, or the thread a sub-agent works in. A sub-agent's thread is never listed, and\n * whoever reads its conversation reads it.\n */\nexport type AgentThreadKind = \"conversation\" | \"subagent\"\n\n/** Where a sub-agent's thread comes from: its conversation, the turn that spawned it, and its key. */\nexport interface AgentThreadParent {\n readonly threadId: string\n /** The turn that spawned it. Its later runs work under the turns that go on with it. */\n readonly spawnedBy: string\n readonly key: string\n}\n\n/** The computer a thread runs on, and the folder there its turns work in. */\nexport interface AgentThreadComputer {\n /** The CLI's id for the computer: a thread's turns are claimed by that computer alone. */\n readonly id: string\n /** What its owner calls the computer, such as \"Anthony's MacBook Pro\". */\n readonly name: string\n /** The absolute path its turns work in, on that computer. */\n readonly folder: string\n}\n\n/** Where a thread runs: which of its owner's computers, and the folder there. */\nexport type AgentThreadPlace = Pick<AgentThreadComputer, \"id\" | \"folder\">\n\nexport interface AgentThreadRecord {\n readonly id: string\n readonly projectId: string\n readonly kind: AgentThreadKind\n /** Set exactly on a sub-agent's thread. */\n readonly parent?: AgentThreadParent\n /** Who owns/opened the thread. Reuses the canonical auth principal (gains `agent` later for free). */\n readonly ownerPrincipal: Principal\n readonly title?: string\n readonly sandboxParams?: AgentThreadSandboxParams\n readonly sandboxState?: AgentThreadSandboxState\n /**\n * Where its turns run: on its owner's computer, which claims them, or, when absent, in the cloud.\n * A computer's thread takes turns from its owner alone.\n */\n readonly runsOn?: \"computer\"\n /**\n * Where on its owner's computers a computer's thread runs: set when it is created, and when its\n * owner moves it. Only that computer, open in that folder, claims its turns. A computer's thread\n * created before folders were kept has none until its owner moves it.\n */\n readonly computer?: AgentThreadComputer\n /**\n * When its turns last moved to where they run now, from a computer to the cloud or between\n * folders: the files earlier turns worked on are not here.\n */\n readonly movedAt?: Date\n readonly status: AgentThreadStatus\n /** Single-flight anchor: the id of the one run currently allowed to write, or `null` when idle. */\n readonly activeRunId: string | null\n readonly lastMessageAt?: Date\n readonly messageCount: number\n readonly createdAt: Date\n readonly updatedAt: Date\n}\n\nexport interface CreateAgentThreadInput {\n readonly id: string\n readonly projectId: string\n readonly ownerPrincipal: Principal\n readonly title?: string\n readonly sandboxParams?: AgentThreadSandboxParams\n readonly runsOn?: \"computer\"\n /** Where a computer's thread runs: required with `runsOn: \"computer\"`, refused without it. */\n readonly computer?: AgentThreadComputer\n readonly status?: AgentThreadStatus\n readonly createdAt?: Date\n readonly updatedAt?: Date\n}\n\n/**\n * A new thread holding a copy of another thread's finished messages. A turn still running is left\n * behind: what came from its trigger message on is not copied. Copies keep their `seq`, content,\n * author and `runId`, and get new ids. Runs are not copied, so the fork's runs, usage and cost are\n * its own; copied answers still show their run's diagnostics.\n *\n * Only the latest checkpoint the copy can use comes along, so the markers of earlier compactions\n * are not in the fork. The fork has no `lastMessageAt` until its first new message, so it sorts\n * by its creation.\n */\nexport interface ForkAgentThreadInput {\n readonly projectId: string\n /** The thread whose history is copied. */\n readonly sourceThreadId: string\n readonly id: string\n readonly ownerPrincipal: Principal\n readonly title?: string\n readonly sandboxParams?: AgentThreadSandboxParams\n /** Provider name of the fork's new sandbox; given exactly when `sandboxParams` is. */\n readonly sandboxName?: string\n /**\n * The source's shared artifacts, each id mapped to its copy's: the copied messages and summary\n * name the copies instead.\n */\n readonly artifactCopies?: Readonly<Record<string, string>>\n readonly createdAt?: Date\n}\n\n/** A conversation's sub-agent threads, oldest first. */\nexport interface ListAgentThreadChildrenInput {\n readonly projectId: string\n /** The conversation. */\n readonly parentThreadId: string\n /** Only those this turn spawned. */\n readonly parentRunId?: string\n /** At most this many, 100 by default. */\n readonly limit?: number\n readonly offset?: number\n}\n\n/** Conversations only: a sub-agent's thread is read through its conversation. */\nexport interface ListAgentThreadsInput {\n readonly projectId: string\n readonly statuses?: readonly AgentThreadStatus[]\n readonly ownerPrincipal?: Principal\n /** Only the threads this user takes part in. */\n readonly participantPrincipal?: UserPrincipal\n /** Only the threads that run on this computer, in this folder, with a turn active. */\n readonly activeOnComputer?: AgentThreadPlace\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListAgentThreadsResult {\n readonly threads: readonly AgentThreadRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n// ── agent_thread_participants — the users a thread's owner added to it ─────────────────────────\n\nexport interface AgentThreadParticipantRecord {\n readonly projectId: string\n readonly threadId: string\n readonly principal: UserPrincipal\n readonly addedAt: Date\n readonly addedBy: Principal\n}\n\nexport interface AddAgentThreadParticipantsInput {\n readonly projectId: string\n readonly threadId: string\n /**\n * Distinct users, checked by the caller. Someone already taking part keeps when and by whom they\n * were first added.\n */\n readonly principals: readonly UserPrincipal[]\n readonly addedBy: Principal\n /** Refused with `participant_limit`, adding no one, when the thread would hold more. */\n readonly maxParticipants: number\n readonly addedAt?: Date\n}\n\nexport interface AssignAgentThreadComputerInput {\n readonly projectId: string\n readonly id: string\n /** Where the thread's turns run from now on. */\n readonly computer: AgentThreadComputer\n /** Its `movedAt` when this changes the computer or folder of a thread that had one. */\n readonly movedAt?: Date\n}\n\nexport interface MoveAgentThreadToCloudInput {\n readonly projectId: string\n readonly id: string\n readonly movedAt?: Date\n}\n\n/** A computer's thread, now in the cloud, and its queued turn, now the cloud's to run. */\nexport interface MoveAgentThreadToCloudResult {\n readonly thread: AgentThreadRecord\n readonly queued?: ConversationAgentRunRecord\n}\n\n/**\n * An open `sixb` on its owner's computer: while it is live, the threads that run on that computer\n * in its folder are reachable there. It ends when `sixb` closes, or lapses when it stops renewing.\n */\nexport interface AgentComputerSessionRecord {\n readonly projectId: string\n /** Chosen by the computer, once per open `sixb`; unique among its owner's sessions. */\n readonly id: string\n readonly ownerPrincipal: Principal\n readonly computer: AgentThreadComputer\n readonly expiresAt: Date\n /** Its threads' background commands, as its latest renewal reported them. */\n readonly backgroundCommands?: readonly AgentComputerBackgroundCommand[]\n /** The commands someone asked to stop: each renewal hands back those still running. */\n readonly stopRequests?: readonly AgentBackgroundCommandRef[]\n}\n\n/** How many background commands a computer session reports, and keeps stop requests for. */\nexport const AGENT_COMPUTER_BACKGROUND_COMMANDS_MAX = 64\n\n/**\n * A background command an open `sixb` runs for one of its threads, which outlives the turn that\n * started it: the web shows how it stands between turns.\n */\nexport interface AgentComputerBackgroundCommand {\n readonly threadId: string\n /** `bg_<hex>`, as the agent's tools name it. */\n readonly id: string\n readonly command: string\n readonly status: \"running\" | \"exited\" | \"stopped\"\n readonly exitCode?: number\n /** ISO timestamps. */\n readonly startedAt: string\n readonly endedAt?: string\n}\n\n/** A background command by its start: its id comes again once `sixb` restarts. */\nexport interface AgentBackgroundCommandRef {\n readonly threadId: string\n readonly id: string\n readonly startedAt: string\n}\n\nexport interface RemoveAgentThreadParticipantInput {\n readonly projectId: string\n readonly threadId: string\n readonly principal: UserPrincipal\n}\n\nexport interface ListAgentThreadParticipantsInput {\n readonly projectId: string\n readonly threadIds: readonly string[]\n}\n\n// ── agent_runs — one loop execution (the worker job; attribution + fencing) ───────────────────\n\n/** Lifecycle shared by every durable agent execution, conversational or workflow-owned. */\nexport type AgentExecutionStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\"\n\nexport type AgentRunStatus = AgentExecutionStatus\nexport type AgentRunKind = \"conversation\" | \"subagent\"\n\n/** Error codes an agent execution can persist and expose through its public contract. */\nexport const AGENT_RUN_FAILURE_CODES = [\n \"internal.unexpected\",\n \"runtime.cancelled\",\n \"agent.context_limit_exceeded\",\n \"agent.execution_failed\",\n \"agent.step_limit_reached\",\n \"ai.usage_limit_exceeded\",\n \"ai.usage_limit_unavailable\",\n] as const satisfies readonly [SixbErrorCode, ...SixbErrorCode[]]\n\nexport type AgentRunFailureCode = (typeof AGENT_RUN_FAILURE_CODES)[number]\n\n/**\n * Why a run ended — Sixb's provider-independent vocabulary. It includes model-loop reasons plus\n * platform-level endings such as `timeout`, `interrupted` for a turn whose worker died before\n * finishing it, `awaiting_approval` for a succeeded turn that paused on calls waiting for its\n * requester, or `awaiting_answer` for a succeeded sub-agent that paused on a question its parent\n * answers in a later turn, so reads remain typed and exhaustive. `other` and `unknown` preserve terminal state\n * when a provider adds a new reason.\n */\nexport const AGENT_RUN_FINISH_REASONS = [\n \"stop\",\n \"length\",\n \"content-filter\",\n \"tool-calls\",\n \"timeout\",\n \"interrupted\",\n \"awaiting_approval\",\n \"awaiting_answer\",\n \"error\",\n \"other\",\n \"unknown\",\n] as const\n\nexport type AgentRunFinishReason = (typeof AGENT_RUN_FINISH_REASONS)[number]\n\n/**\n * Coerce an external finish-reason string — a DB column or an SDK value — to {@link\n * AgentRunFinishReason}. An unrecognised value becomes `\"unknown\"` rather than being dropped.\n */\nexport function coerceAgentRunFinishReason(\n value: string | null | undefined\n): AgentRunFinishReason | undefined {\n if (value === null || value === undefined) {\n return undefined\n }\n return (AGENT_RUN_FINISH_REASONS as readonly string[]).includes(value)\n ? (value as AgentRunFinishReason)\n : \"unknown\"\n}\n\n/** Stable, user-facing diagnostics emitted by the platform while executing a run. */\nexport const AGENT_RUN_DIAGNOSTIC_CODES = [\"step_limit_reached\", \"output_limit_reached\"] as const\n\n/**\n * Closed on purpose, and the wire is closed with it.\n *\n * Sixb writes these codes and the generated client is what reads them, so an open union would only\n * be honest if the HTTP schema were open too — and that costs the OpenAPI enum, the client's\n * autocompletion, and the app's exhaustive `switch`. Sixb owns both ends, so a new code is a minor\n * version bump: cheap here, and a broken `switch` is better than a 500 from `z.enum`.\n */\nexport type AgentRunDiagnosticCode = (typeof AGENT_RUN_DIAGNOSTIC_CODES)[number]\nexport type AgentRunDiagnosticSeverity = \"warning\" | \"error\"\n\nexport interface AgentRunDiagnostic {\n readonly code: AgentRunDiagnosticCode\n readonly severity: AgentRunDiagnosticSeverity\n /** What the diagnostic is about: the turn as a whole. */\n readonly scope: \"run\"\n /** Sanitized, stable copy suitable for display to an end user. */\n readonly message: string\n}\n\n/**\n * Authorization state for the current queue delivery.\n *\n * `queueLeaseExpiresAt` is a persisted projection of `ClaimedQueueJob.leaseExpiresAt`, not an\n * independently managed run lease. It may only be extended from a successful queue lease renewal.\n */\nexport interface AgentRunExecution {\n readonly token: string\n readonly queueLeaseExpiresAt: Date\n}\n\ninterface AgentRunRecordBase {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly status: AgentRunStatus\n readonly modelId?: string\n /** Why the run ended (our own SDK-independent enum). */\n readonly finishReason?: AgentRunFinishReason\n /** Platform diagnostics are transcript annotations, never agent-authored message content. */\n readonly diagnostics?: readonly AgentRunDiagnostic[]\n /** Portable failure snapshot when the run did not succeed. */\n readonly error?: SixbFailure<AgentRunFailureCode>\n /** Execution attempts: `0` while queued, `1` on first start, incremented on redelivery. */\n readonly attempt: number\n readonly execution?: AgentRunExecution\n /**\n * When someone asked a running run to stop. Its run token stops working at once, and its runner\n * learns of it at its next lease renewal if the broker's cancel never reached it.\n */\n readonly cancelRequestedAt?: Date\n readonly createdAt: Date\n readonly startedAt?: Date\n readonly completedAt?: Date\n}\n\nexport interface ConversationAgentRunRecord extends AgentRunRecordBase {\n readonly kind: \"conversation\"\n readonly threadId: string\n readonly triggerMessageId: string\n /** Immutable model selection captured at admission. Absent only on runs predating this field. */\n readonly spec?: ConversationAgentRunSpec\n}\n\n/** Immutable, serialisable model selection and requester settings for one conversational turn. */\nexport interface ConversationAgentRunSpec {\n readonly model: LanguageModelRef\n /** With tiers, the tier of the model the turn runs on. */\n readonly tier?: LanguageModelTier\n /**\n * How likely the decision model judged each tier, when Sixb picked the turn's model. Kept to\n * calibrate the thresholds the tier is picked from (`heavy` from 0.4, `light` from 0.8).\n */\n readonly tierProbabilities?: LanguageModelTierProbabilities\n readonly reasoning?: AgentReasoning\n /** Canonical IANA time zone of the requester. Absent uses the project time zone. */\n readonly timeZone?: string\n /** Canonical BCP 47 language of the requester. Absent uses the project locale. */\n readonly locale?: string\n /** What the turn may change without asking its requester. Absent on older runs: `auto`. */\n readonly approvalMode?: AgentApprovalMode\n /** Its thread's `runsOn` when it was asked for: a computer's turn never reaches the agent queue. */\n readonly runsOn?: \"computer\"\n}\n\n/** Immutable, serialisable child configuration captured before dispatch. */\nexport interface SubagentRunSpec {\n readonly model: LanguageModelRef\n /** With tiers, the tier of the model the child runs on. Absent on children admitted before it. */\n readonly tier?: LanguageModelTier\n readonly reasoning?: AgentReasoning\n /** Focused task supplied by the parent Agent. */\n readonly task: string\n /** At most this many steps per run, as its parent asked: the project's limit still applies. */\n readonly maxSteps?: number\n /** Project tools available when the child was admitted. Runtime tools are injected separately. */\n readonly toolNames: readonly string[]\n /** The parent turn's mode, copied when the child was admitted. Absent: `auto`. */\n readonly approvalMode?: AgentApprovalMode\n /** The parent turn's requester settings. Absent uses the project's. */\n readonly timeZone?: string\n readonly locale?: string\n /** Files the parent handed over, copied into the child's sandbox at these paths. */\n readonly files?: readonly SubagentRunFile[]\n}\n\n/** A file a parent and its child hand each other, stored once and copied into a sandbox. */\nexport interface SubagentRunFile {\n /** Relative, `/`-separated, without `.` or `..` segments. */\n readonly path: string\n readonly fileRef: FileRef\n}\n\n/** Durable child output returned to its parent by `wait`. */\nexport interface SubagentRunResult {\n /** Empty only for a child that paused on its held calls before it answered. */\n readonly text: string\n /** What the child wrote under `out/`, by path relative to it. */\n readonly files?: readonly SubagentRunFile[]\n /** Why none of what it wrote under `out/` came back, and what to do about it. */\n readonly filesError?: string\n /**\n * What its parent sent a paused child that it had not read: the run that continues it reads it\n * first.\n */\n readonly unread?: readonly { readonly id: string; readonly text: string }[]\n}\n\nexport interface SubagentRunRecord extends AgentRunRecordBase {\n readonly kind: \"subagent\"\n /** The child's own thread, which holds its task and its work. */\n readonly threadId: string\n /** The message of its thread that started the run. */\n readonly triggerMessageId: string\n /** The conversation turn the child runs under: its mode and cancellation. */\n readonly parentRunId: string\n /** Stable parent-selected key that makes repeated tool execution idempotent. */\n readonly spawnKey: string\n readonly spec: SubagentRunSpec\n readonly result?: SubagentRunResult\n}\n\nexport type AgentRunRecord = ConversationAgentRunRecord | SubagentRunRecord\n\nexport interface CreateAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly threadId: string\n readonly triggerMessageId: string\n readonly spec: ConversationAgentRunSpec\n readonly createdAt?: Date\n}\n\nexport interface CreateSubagentRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly parentRunId: string\n /** Current parent delivery token. New children are admitted only while that delivery owns it. */\n readonly parentExecutionToken: string\n readonly spawnKey: string\n readonly spec: SubagentRunSpec\n /**\n * The child's thread. Its first run creates it, owned by the conversation's owner; a later run\n * goes into it, and is refused while another run of the thread is active.\n */\n readonly thread: { readonly id: string; readonly create: boolean }\n /** The user message that starts the run, appended to the child's thread with the run's id. */\n readonly trigger: Pick<AppendAgentMessageInput, \"id\" | \"parts\" | \"metadata\">\n /** Internal safety bound enforced atomically across worker processes. */\n readonly maxActiveChildren: number\n readonly createdAt?: Date\n}\n\nexport interface StartAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly modelId?: string\n readonly execution: AgentRunExecution\n readonly startedAt?: Date\n /**\n * Start it only as a computer's turn, there and in that folder: one whose thread moved meanwhile\n * is refused with `invalid_state`, so it never starts where its thread no longer runs.\n */\n readonly onComputer?: AgentThreadPlace\n}\n\nexport interface FinishQueuedAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\" | \"cancelled\"\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly completedAt?: Date\n}\n\nexport interface ReclaimAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly execution: AgentRunExecution\n /**\n * Take the run over only if the lease last recorded on it ran out by then, checked in the same\n * write: a renewal that lands first keeps it its runner's. Otherwise `invalid_state`.\n */\n readonly ifLapsedBy?: Date\n}\n\nexport interface ConfirmAgentRunExecutionOwnershipInput {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n /** Exact expiration returned by the queue claim or its latest successful renewal. */\n readonly queueLeaseExpiresAt: Date\n}\n\nexport interface RequestAgentRunCancelInput {\n readonly id: string\n readonly projectId: string\n readonly at?: Date\n}\n\nexport type FinishAgentRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n readonly status: \"succeeded\"\n readonly modelId?: string\n readonly finishReason?: AgentRunFinishReason\n readonly diagnostics?: readonly AgentRunDiagnostic[]\n readonly result?: SubagentRunResult\n readonly completedAt?: Date\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n readonly status: \"failed\" | \"cancelled\"\n readonly modelId?: string\n /** Only a succeeded run pauses. */\n readonly finishReason?: Exclude<AgentRunFinishReason, \"awaiting_approval\" | \"awaiting_answer\">\n readonly diagnostics?: readonly AgentRunDiagnostic[]\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly completedAt?: Date\n }\n\nexport interface ListAgentRunsInput {\n readonly projectId: string\n readonly kinds?: readonly AgentRunKind[]\n readonly threadId?: string\n readonly parentRunId?: string\n readonly statuses?: readonly AgentRunStatus[]\n /** Effective start time; runs that never started use `createdAt`. */\n readonly startedAfter?: Date\n /** Effective start time; runs that never started use `createdAt`. */\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n /** Leave out the turns that wait for a computer: only a worker's to run. */\n readonly excludeComputerTurns?: boolean\n}\n\nexport interface ListThreadSubagentsInput {\n readonly projectId: string\n /** The conversation whose turns spawned them. */\n readonly threadId: string\n readonly spawnKey?: string\n readonly finishReason?: AgentRunFinishReason\n /** At most this many, 100 by default. */\n readonly limit?: number\n}\n\nexport interface ListAgentRunsResult {\n readonly runs: readonly AgentRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n// ── agent_messages — one message (assistant messages inserted only once finalized) ─────────────\n\nexport type { AgentMessageRole }\n\nexport interface AgentMessageRecord {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n /**\n * The run that produced this message; `null` for user-authored messages. In a sub-agent's thread\n * every message has one, its trigger too, so a run's messages are deleted whole. A message copied\n * by a fork keeps the run that produced it, which belongs to the thread it was copied from.\n */\n readonly runId: string | null\n readonly role: AgentMessageRole\n /** Principal that authored this persisted message: caller for user messages, agent identity later for assistant messages. */\n readonly authorPrincipal?: Principal\n /** Monotonic per thread, assigned by the store. */\n readonly seq: number\n /** Structured message content — text / reasoning / step boundaries / tool calls. */\n readonly parts: readonly AgentMessagePart[]\n /** Message-level metadata (mirrors `UIMessage.metadata`). */\n readonly metadata?: JsonValue\n /** Versions the `parts` shape so it can be migrated; stamped from `AGENT_MESSAGE_CONTENT_VERSION`. */\n readonly contentVersion: number\n readonly createdAt: Date\n readonly completedAt?: Date\n}\n\n/** Append a message: a {@link AgentMessage} (role + parts + metadata) plus its storage identity. */\nexport interface AppendAgentMessageInput extends AgentMessage {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n readonly runId: string | null\n readonly authorPrincipal?: Principal\n readonly createdAt?: Date\n readonly completedAt?: Date\n}\n\nexport interface DeleteAgentMessagesByRunInput {\n readonly projectId: string\n readonly threadId: string\n readonly runId: string\n /**\n * The run that deletes them, when one does: refused with `execution_lost` unless it still runs\n * under this token, checked in the same transaction as the delete.\n */\n readonly fence?: { readonly runId: string; readonly executionToken: string }\n}\n\nexport interface ListAgentMessagesInput {\n readonly projectId: string\n readonly threadId: string\n /** Return only messages whose per-thread sequence is greater than this retained boundary. */\n readonly afterSeq?: number\n readonly roles?: readonly AgentMessageRole[]\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListAgentMessagesResult {\n readonly messages: readonly AgentMessageRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n// ── agent_context_checkpoints — append-only model-context boundaries ──────────────────────────\n\nexport type AgentContextCheckpointReason = \"threshold\" | \"overflow\"\n\n/**\n * A durable summary boundary used only when projecting a thread into model context.\n *\n * Checkpoints never replace or mutate transcript messages. Normal thread reads remain authoritative\n * and complete; the worker reads the latest checkpoint and only the retained message tail.\n */\nexport interface AgentContextCheckpointRecord {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n /** A fork's copy keeps the run that wrote the summary, in the thread it was copied from. */\n readonly createdByRunId: string\n readonly previousCheckpointId?: string\n readonly reason: AgentContextCheckpointReason\n readonly summary: string\n readonly summaryFormatVersion: 1\n readonly summarizedThroughSeq: number\n readonly observedHeadSeq: number\n readonly estimatedInputTokensBefore: number\n readonly estimatedInputTokensAfter: number\n readonly summaryModelId: string\n readonly createdAt: Date\n}\n\nexport interface CreateAgentContextCheckpointInput {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n readonly createdByRunId: string\n /** Compare-and-swap anchor. `null` means the thread must not have a prior checkpoint. */\n readonly expectedPreviousCheckpointId: string | null\n /** Compare-and-swap anchor for the complete transcript observed by the summarizer. */\n readonly expectedHeadSeq: number\n /** Current delivery token for `createdByRunId`; stale redeliveries must not write. */\n readonly executionToken: string\n readonly reason: AgentContextCheckpointReason\n readonly summary: string\n readonly summaryFormatVersion: 1\n readonly summarizedThroughSeq: number\n readonly observedHeadSeq: number\n readonly estimatedInputTokensBefore: number\n readonly estimatedInputTokensAfter: number\n readonly summaryModelId: string\n readonly createdAt?: Date\n}\n\n// ── Store ───────────────────────────────────────────────────────────────────────────────────────\n\nexport interface AgentThreadStore {\n /** Atomic run-fenced transition, or explicit idle-thread recreation. */\n transitionSandbox(input: TransitionAgentThreadSandboxInput): Promise<AgentThreadSandboxState>\n create(input: CreateAgentThreadInput): Promise<AgentThreadRecord>\n /**\n * Create a thread holding a copy of another's finished history, in one transaction. The source's\n * sub-agent threads are not copied, and a sub-agent's thread is refused.\n */\n fork(input: ForkAgentThreadInput): Promise<AgentThreadRecord>\n getById(params: { projectId: string; id: string }): Promise<AgentThreadRecord | null>\n /** The threads found, in first-occurrence input order; a missing one is omitted. */\n getByIds(params: {\n readonly projectId: string\n readonly ids: readonly string[]\n }): Promise<readonly AgentThreadRecord[]>\n list(input: ListAgentThreadsInput): Promise<ListAgentThreadsResult>\n /** The sub-agents' threads of a conversation, by creation and id, all of them or one turn's. */\n listChildren(input: ListAgentThreadChildrenInput): Promise<readonly AgentThreadRecord[]>\n /**\n * Add users atomically and return every participant of the thread afterwards. A sub-agent's\n * thread has none: its readers are its conversation's.\n */\n addParticipants(\n input: AddAgentThreadParticipantsInput\n ): Promise<readonly AgentThreadParticipantRecord[]>\n /** Whether the user took part until now. */\n removeParticipant(input: RemoveAgentThreadParticipantInput): Promise<boolean>\n /**\n * Move a computer's thread to another computer or folder, and return the thread after. A cloud\n * thread runs on none, and is refused.\n */\n assignComputer(input: AssignAgentThreadComputerInput): Promise<AgentThreadRecord>\n /**\n * Move a computer's thread to the cloud, in one transaction with its queued turn, which the cloud\n * runs instead. Refused with `active_run_exists` while a turn runs on the computer, and\n * `invalid_input` for a thread already in the cloud.\n */\n moveToCloud(input: MoveAgentThreadToCloudInput): Promise<MoveAgentThreadToCloudResult>\n /** The participants of these threads, oldest first, then by user id and thread id. */\n listParticipants(\n input: ListAgentThreadParticipantsInput\n ): Promise<readonly AgentThreadParticipantRecord[]>\n}\n\nexport interface AgentRunStore {\n /**\n * Persist a queued turn and atomically claim the thread's single-flight slot. A sub-agent's\n * thread takes only child runs.\n */\n create(input: CreateAgentRunInput): Promise<ConversationAgentRunRecord>\n /**\n * Persist or replay one idempotent child run while atomically enforcing parent fan-out. In one\n * transaction it creates the child's thread or takes it (single-flight, as a conversation), then\n * appends the trigger and the run.\n */\n createSubagent(input: CreateSubagentRunInput): Promise<SubagentRunRecord>\n /** Transition a queued run to running and install the first delivery's execution token. */\n start(input: StartAgentRunInput): Promise<AgentRunRecord>\n /** Finish a queued run before execution and release the thread's single-flight slot. */\n finishQueued(input: FinishQueuedAgentRunInput): Promise<AgentRunRecord>\n /** Rotate the execution token for a redelivered running job (`attempt++`). */\n reclaim(input: ReclaimAgentRunInput): Promise<AgentRunRecord>\n /**\n * Project the queue's latest confirmed ownership expiration onto the current execution.\n * Implementations must fence by token and must never move the expiration backwards.\n */\n confirmExecutionOwnership(input: ConfirmAgentRunExecutionOwnershipInput): Promise<AgentRunRecord>\n /**\n * Record that a running run was asked to stop, keeping the first time it was. A run in any other\n * state is returned as it is: a queued one is cancelled with `finishQueued`.\n */\n requestCancel(input: RequestAgentRunCancelInput): Promise<AgentRunRecord>\n /**\n * Finalize a run and release the thread's `activeRunId`. `finishReason: \"awaiting_approval\"`\n * needs a call the run holds (see `approvals.holdsRun`). A turn that ends any other way cancels\n * its pending approvals and stops resuming on the rest; a child that fails or is cancelled\n * cancels its own pending ones.\n */\n finish(input: FinishAgentRunInput): Promise<AgentRunRecord>\n getById(params: { projectId: string; id: string }): Promise<AgentRunRecord | null>\n getByIds(params: {\n projectId: string\n ids: readonly string[]\n }): Promise<readonly AgentRunRecord[]>\n /**\n * The children of a conversation's turns, the latest turn's first, by its effective start, and\n * within a turn the latest admitted first. Read by key (one per turn) or by finish reason.\n */\n listThreadSubagents(input: ListThreadSubagentsInput): Promise<readonly SubagentRunRecord[]>\n list(input: ListAgentRunsInput): Promise<ListAgentRunsResult>\n}\n\nexport interface AgentMessageStore {\n /** Insert a message (its `parts` are the canonical content) and bump thread stats. */\n append(input: AppendAgentMessageInput): Promise<AgentMessageRecord>\n /** Delete every message produced by one run and repair the thread's message stats. */\n deleteByRunId(input: DeleteAgentMessagesByRunInput): Promise<number>\n getById(params: { projectId: string; id: string }): Promise<AgentMessageRecord | null>\n list(input: ListAgentMessagesInput): Promise<ListAgentMessagesResult>\n}\n\nexport interface AgentContextCheckpointStore {\n /**\n * Append one checkpoint after atomically validating run ownership and both transcript anchors.\n * Repeating the same payload for the same creating run is idempotent.\n */\n create(input: CreateAgentContextCheckpointInput): Promise<AgentContextCheckpointRecord>\n /** The thread's checkpoints created by the requested runs, in first-occurrence input order. */\n getByRunIds(input: {\n readonly projectId: string\n readonly threadId: string\n readonly runIds: readonly string[]\n }): Promise<readonly AgentContextCheckpointRecord[]>\n getLatest(input: {\n readonly projectId: string\n readonly threadId: string\n }): Promise<AgentContextCheckpointRecord | null>\n}\n\n// ── agent_approvals — calls of the Agent that wait for whoever asked ───────────────────────────\n\n/**\n * What the Agent may change without asking its requester: `manual` asks for every action and\n * workflow, `accept-edits` runs the actions that only change Sixb, `auto` runs everything.\n */\nexport const AGENT_APPROVAL_MODES = [\"manual\", \"accept-edits\", \"auto\"] as const\n\nexport type AgentApprovalMode = (typeof AGENT_APPROVAL_MODES)[number]\n\n/** The modes that hold some calls: the one that held a call is recorded on its approval. */\nexport const AGENT_HOLDING_APPROVAL_MODES = [\n \"manual\",\n \"accept-edits\",\n] as const satisfies readonly AgentApprovalMode[]\n\nexport type AgentHoldingApprovalMode = (typeof AGENT_HOLDING_APPROVAL_MODES)[number]\n\nexport const AGENT_APPROVAL_STATUSES = [\n \"pending\",\n \"approved\",\n \"denied\",\n \"cancelled\",\n \"superseded\",\n \"expired\",\n] as const\n\nexport type AgentApprovalStatus = (typeof AGENT_APPROVAL_STATUSES)[number]\n\n/** The statuses a pending approval is settled to without a decision. */\nexport type AgentApprovalSettledStatus = Extract<\n AgentApprovalStatus,\n \"cancelled\" | \"superseded\" | \"expired\"\n>\n\n/**\n * The held call, as it runs once approved. An action's params are normalized: what the user\n * approves is exactly what runs. Its run id is the one the Agent named, so a repeated request finds\n * the same approval and the same run.\n */\nexport type AgentApprovalCall =\n | {\n readonly kind: \"action\"\n readonly actionId: string\n readonly subject: ActionSubject\n readonly params: ActionRunParams\n readonly actionRunId: string\n /** `external` when the action has a writeback or effects: it reaches beyond Sixb. */\n readonly effect: \"ontology\" | \"external\"\n }\n | {\n readonly kind: \"workflow\"\n readonly workflowId: string\n readonly input: JsonObject\n readonly workflowRunId: string\n }\n\n/** What running an approved call gave. */\nexport type AgentApprovalOutcome =\n | {\n readonly kind: \"action-run\"\n readonly runId: string\n readonly status: \"succeeded\" | \"failed\"\n readonly error?: ActionRunFailure\n }\n | { readonly kind: \"workflow-run\"; readonly runId: string; readonly queuedAt: string }\n /** The call was refused when it ran, for example because its requester lost a grant. */\n | { readonly kind: \"error\"; readonly error: SixbFailure }\n\nexport interface AgentApprovalRecord {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n /** The conversation turn the call belongs to. */\n readonly runId: string\n /** The run that made the call: the turn itself, or one of its children. */\n readonly callerRunId: string\n /** Who asked for the turn: the only one who decides, as the call runs with their rights. */\n readonly requestedBy: Principal\n /** The mode that held the call. */\n readonly mode: AgentHoldingApprovalMode\n /** The call's run id, unique among a thread's pending, approved and denied approvals. */\n readonly callKey: string\n readonly call: AgentApprovalCall\n readonly status: AgentApprovalStatus\n readonly createdAt: Date\n readonly expiresAt: Date\n readonly decidedAt?: Date\n readonly decidedBy?: Principal\n /** Set once an approved call ran. */\n readonly outcome?: AgentApprovalOutcome\n /** The user message that told the model how the approval ended. */\n readonly reportedInMessageId?: string\n /** \"Always allow\": the mode its requester raised the turn's calls to when deciding this one. */\n readonly raisedMode?: AgentApprovalMode\n /**\n * The turn will not resume for it: stopped, its requester left, or another of its calls was set\n * aside. The thread's next message still reports it.\n */\n readonly turnStoppedAt?: Date\n /** When a process last took the approved call to run it; a stale claim can be taken again. */\n readonly executionClaimedAt?: Date\n}\n\nexport interface RequestAgentApprovalInput {\n readonly id: string\n readonly projectId: string\n readonly runId: string\n readonly callerRunId: string\n /** The caller run's current delivery token: a stale delivery holds nothing. */\n readonly executionToken: string\n readonly requestedBy: Principal\n readonly mode: AgentHoldingApprovalMode\n readonly call: AgentApprovalCall\n readonly createdAt?: Date\n readonly expiresAt: Date\n}\n\nexport interface RequestAgentApprovalResult {\n readonly approval: AgentApprovalRecord\n /** `false` when a pending, approved or denied approval of the thread had the same call key. */\n readonly created: boolean\n}\n\nexport interface DecideAgentApprovalInput {\n readonly projectId: string\n readonly id: string\n readonly decision: \"approved\" | \"denied\"\n readonly decidedBy: Principal\n readonly decidedAt?: Date\n /** With `approved`: \"Always allow\" raised the turn's mode to this one. */\n readonly raisedMode?: AgentApprovalMode\n}\n\nexport interface DecideAgentApprovalResult {\n /** The approval afterwards: `expired` when its time ran out before this decision. */\n readonly approval: AgentApprovalRecord\n /** Whether this call moved it out of `pending` with the decision. */\n readonly decided: boolean\n}\n\nexport interface SettleAgentApprovalsInput {\n readonly projectId: string\n readonly threadId: string\n readonly status: AgentApprovalSettledStatus\n}\n\n/** Stop a thread's turn, or a requester's turns there, from resuming on their calls. */\nexport interface StopAgentApprovalsInput {\n readonly projectId: string\n readonly threadId: string\n /** Only the calls of this conversation turn. */\n readonly runId?: string\n /** Only the calls this principal asked for. */\n readonly requestedBy?: Principal\n readonly stoppedAt?: Date\n}\n\nexport interface StopAgentApprovalsResult {\n /** The pending approvals it cancelled. */\n readonly cancelled: readonly AgentApprovalRecord[]\n /** How many unreported approvals it stopped, the cancelled ones included. */\n readonly stopped: number\n}\n\n/** Where a keyset listing resumes: after this approval, in the order approvals are listed. */\nexport interface AgentApprovalCursor {\n readonly createdAt: Date\n readonly id: string\n}\n\nexport interface MarkAgentApprovalsReportedInput {\n readonly projectId: string\n readonly threadId: string\n readonly ids: readonly string[]\n readonly messageId: string\n /** A resume: an approval whose turn was stopped is not marked. */\n readonly resuming?: boolean\n}\n\nexport interface ListAgentApprovalsInput {\n readonly projectId: string\n readonly threadId?: string\n readonly runId?: string\n readonly requestedBy?: Principal\n readonly statuses?: readonly AgentApprovalStatus[]\n /** `false`: only the approvals no message reported yet. */\n readonly reported?: boolean\n readonly limit?: number\n readonly offset?: number\n}\n\nexport interface ListAgentApprovalsResult {\n /** Oldest first. */\n readonly approvals: readonly AgentApprovalRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n/**\n * Held calls and their decisions. `runs.finish` settles a run's approvals in its own transaction:\n * a turn that pauses keeps them for their decision, any other ending cancels its pending ones.\n */\nexport interface AgentApprovalStore {\n /**\n * Fenced like a checkpoint: the caller run is running with `executionToken`, and is the\n * conversation turn `runId` or one of its children. Returns the thread's pending, approved or\n * denied approval with the same call key when there is one, and creates one otherwise.\n */\n request(input: RequestAgentApprovalInput): Promise<RequestAgentApprovalResult>\n /** Compare-and-swap from `pending`; `null` when no such approval exists. */\n decide(input: DecideAgentApprovalInput): Promise<DecideAgentApprovalResult | null>\n /** Record what an approved call gave, once: an approval with an outcome is returned unchanged. */\n recordOutcome(input: {\n readonly projectId: string\n readonly id: string\n readonly outcome: AgentApprovalOutcome\n }): Promise<AgentApprovalRecord>\n /** Settle the thread's pending approvals, and return the ones it settled. */\n settle(input: SettleAgentApprovalsInput): Promise<readonly AgentApprovalRecord[]>\n /** Expire the project's pending approvals whose time ran out by `now`, and return them. */\n expireDue(input: {\n readonly projectId: string\n readonly now: Date\n readonly limit?: number\n }): Promise<readonly AgentApprovalRecord[]>\n /**\n * Cancel the matching pending approvals and mark every matching one no message reported yet as\n * stopped: their turn never resumes on them.\n */\n stop(input: StopAgentApprovalsInput): Promise<StopAgentApprovalsResult>\n /** Mark the ones no message reported yet, and return their ids. */\n markReported(input: MarkAgentApprovalsReportedInput): Promise<readonly string[]>\n /**\n * Whether the run holds a call: one of its approvals, or one it made for its turn, pending, or\n * decided and not reported yet. `runs.finish` checks the same before `awaiting_approval`.\n */\n holdsRun(input: { readonly projectId: string; readonly runId: string }): Promise<boolean>\n /**\n * Take an approved call without an outcome to run it, unless another process took it after\n * `staleBefore`; its decision is its first claim. `null` when it is not there to take.\n */\n claimExecution(input: {\n readonly projectId: string\n readonly id: string\n readonly claimedAt: Date\n readonly staleBefore: Date\n }): Promise<AgentApprovalRecord | null>\n /**\n * What a repair pass works on, oldest first: approved calls without an outcome whose claim is\n * older than `claimableBefore`, and decided calls no message reported whose turn is not stopped.\n */\n listRepairable(input: {\n readonly projectId: string\n readonly claimableBefore: Date\n readonly after?: AgentApprovalCursor\n readonly limit: number\n }): Promise<readonly AgentApprovalRecord[]>\n getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<AgentApprovalRecord | null>\n list(input: ListAgentApprovalsInput): Promise<ListAgentApprovalsResult>\n}\n\n/** Each user's approval mode: a default, and their own choice in each thread. */\nexport interface AgentApprovalModeStore {\n getDefault(input: {\n readonly projectId: string\n readonly principal: Principal\n }): Promise<AgentApprovalMode | null>\n setDefault(input: {\n readonly projectId: string\n readonly principal: Principal\n readonly mode: AgentApprovalMode\n readonly updatedAt?: Date\n }): Promise<void>\n getForThread(input: {\n readonly projectId: string\n readonly threadId: string\n readonly principal: Principal\n }): Promise<AgentApprovalMode | null>\n /**\n * `null` clears the choice: the user's turns in the thread follow their default again. Throws\n * `thread_not_found` when the thread does not exist.\n */\n setForThread(input: {\n readonly projectId: string\n readonly threadId: string\n readonly principal: Principal\n readonly mode: AgentApprovalMode | null\n readonly updatedAt?: Date\n }): Promise<void>\n}\n\n// ── Memory ──────────────────────────────────────────────────────────────────────────────────────\n\n/** One file of a memory repo, at its path from the repo root. */\nexport interface AgentMemoryFile {\n readonly path: string\n readonly contents: string\n}\n\n/** A memory repo as of its latest revision. */\nexport interface AgentMemoryRepoRecord {\n /** 0 before the first save. */\n readonly revision: number\n /** Ordered by path. */\n readonly files: readonly AgentMemoryFile[]\n}\n\n/** One change of a save: the file's new contents, or `null` to delete it. */\nexport interface AgentMemoryChange {\n readonly path: string\n readonly contents: string | null\n}\n\nexport interface SaveAgentMemoryInput {\n readonly projectId: string\n /** `user:<userId>` or `project`. */\n readonly repoId: string\n /** The revision the caller loaded. */\n readonly baseRevision: number\n readonly message: string\n readonly author: Principal\n /** The conversation the save came from, `/agents/<threadId>`. */\n readonly source?: string\n readonly changes: readonly AgentMemoryChange[]\n readonly createdAt?: Date\n}\n\nexport type SaveAgentMemoryResult =\n | { readonly saved: true; readonly revision: number }\n | {\n readonly saved: false\n /** The repo's latest revision. */\n readonly revision: number\n /** Files in `changes` that another save changed after `baseRevision`, as they are now. */\n readonly conflicts: readonly AgentMemoryChange[]\n }\n\n/** One save: who made it, why, and which paths it wrote. A revision never changes. */\nexport interface AgentMemoryRevisionRecord {\n readonly revision: number\n readonly message: string\n readonly author: Principal\n readonly source?: string\n /** Ordered by path. */\n readonly changes: readonly { readonly path: string; readonly deleted: boolean }[]\n readonly createdAt: Date\n}\n\nexport interface ListAgentMemoryRevisionsInput {\n readonly projectId: string\n readonly repoId: string\n readonly limit?: number\n readonly offset?: number\n}\n\nexport interface ListAgentMemoryRevisionsResult {\n /** Newest first. */\n readonly revisions: readonly AgentMemoryRevisionRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n/**\n * Memory repos as append-only revisions: a save inserts one revision and the files it wrote, and\n * never updates a row. Paths, sizes and who may save are decided in Core before a call reaches\n * storage.\n */\nexport interface AgentMemoryStore {\n /**\n * The repo at its latest revision, or with `asOf` at the latest revision saved by then, and with\n * `revision` at the latest up to that one: revision 0 and no files when none was. File versions\n * pruned from the history are missing from it.\n */\n get(input: {\n readonly projectId: string\n readonly repoId: string\n readonly asOf?: Date\n readonly revision?: number\n }): Promise<AgentMemoryRepoRecord>\n /**\n * In one transaction: reports a conflict when a path in `changes` was written after\n * `baseRevision`, or when the repo is behind `baseRevision` because it was deleted; otherwise\n * stores the next revision. The same transaction removes file versions older than\n * {@link AGENT_MEMORY_HISTORY_DAYS} days that are not their path's latest.\n */\n save(input: SaveAgentMemoryInput): Promise<SaveAgentMemoryResult>\n listRevisions(input: ListAgentMemoryRevisionsInput): Promise<ListAgentMemoryRevisionsResult>\n /** Deletes the repo with its history. */\n delete(input: { readonly projectId: string; readonly repoId: string }): Promise<void>\n}\n\n/** How long a file version that is not its path's latest stays in a repo's history. */\nexport const AGENT_MEMORY_HISTORY_DAYS = 90\n\n/** Each open `sixb` on its owner's computers, as a lease it renews. */\nexport interface AgentComputerSessionStore {\n /**\n * Open the session, or renew it until `expiresAt`; its computer, folder and background commands\n * are kept as given, and its stop requests as they are.\n */\n hold(input: Omit<AgentComputerSessionRecord, \"stopRequests\">): Promise<void>\n /**\n * Record that someone asked to stop one of its commands, once, keeping the newest\n * {@link AGENT_COMPUTER_BACKGROUND_COMMANDS_MAX}. Null when the owner holds no such session.\n */\n requestStop(input: {\n readonly projectId: string\n readonly id: string\n readonly ownerPrincipal: Principal\n readonly command: AgentBackgroundCommandRef\n }): Promise<AgentComputerSessionRecord | null>\n /** End the owner's session; null when it is not open. */\n release(input: {\n readonly projectId: string\n readonly id: string\n readonly ownerPrincipal: Principal\n }): Promise<AgentComputerSessionRecord | null>\n /** The owner's sessions live at `now`. */\n listLive(input: {\n readonly projectId: string\n readonly ownerPrincipal: Principal\n readonly now: Date\n }): Promise<readonly AgentComputerSessionRecord[]>\n /** Remove every session that lapsed before `now`, and return them. */\n removeLapsed(input: {\n readonly projectId: string\n readonly now: Date\n }): Promise<readonly AgentComputerSessionRecord[]>\n}\n\n// ── agent_token_rates — what each model's tokenizer measured on the project's agent runs ──────\n\n/** How many measurements a project keeps per model: its newest. */\nexport const AGENT_TOKEN_RATE_SAMPLES = 20\n\n/**\n * The band of bytes per token a measurement may show. Every tokenizer measured on agent turns\n * reads 2.1 to 4.7; a value outside is a broken measurement, and a single one would set its\n * model's rate for the whole project.\n */\nexport const AGENT_TOKEN_RATE_MIN_BYTES_PER_TOKEN = 1\nexport const AGENT_TOKEN_RATE_MAX_BYTES_PER_TOKEN = 8\n\n/**\n * One run's measurement of its model's tokenizer: the UTF-8 bytes of a request's text, as the\n * Agent's context estimator weighs them, against the text tokens the provider counted for it.\n */\nexport interface AgentTokenRateRecord {\n readonly projectId: string\n readonly providerId: string\n readonly modelId: string\n /** The agent run or workflow step that measured it: one measurement each. */\n readonly runId: string\n readonly bytes: number\n readonly tokens: number\n readonly measuredAt: Date\n}\n\n/**\n * The newest measurements of each model's bytes per token, per project. Agent runs start their\n * context estimate from them; losing them only makes the next estimates more conservative.\n */\nexport interface AgentTokenRateStore {\n /**\n * Keep a run's measurement, in place of one it recorded before, and drop the model's\n * measurements past its newest {@link AGENT_TOKEN_RATE_SAMPLES}.\n */\n record(input: AgentTokenRateRecord): Promise<void>\n /** The model's measurements, newest first: at most {@link AGENT_TOKEN_RATE_SAMPLES}. */\n listLatest(input: {\n readonly projectId: string\n readonly providerId: string\n readonly modelId: string\n }): Promise<readonly AgentTokenRateRecord[]>\n}\n\n// -- agent_thread_inbox: mid-run steers and queued follow-up messages -------------------------\n\nexport const AGENT_INBOX_MODES = [\"steer\", \"queue\"] as const\nexport type AgentInboxMode = (typeof AGENT_INBOX_MODES)[number]\n\n/** Maximum pending items one conversation thread holds in its inbox at once. */\nexport const AGENT_THREAD_INBOX_MAX_ITEMS = 50\n\n/** Optional per-turn overrides carried by a queued or immediate inbox item. */\nexport interface AgentInboxSpec {\n readonly model?: LanguageModelRef\n readonly reasoning?: AgentReasoning\n readonly approvalMode?: AgentApprovalMode\n}\n\n/** Claim recorded when a running conversation turn drains a `steer` item at a step boundary. */\nexport interface AgentInboxClaim {\n readonly runId: string\n readonly executionToken: string\n readonly stepIndex: number\n readonly afterAnswer?: boolean\n}\n\nexport interface AgentInboxItemRecord {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n /** Stable id reserved for `agent_messages` once this item is delivered. */\n readonly messageId: string\n readonly seq: number\n readonly authorPrincipal: Principal\n readonly mode: AgentInboxMode\n readonly parts: readonly AgentMessagePart[]\n readonly spec?: AgentInboxSpec\n readonly timeZone?: string\n readonly locale?: string\n /** Marked by Send now so `afterAgentRunFinished` dispatches it across a user cancel. */\n readonly immediate?: boolean\n /**\n * The execution of the request that sent it. A turn that starts it without a request of its\n * sender's runs as a child of this one, with the sender's grants as they are then.\n */\n readonly executionId?: string\n readonly claimedBy?: AgentInboxClaim\n readonly createdAt: Date\n readonly updatedAt: Date\n}\n\nexport interface EnqueueAgentInboxItemInput {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n readonly messageId: string\n readonly authorPrincipal: Principal\n readonly mode: AgentInboxMode\n readonly parts: readonly AgentMessagePart[]\n readonly spec?: AgentInboxSpec\n readonly timeZone?: string\n readonly locale?: string\n readonly immediate?: boolean\n readonly executionId?: string\n readonly createdAt?: Date\n}\n\nexport interface EnqueueAgentInboxItemResult {\n readonly item: AgentInboxItemRecord\n readonly created: boolean\n}\n\nexport interface ListAgentInboxItemsInput {\n readonly projectId: string\n readonly threadId: string\n /** Whether items already claimed by a running step are included; defaults to `true`. */\n readonly includeClaimed?: boolean\n}\n\nexport interface UpdateAgentInboxItemInput {\n readonly projectId: string\n readonly threadId: string\n readonly id: string\n readonly mode?: AgentInboxMode\n readonly parts?: readonly AgentMessagePart[]\n readonly spec?: AgentInboxSpec | null\n readonly immediate?: boolean\n readonly updatedAt?: Date\n}\n\nexport interface RemoveAgentInboxItemInput {\n readonly projectId: string\n readonly threadId: string\n readonly id: string\n}\n\nexport interface TakeAgentInboxSteersInput {\n readonly projectId: string\n readonly threadId: string\n readonly runId: string\n readonly executionToken: string\n readonly stepIndex: number\n readonly afterAnswer?: boolean\n /**\n * The run's requester: a turn runs as them, so it reads only the steers they sent. Another\n * participant's steer waits for a turn of theirs.\n */\n readonly authorPrincipal: Principal\n}\n\nexport interface ConsumeClaimedAgentInboxInput {\n readonly projectId: string\n readonly threadId: string\n readonly runId: string\n readonly executionToken: string\n /** Message ids persisted into `agent_messages`; other claims of this run are released. */\n readonly messageIds: readonly string[]\n}\n\nexport interface TakeNextQueuedAgentInboxInput {\n readonly projectId: string\n readonly threadId: string\n /** When `true`, only an item marked `immediate` is popped (used after a user cancel). */\n readonly onlyImmediate?: boolean\n /**\n * Only an item this person sent: a turn runs as its requester, so it starts the messages they\n * sent, and another participant's waits for a turn of theirs.\n */\n readonly authorPrincipal?: Principal\n}\n\nexport interface ListWaitingAgentInboxThreadsInput {\n readonly projectId: string\n /** Only threads holding an item created before this: newer ones a turn's end is still starting. */\n readonly createdBefore: Date\n /** Page after this thread id, in id order. */\n readonly afterThreadId?: string\n readonly limit: number\n}\n\nexport interface AgentInboxStore {\n enqueue(input: EnqueueAgentInboxItemInput): Promise<EnqueueAgentInboxItemResult>\n getById(params: { projectId: string; id: string }): Promise<AgentInboxItemRecord | null>\n list(input: ListAgentInboxItemsInput): Promise<readonly AgentInboxItemRecord[]>\n /** Update an unclaimed inbox item; throws `invalid_state` when already claimed. */\n update(input: UpdateAgentInboxItemInput): Promise<AgentInboxItemRecord | null>\n /** Remove an unclaimed inbox item; throws `invalid_state` when already claimed. */\n remove(input: RemoveAgentInboxItemInput): Promise<AgentInboxItemRecord | null>\n /**\n * Fenced by `(runId, executionToken)`: claim the non-immediate steers `authorPrincipal` sent, in\n * FIFO order. The thread's running turn holds it, so a claim any other execution left behind (one\n * this run replaced, or a turn whose release failed) was never written, and is taken over.\n */\n takeSteers(input: TakeAgentInboxSteersInput): Promise<readonly AgentInboxItemRecord[]>\n /** Consume persisted claims of `(runId, executionToken)` and release any unwritten ones. */\n consumeClaimed(input: ConsumeClaimedAgentInboxInput): Promise<readonly AgentInboxItemRecord[]>\n /** Release remaining claims held by `runId` after an interrupted, failed, or cancelled turn. */\n releaseClaimed(input: { projectId: string; runId: string }): Promise<number>\n /** Pop the next unclaimed item when `thread.activeRunId` is null; null when busy or empty. */\n takeNextQueued(input: TakeNextQueuedAgentInboxInput): Promise<AgentInboxItemRecord | null>\n /** Ids of threads no turn holds whose inbox still holds an item, for the repair pass. */\n listWaitingThreads(input: ListWaitingAgentInboxThreadsInput): Promise<readonly string[]>\n}\n\nexport interface AgentStorage {\n readonly threads: AgentThreadStore\n readonly runs: AgentRunStore\n readonly messages: AgentMessageStore\n readonly checkpoints: AgentContextCheckpointStore\n readonly memory: AgentMemoryStore\n readonly approvals: AgentApprovalStore\n readonly approvalModes: AgentApprovalModeStore\n readonly computers: AgentComputerSessionStore\n readonly tokenRates: AgentTokenRateStore\n readonly inbox: AgentInboxStore\n}\n"
5
+ "import type { ActionSubject } from \"../../actions/types\"\nimport type { AgentMessage, AgentMessagePart, AgentMessageRole } from \"../../agents/message\"\nimport type { AgentReasoning } from \"../../agents/types\"\nimport type { Principal, UserPrincipal } from \"../../auth\"\nimport type { FileRef } from \"../../blob-storage/types\"\nimport type { SixbErrorCode, SixbFailure } from \"../../errors/types\"\nimport type { JsonObject, JsonValue } from \"../../json\"\nimport type {\n LanguageModelRef,\n LanguageModelTier,\n LanguageModelTierProbabilities,\n} from \"../../models\"\nimport type { ActionRunFailure, ActionRunParams } from \"../action-runs/types\"\n\n// ── agent_threads — one conversation with an agent ──────────────────────────────────────────────\n\nexport type AgentThreadStatus = \"active\" | \"archived\"\n\n/** Immutable, non-secret application input. Never store resolved env or credentials here. */\nexport type AgentThreadSandboxParams = Readonly<Record<string, JsonValue>>\n\n/** Worker-owned state, independent from the immutable application binding. */\nexport interface AgentThreadSandboxState {\n /** Exact name passed to the provider. Replacements always receive a fresh name. */\n readonly name: string\n readonly status: \"new\" | \"busy\" | \"ready\" | \"blocked\" | \"unavailable\"\n readonly sourceFingerprint?: string\n readonly initialized: boolean\n /** Durable context boundary: local files from before this reset are no longer available. */\n readonly resetAt?: string\n /** Never expires automatically: a delayed provider operation must not reach a successor. */\n readonly owner?: { readonly runId: string; readonly executionToken: string }\n}\n\nexport type TransitionAgentThreadSandboxInput = {\n readonly projectId: string\n readonly id: string\n} & (\n | {\n readonly action: \"acquire\"\n readonly runId: string\n readonly executionToken: string\n readonly name: string\n readonly sourceFingerprint: string\n }\n | {\n readonly action: \"replace\"\n readonly runId: string\n readonly executionToken: string\n readonly name: string\n readonly nextName: string\n }\n | {\n readonly action: \"settle\"\n readonly runId: string\n readonly executionToken: string\n readonly name: string\n readonly status: \"ready\" | \"blocked\" | \"unavailable\"\n readonly initialized: boolean\n }\n | {\n readonly action: \"recreate\"\n readonly expectedSandboxName: string\n readonly name: string\n }\n | {\n /** Go on in the sandbox a failed save left, as its owner chose: the one named `name`. */\n readonly action: \"restore\"\n readonly name: string\n }\n)\n\n/**\n * A conversation, or the thread a sub-agent works in. A sub-agent's thread is never listed, and\n * whoever reads its conversation reads it.\n */\nexport type AgentThreadKind = \"conversation\" | \"subagent\"\n\n/** Where a sub-agent's thread comes from: its conversation, the turn that spawned it, and its key. */\nexport interface AgentThreadParent {\n readonly threadId: string\n /** The turn that spawned it. Its later runs work under the turns that go on with it. */\n readonly spawnedBy: string\n readonly key: string\n}\n\n/** The computer a thread runs on, and the folder there its turns work in. */\nexport interface AgentThreadComputer {\n /** The CLI's id for the computer: a thread's turns are claimed by that computer alone. */\n readonly id: string\n /** What its owner calls the computer, such as \"Anthony's MacBook Pro\". */\n readonly name: string\n /** The absolute path its turns work in, on that computer. */\n readonly folder: string\n}\n\n/** Where a thread runs: which of its owner's computers, and the folder there. */\nexport type AgentThreadPlace = Pick<AgentThreadComputer, \"id\" | \"folder\">\n\nexport interface AgentThreadRecord {\n readonly id: string\n readonly projectId: string\n readonly kind: AgentThreadKind\n /** Set exactly on a sub-agent's thread. */\n readonly parent?: AgentThreadParent\n /** Who owns/opened the thread. Reuses the canonical auth principal (gains `agent` later for free). */\n readonly ownerPrincipal: Principal\n readonly title?: string\n readonly sandboxParams?: AgentThreadSandboxParams\n readonly sandboxState?: AgentThreadSandboxState\n /**\n * Where its turns run: on its owner's computer, which claims them, or, when absent, in the cloud.\n * A computer's thread takes turns from its owner alone.\n */\n readonly runsOn?: \"computer\"\n /**\n * Where on its owner's computers a computer's thread runs: set when it is created, and when its\n * owner moves it. Only that computer, open in that folder, claims its turns. A computer's thread\n * created before folders were kept has none until its owner moves it.\n */\n readonly computer?: AgentThreadComputer\n /**\n * When its turns last moved to where they run now, from a computer to the cloud or between\n * folders: the files earlier turns worked on are not here.\n */\n readonly movedAt?: Date\n readonly status: AgentThreadStatus\n /** Single-flight anchor: the id of the one run currently allowed to write, or `null` when idle. */\n readonly activeRunId: string | null\n readonly lastMessageAt?: Date\n readonly messageCount: number\n readonly createdAt: Date\n readonly updatedAt: Date\n}\n\nexport interface CreateAgentThreadInput {\n readonly id: string\n readonly projectId: string\n readonly ownerPrincipal: Principal\n readonly title?: string\n readonly sandboxParams?: AgentThreadSandboxParams\n readonly runsOn?: \"computer\"\n /** Where a computer's thread runs: required with `runsOn: \"computer\"`, refused without it. */\n readonly computer?: AgentThreadComputer\n readonly status?: AgentThreadStatus\n readonly createdAt?: Date\n readonly updatedAt?: Date\n}\n\n/**\n * A new thread holding a copy of another thread's finished messages. A turn still running is left\n * behind: what came from its trigger message on is not copied. Copies keep their `seq`, content,\n * author and `runId`, and get new ids. Runs are not copied, so the fork's runs, usage and cost are\n * its own; copied answers still show their run's diagnostics.\n *\n * Only the latest checkpoint the copy can use comes along, so the markers of earlier compactions\n * are not in the fork. The fork has no `lastMessageAt` until its first new message, so it sorts\n * by its creation.\n */\nexport interface ForkAgentThreadInput {\n readonly projectId: string\n /** The thread whose history is copied. */\n readonly sourceThreadId: string\n readonly id: string\n readonly ownerPrincipal: Principal\n readonly title?: string\n readonly sandboxParams?: AgentThreadSandboxParams\n /** Provider name of the fork's new sandbox; given exactly when `sandboxParams` is. */\n readonly sandboxName?: string\n /**\n * The source's shared artifacts, each id mapped to its copy's: the copied messages and summary\n * name the copies instead.\n */\n readonly artifactCopies?: Readonly<Record<string, string>>\n readonly createdAt?: Date\n}\n\n/** A conversation's sub-agent threads, oldest first. */\nexport interface ListAgentThreadChildrenInput {\n readonly projectId: string\n /** The conversation. */\n readonly parentThreadId: string\n /** Only those this turn spawned. */\n readonly parentRunId?: string\n /** At most this many, 100 by default. */\n readonly limit?: number\n readonly offset?: number\n}\n\n/** Conversations only: a sub-agent's thread is read through its conversation. */\nexport interface ListAgentThreadsInput {\n readonly projectId: string\n readonly statuses?: readonly AgentThreadStatus[]\n readonly ownerPrincipal?: Principal\n /** Only the threads this user takes part in. */\n readonly participantPrincipal?: UserPrincipal\n /** Only the threads that run on this computer, in this folder, with a turn active. */\n readonly activeOnComputer?: AgentThreadPlace\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListAgentThreadsResult {\n readonly threads: readonly AgentThreadRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n// ── agent_thread_participants — the users a thread's owner added to it ─────────────────────────\n\nexport interface AgentThreadParticipantRecord {\n readonly projectId: string\n readonly threadId: string\n readonly principal: UserPrincipal\n readonly addedAt: Date\n readonly addedBy: Principal\n}\n\nexport interface AddAgentThreadParticipantsInput {\n readonly projectId: string\n readonly threadId: string\n /**\n * Distinct users, checked by the caller. Someone already taking part keeps when and by whom they\n * were first added.\n */\n readonly principals: readonly UserPrincipal[]\n readonly addedBy: Principal\n /** Refused with `participant_limit`, adding no one, when the thread would hold more. */\n readonly maxParticipants: number\n readonly addedAt?: Date\n}\n\nexport interface AssignAgentThreadComputerInput {\n readonly projectId: string\n readonly id: string\n /** Where the thread's turns run from now on. */\n readonly computer: AgentThreadComputer\n /** Its `movedAt` when this changes the computer or folder of a thread that had one. */\n readonly movedAt?: Date\n}\n\nexport interface MoveAgentThreadToCloudInput {\n readonly projectId: string\n readonly id: string\n readonly movedAt?: Date\n}\n\n/** A computer's thread, now in the cloud, and its queued turn, now the cloud's to run. */\nexport interface MoveAgentThreadToCloudResult {\n readonly thread: AgentThreadRecord\n readonly queued?: ConversationAgentRunRecord\n}\n\n/**\n * An open `sixb` on its owner's computer: while it is live, the threads that run on that computer\n * in its folder are reachable there. It ends when `sixb` closes, or lapses when it stops renewing.\n */\nexport interface AgentComputerSessionRecord {\n readonly projectId: string\n /** Chosen by the computer, once per open `sixb`; unique among its owner's sessions. */\n readonly id: string\n readonly ownerPrincipal: Principal\n readonly computer: AgentThreadComputer\n readonly expiresAt: Date\n /** Its threads' background commands, as its latest renewal reported them. */\n readonly backgroundCommands?: readonly AgentComputerBackgroundCommand[]\n /** The commands someone asked to stop: each renewal hands back those still running. */\n readonly stopRequests?: readonly AgentBackgroundCommandRef[]\n}\n\n/** How many background commands a computer session reports, and keeps stop requests for. */\nexport const AGENT_COMPUTER_BACKGROUND_COMMANDS_MAX = 64\n\n/**\n * A background command an open `sixb` runs for one of its threads, which outlives the turn that\n * started it: the web shows how it stands between turns.\n */\nexport interface AgentComputerBackgroundCommand {\n readonly threadId: string\n /** `bg_<hex>`, as the agent's tools name it. */\n readonly id: string\n readonly command: string\n readonly status: \"running\" | \"exited\" | \"stopped\"\n readonly exitCode?: number\n /** ISO timestamps. */\n readonly startedAt: string\n readonly endedAt?: string\n}\n\n/** A background command by its start: its id comes again once `sixb` restarts. */\nexport interface AgentBackgroundCommandRef {\n readonly threadId: string\n readonly id: string\n readonly startedAt: string\n}\n\nexport interface RemoveAgentThreadParticipantInput {\n readonly projectId: string\n readonly threadId: string\n readonly principal: UserPrincipal\n}\n\nexport interface ListAgentThreadParticipantsInput {\n readonly projectId: string\n readonly threadIds: readonly string[]\n}\n\n// ── agent_thread_reads — how far each person has read a conversation ──────────────────────────\n\n/**\n * How far one person's reading of a conversation has reached, as the `seq` of its last message.\n *\n * A watermark, not a flag: nothing writes here when a message arrives, so new ones sit past it\n * until the reader moves it. A mark never moves it backwards, so two devices converge on the later\n * position and a stale one cannot rewind the other. Only a deletion does: when a retry or an edit\n * takes the newest messages away, every place past what remains comes back to it, because the next\n * messages take those numbers again.\n */\nexport interface AgentThreadReadRecord {\n readonly projectId: string\n readonly threadId: string\n readonly principal: UserPrincipal\n /** The highest message `seq` this person's reading has reached. 0 when none has. */\n readonly throughSeq: number\n /** When this person last looked: every mark sets it, even one that leaves `throughSeq` alone. */\n readonly readAt: Date\n}\n\n/**\n * One person's place in a conversation, and what arrived past it.\n *\n * `unread` counts the messages past `throughSeq` that are new to them: every Agent answer and\n * every other person's message. What they wrote is not, nor a message that only reports how\n * approved calls ended (`countsAsThreadMessage`).\n */\nexport interface AgentThreadReadState {\n readonly threadId: string\n /** Where their reading reached, never past `headSeq`. 0 when they have no row. */\n readonly throughSeq: number\n /** The `seq` of the thread's newest message, 0 when it has none. */\n readonly headSeq: number\n /** Messages past `throughSeq` that someone else wrote. */\n readonly unread: number\n /** When they last looked; absent until they have a row. */\n readonly readAt?: Date\n}\n\nexport interface MarkAgentThreadReadInput {\n readonly projectId: string\n readonly threadId: string\n readonly principal: UserPrincipal\n /**\n * The last message they read, or the thread's newest when absent. A message the thread no longer\n * holds marks nothing: a retry or an edit took it away, and its number may already name another.\n */\n readonly throughMessageId?: string\n readonly readAt?: Date\n}\n\nexport interface ListAgentThreadReadsInput {\n readonly projectId: string\n readonly threadIds: readonly string[]\n readonly principal: UserPrincipal\n}\n\nexport interface AgentThreadReadStore {\n /**\n * Record that this person's reading reached a message, never moving it back, and that they\n * looked now. A participant has a row from the moment they join, and the migration gave one to\n * everyone in the threads that existed before; an owner without one reads as 0 until their\n * first mark. Answers their place afterwards.\n */\n mark(input: MarkAgentThreadReadInput): Promise<AgentThreadReadState>\n /** One person's place in each of these threads; a thread that does not exist is absent. */\n list(input: ListAgentThreadReadsInput): Promise<readonly AgentThreadReadState[]>\n}\n\n// ── agent_runs — one loop execution (the worker job; attribution + fencing) ───────────────────\n\n/** Lifecycle shared by every durable agent execution, conversational or workflow-owned. */\nexport type AgentExecutionStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\"\n\nexport type AgentRunStatus = AgentExecutionStatus\nexport type AgentRunKind = \"conversation\" | \"subagent\"\n\n/** Error codes an agent execution can persist and expose through its public contract. */\nexport const AGENT_RUN_FAILURE_CODES = [\n \"internal.unexpected\",\n \"runtime.cancelled\",\n \"agent.context_limit_exceeded\",\n \"agent.execution_failed\",\n \"agent.step_limit_reached\",\n \"ai.usage_limit_exceeded\",\n \"ai.usage_limit_unavailable\",\n] as const satisfies readonly [SixbErrorCode, ...SixbErrorCode[]]\n\nexport type AgentRunFailureCode = (typeof AGENT_RUN_FAILURE_CODES)[number]\n\n/**\n * Why a run ended — Sixb's provider-independent vocabulary. It includes model-loop reasons plus\n * platform-level endings such as `timeout`, `interrupted` for a turn whose worker died before\n * finishing it, `awaiting_approval` for a succeeded turn that paused on calls waiting for its\n * requester, or `awaiting_answer` for a succeeded sub-agent that paused on a question its parent\n * answers in a later turn, so reads remain typed and exhaustive. `other` and `unknown` preserve terminal state\n * when a provider adds a new reason.\n */\nexport const AGENT_RUN_FINISH_REASONS = [\n \"stop\",\n \"length\",\n \"content-filter\",\n \"tool-calls\",\n \"timeout\",\n \"interrupted\",\n \"awaiting_approval\",\n \"awaiting_answer\",\n \"error\",\n \"other\",\n \"unknown\",\n] as const\n\nexport type AgentRunFinishReason = (typeof AGENT_RUN_FINISH_REASONS)[number]\n\n/**\n * Coerce an external finish-reason string — a DB column or an SDK value — to {@link\n * AgentRunFinishReason}. An unrecognised value becomes `\"unknown\"` rather than being dropped.\n */\nexport function coerceAgentRunFinishReason(\n value: string | null | undefined\n): AgentRunFinishReason | undefined {\n if (value === null || value === undefined) {\n return undefined\n }\n return (AGENT_RUN_FINISH_REASONS as readonly string[]).includes(value)\n ? (value as AgentRunFinishReason)\n : \"unknown\"\n}\n\n/** Stable, user-facing diagnostics emitted by the platform while executing a run. */\nexport const AGENT_RUN_DIAGNOSTIC_CODES = [\"step_limit_reached\", \"output_limit_reached\"] as const\n\n/**\n * Closed on purpose, and the wire is closed with it.\n *\n * Sixb writes these codes and the generated client is what reads them, so an open union would only\n * be honest if the HTTP schema were open too — and that costs the OpenAPI enum, the client's\n * autocompletion, and the app's exhaustive `switch`. Sixb owns both ends, so a new code is a minor\n * version bump: cheap here, and a broken `switch` is better than a 500 from `z.enum`.\n */\nexport type AgentRunDiagnosticCode = (typeof AGENT_RUN_DIAGNOSTIC_CODES)[number]\nexport type AgentRunDiagnosticSeverity = \"warning\" | \"error\"\n\nexport interface AgentRunDiagnostic {\n readonly code: AgentRunDiagnosticCode\n readonly severity: AgentRunDiagnosticSeverity\n /** What the diagnostic is about: the turn as a whole. */\n readonly scope: \"run\"\n /** Sanitized, stable copy suitable for display to an end user. */\n readonly message: string\n}\n\n/**\n * Authorization state for the current queue delivery.\n *\n * `queueLeaseExpiresAt` is a persisted projection of `ClaimedQueueJob.leaseExpiresAt`, not an\n * independently managed run lease. It may only be extended from a successful queue lease renewal.\n */\nexport interface AgentRunExecution {\n readonly token: string\n readonly queueLeaseExpiresAt: Date\n}\n\ninterface AgentRunRecordBase {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly status: AgentRunStatus\n readonly modelId?: string\n /** Why the run ended (our own SDK-independent enum). */\n readonly finishReason?: AgentRunFinishReason\n /** Platform diagnostics are transcript annotations, never agent-authored message content. */\n readonly diagnostics?: readonly AgentRunDiagnostic[]\n /** Portable failure snapshot when the run did not succeed. */\n readonly error?: SixbFailure<AgentRunFailureCode>\n /** Execution attempts: `0` while queued, `1` on first start, incremented on redelivery. */\n readonly attempt: number\n readonly execution?: AgentRunExecution\n /**\n * When someone asked a running run to stop. Its run token stops working at once, and its runner\n * learns of it at its next lease renewal if the broker's cancel never reached it.\n */\n readonly cancelRequestedAt?: Date\n readonly createdAt: Date\n readonly startedAt?: Date\n readonly completedAt?: Date\n}\n\nexport interface ConversationAgentRunRecord extends AgentRunRecordBase {\n readonly kind: \"conversation\"\n readonly threadId: string\n readonly triggerMessageId: string\n /** Immutable model selection captured at admission. Absent only on runs predating this field. */\n readonly spec?: ConversationAgentRunSpec\n}\n\n/** Immutable, serialisable model selection and requester settings for one conversational turn. */\nexport interface ConversationAgentRunSpec {\n readonly model: LanguageModelRef\n /** With tiers, the tier of the model the turn runs on. */\n readonly tier?: LanguageModelTier\n /**\n * How likely the decision model judged each tier, when Sixb picked the turn's model. Kept to\n * calibrate the thresholds the tier is picked from (`heavy` from 0.4, `light` from 0.8).\n */\n readonly tierProbabilities?: LanguageModelTierProbabilities\n readonly reasoning?: AgentReasoning\n /** Canonical IANA time zone of the requester. Absent uses the project time zone. */\n readonly timeZone?: string\n /** Canonical BCP 47 language of the requester. Absent uses the project locale. */\n readonly locale?: string\n /** What the turn may change without asking its requester. Absent on older runs: `auto`. */\n readonly approvalMode?: AgentApprovalMode\n /** Its thread's `runsOn` when it was asked for: a computer's turn never reaches the agent queue. */\n readonly runsOn?: \"computer\"\n /**\n * Which computer and folder the turn ran in: captured with `runsOn: \"computer\"` and updated if a\n * queued turn moves to another folder before starting.\n */\n readonly computer?: AgentThreadPlace\n}\n\n/** Immutable, serialisable child configuration captured before dispatch. */\nexport interface SubagentRunSpec {\n readonly model: LanguageModelRef\n /** With tiers, the tier of the model the child runs on. Absent on children admitted before it. */\n readonly tier?: LanguageModelTier\n readonly reasoning?: AgentReasoning\n /** Focused task supplied by the parent Agent. */\n readonly task: string\n /** At most this many steps per run, as its parent asked: the project's limit still applies. */\n readonly maxSteps?: number\n /** Project tools available when the child was admitted. Runtime tools are injected separately. */\n readonly toolNames: readonly string[]\n /** The parent turn's mode, copied when the child was admitted. Absent: `auto`. */\n readonly approvalMode?: AgentApprovalMode\n /** The parent turn's requester settings. Absent uses the project's. */\n readonly timeZone?: string\n readonly locale?: string\n /** Files the parent handed over, copied into the child's sandbox at these paths. */\n readonly files?: readonly SubagentRunFile[]\n}\n\n/** A file a parent and its child hand each other, stored once and copied into a sandbox. */\nexport interface SubagentRunFile {\n /** Relative, `/`-separated, without `.` or `..` segments. */\n readonly path: string\n readonly fileRef: FileRef\n}\n\n/** Durable child output returned to its parent by `wait`. */\nexport interface SubagentRunResult {\n /** Empty only for a child that paused on its held calls before it answered. */\n readonly text: string\n /** What the child wrote under `out/`, by path relative to it. */\n readonly files?: readonly SubagentRunFile[]\n /** Why none of what it wrote under `out/` came back, and what to do about it. */\n readonly filesError?: string\n /**\n * What its parent sent a paused child that it had not read: the run that continues it reads it\n * first.\n */\n readonly unread?: readonly { readonly id: string; readonly text: string }[]\n}\n\nexport interface SubagentRunRecord extends AgentRunRecordBase {\n readonly kind: \"subagent\"\n /** The child's own thread, which holds its task and its work. */\n readonly threadId: string\n /** The message of its thread that started the run. */\n readonly triggerMessageId: string\n /** The conversation turn the child runs under: its mode and cancellation. */\n readonly parentRunId: string\n /** Stable parent-selected key that makes repeated tool execution idempotent. */\n readonly spawnKey: string\n readonly spec: SubagentRunSpec\n readonly result?: SubagentRunResult\n}\n\nexport type AgentRunRecord = ConversationAgentRunRecord | SubagentRunRecord\n\nexport interface CreateAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly threadId: string\n readonly triggerMessageId: string\n readonly spec: ConversationAgentRunSpec\n readonly createdAt?: Date\n}\n\nexport interface CreateSubagentRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly parentRunId: string\n /** Current parent delivery token. New children are admitted only while that delivery owns it. */\n readonly parentExecutionToken: string\n readonly spawnKey: string\n readonly spec: SubagentRunSpec\n /**\n * The child's thread. Its first run creates it, owned by the conversation's owner; a later run\n * goes into it, and is refused while another run of the thread is active.\n */\n readonly thread: { readonly id: string; readonly create: boolean }\n /** The user message that starts the run, appended to the child's thread with the run's id. */\n readonly trigger: Pick<AppendAgentMessageInput, \"id\" | \"parts\" | \"metadata\">\n /** Internal safety bound enforced atomically across worker processes. */\n readonly maxActiveChildren: number\n readonly createdAt?: Date\n}\n\nexport interface StartAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly modelId?: string\n readonly execution: AgentRunExecution\n readonly startedAt?: Date\n /**\n * Start it only as a computer's turn, there and in that folder: one whose thread moved meanwhile\n * is refused with `invalid_state`, so it never starts where its thread no longer runs.\n */\n readonly onComputer?: AgentThreadPlace\n}\n\nexport interface FinishQueuedAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\" | \"cancelled\"\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly completedAt?: Date\n}\n\nexport interface ReclaimAgentRunInput {\n readonly id: string\n readonly projectId: string\n readonly execution: AgentRunExecution\n /**\n * Take the run over only if the lease last recorded on it ran out by then, checked in the same\n * write: a renewal that lands first keeps it its runner's. Otherwise `invalid_state`.\n */\n readonly ifLapsedBy?: Date\n}\n\nexport interface ConfirmAgentRunExecutionOwnershipInput {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n /** Exact expiration returned by the queue claim or its latest successful renewal. */\n readonly queueLeaseExpiresAt: Date\n}\n\nexport interface RequestAgentRunCancelInput {\n readonly id: string\n readonly projectId: string\n readonly at?: Date\n}\n\nexport type FinishAgentRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n readonly status: \"succeeded\"\n readonly modelId?: string\n readonly finishReason?: AgentRunFinishReason\n readonly diagnostics?: readonly AgentRunDiagnostic[]\n readonly result?: SubagentRunResult\n readonly completedAt?: Date\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n readonly status: \"failed\" | \"cancelled\"\n readonly modelId?: string\n /** Only a succeeded run pauses. */\n readonly finishReason?: Exclude<AgentRunFinishReason, \"awaiting_approval\" | \"awaiting_answer\">\n readonly diagnostics?: readonly AgentRunDiagnostic[]\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly completedAt?: Date\n }\n\nexport interface ListAgentRunsInput {\n readonly projectId: string\n readonly kinds?: readonly AgentRunKind[]\n readonly threadId?: string\n readonly parentRunId?: string\n readonly statuses?: readonly AgentRunStatus[]\n /** Effective start time; runs that never started use `createdAt`. */\n readonly startedAfter?: Date\n /** Effective start time; runs that never started use `createdAt`. */\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n /** Leave out the turns that wait for a computer: only a worker's to run. */\n readonly excludeComputerTurns?: boolean\n}\n\nexport interface ListThreadSubagentsInput {\n readonly projectId: string\n /** The conversation whose turns spawned them. */\n readonly threadId: string\n readonly spawnKey?: string\n readonly finishReason?: AgentRunFinishReason\n /** Only children spawned by turns whose trigger message is still in the thread. */\n readonly retainedTurnsOnly?: boolean\n /** At most this many, 100 by default. */\n readonly limit?: number\n}\n\nexport interface ListAgentRunsResult {\n readonly runs: readonly AgentRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface ListLatestAgentRunsInput {\n readonly projectId: string\n readonly threadIds: readonly string[]\n}\n\n// ── agent_messages — one message (assistant messages inserted only once finalized) ─────────────\n\nexport type { AgentMessageRole }\n\nexport interface AgentMessageRecord {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n /**\n * The run that produced this message; `null` for user-authored messages. In a sub-agent's thread\n * every message has one, its trigger too, so a run's messages are deleted whole. A message copied\n * by a fork keeps the run that produced it, which belongs to the thread it was copied from.\n */\n readonly runId: string | null\n readonly role: AgentMessageRole\n /** Principal that authored this persisted message: caller for user messages, agent identity later for assistant messages. */\n readonly authorPrincipal?: Principal\n /** Monotonic per thread, assigned by the store. */\n readonly seq: number\n /** Structured message content — text / reasoning / step boundaries / tool calls. */\n readonly parts: readonly AgentMessagePart[]\n /** Message-level metadata (mirrors `UIMessage.metadata`). */\n readonly metadata?: JsonValue\n /** Versions the `parts` shape so it can be migrated; stamped from `AGENT_MESSAGE_CONTENT_VERSION`. */\n readonly contentVersion: number\n readonly createdAt: Date\n readonly completedAt?: Date\n}\n\n/** Append a message: a {@link AgentMessage} (role + parts + metadata) plus its storage identity. */\nexport interface AppendAgentMessageInput extends AgentMessage {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n readonly runId: string | null\n readonly authorPrincipal?: Principal\n readonly createdAt?: Date\n readonly completedAt?: Date\n}\n\nexport interface DeleteAgentMessagesFromSeqInput {\n readonly projectId: string\n readonly threadId: string\n /** Delete every message whose per-thread sequence is greater than or equal to this boundary. */\n readonly fromSeq: number\n}\n\nexport interface DeleteAgentMessagesByRunInput {\n readonly projectId: string\n readonly threadId: string\n readonly runId: string\n /**\n * The run that deletes them, when one does: refused with `execution_lost` unless it still runs\n * under this token, checked in the same transaction as the delete.\n */\n readonly fence?: { readonly runId: string; readonly executionToken: string }\n}\n\nexport interface ListAgentMessagesInput {\n readonly projectId: string\n readonly threadId: string\n /** Return only messages whose per-thread sequence is greater than this retained boundary. */\n readonly afterSeq?: number\n readonly roles?: readonly AgentMessageRole[]\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListAgentMessagesResult {\n readonly messages: readonly AgentMessageRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n// ── agent_context_checkpoints — append-only model-context boundaries ──────────────────────────\n\nexport type AgentContextCheckpointReason = \"threshold\" | \"overflow\"\n\n/**\n * A durable summary boundary used only when projecting a thread into model context.\n *\n * Checkpoints never replace or mutate transcript messages. Normal thread reads remain authoritative\n * and complete; the worker reads the latest checkpoint and only the retained message tail.\n */\nexport interface AgentContextCheckpointRecord {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n /** A fork's copy keeps the run that wrote the summary, in the thread it was copied from. */\n readonly createdByRunId: string\n readonly previousCheckpointId?: string\n readonly reason: AgentContextCheckpointReason\n readonly summary: string\n readonly summaryFormatVersion: 1\n readonly summarizedThroughSeq: number\n readonly observedHeadSeq: number\n readonly estimatedInputTokensBefore: number\n readonly estimatedInputTokensAfter: number\n readonly summaryModelId: string\n readonly createdAt: Date\n}\n\nexport interface CreateAgentContextCheckpointInput {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n readonly createdByRunId: string\n /** Compare-and-swap anchor. `null` means the thread must not have a prior checkpoint. */\n readonly expectedPreviousCheckpointId: string | null\n /** Compare-and-swap anchor for the complete transcript observed by the summarizer. */\n readonly expectedHeadSeq: number\n /** Current delivery token for `createdByRunId`; stale redeliveries must not write. */\n readonly executionToken: string\n readonly reason: AgentContextCheckpointReason\n readonly summary: string\n readonly summaryFormatVersion: 1\n readonly summarizedThroughSeq: number\n readonly observedHeadSeq: number\n readonly estimatedInputTokensBefore: number\n readonly estimatedInputTokensAfter: number\n readonly summaryModelId: string\n readonly createdAt?: Date\n}\n\n// ── Store ───────────────────────────────────────────────────────────────────────────────────────\n\nexport interface AgentThreadStore {\n /** Atomic run-fenced transition, or explicit idle-thread recreation. */\n transitionSandbox(input: TransitionAgentThreadSandboxInput): Promise<AgentThreadSandboxState>\n create(input: CreateAgentThreadInput): Promise<AgentThreadRecord>\n /**\n * Create a thread holding a copy of another's finished history, in one transaction. The source's\n * sub-agent threads are not copied, and a sub-agent's thread is refused.\n */\n fork(input: ForkAgentThreadInput): Promise<AgentThreadRecord>\n getById(params: { projectId: string; id: string }): Promise<AgentThreadRecord | null>\n /** The threads found, in first-occurrence input order; a missing one is omitted. */\n getByIds(params: {\n readonly projectId: string\n readonly ids: readonly string[]\n }): Promise<readonly AgentThreadRecord[]>\n list(input: ListAgentThreadsInput): Promise<ListAgentThreadsResult>\n /** The sub-agents' threads of a conversation, by creation and id, all of them or one turn's. */\n listChildren(input: ListAgentThreadChildrenInput): Promise<readonly AgentThreadRecord[]>\n /**\n * Add users atomically and return every participant of the thread afterwards. A sub-agent's\n * thread has none: its readers are its conversation's.\n */\n addParticipants(\n input: AddAgentThreadParticipantsInput\n ): Promise<readonly AgentThreadParticipantRecord[]>\n /** Whether the user took part until now. */\n removeParticipant(input: RemoveAgentThreadParticipantInput): Promise<boolean>\n /**\n * Move a conversation thread to a computer and folder, from the cloud or from another computer or\n * folder, and return the thread after. Refused while a turn holds a cloud thread or runs on its\n * computer.\n */\n assignComputer(input: AssignAgentThreadComputerInput): Promise<AgentThreadRecord>\n /**\n * Move a computer's thread to the cloud, in one transaction with its queued turn, which the cloud\n * runs instead. Refused with `active_run_exists` while a turn runs on the computer, and\n * `invalid_input` for a thread already in the cloud.\n */\n moveToCloud(input: MoveAgentThreadToCloudInput): Promise<MoveAgentThreadToCloudResult>\n /** The participants of these threads, oldest first, then by user id and thread id. */\n listParticipants(\n input: ListAgentThreadParticipantsInput\n ): Promise<readonly AgentThreadParticipantRecord[]>\n}\n\nexport interface AgentRunStore {\n /**\n * Persist a queued turn and atomically claim the thread's single-flight slot. A sub-agent's\n * thread takes only child runs.\n */\n create(input: CreateAgentRunInput): Promise<ConversationAgentRunRecord>\n /**\n * Persist or replay one idempotent child run while atomically enforcing parent fan-out. In one\n * transaction it creates the child's thread or takes it (single-flight, as a conversation), then\n * appends the trigger and the run.\n */\n createSubagent(input: CreateSubagentRunInput): Promise<SubagentRunRecord>\n /** Transition a queued run to running and install the first delivery's execution token. */\n start(input: StartAgentRunInput): Promise<AgentRunRecord>\n /** Finish a queued run before execution and release the thread's single-flight slot. */\n finishQueued(input: FinishQueuedAgentRunInput): Promise<AgentRunRecord>\n /** Rotate the execution token for a redelivered running job (`attempt++`). */\n reclaim(input: ReclaimAgentRunInput): Promise<AgentRunRecord>\n /**\n * Project the queue's latest confirmed ownership expiration onto the current execution.\n * Implementations must fence by token and must never move the expiration backwards.\n */\n confirmExecutionOwnership(input: ConfirmAgentRunExecutionOwnershipInput): Promise<AgentRunRecord>\n /**\n * Record that a running run was asked to stop, keeping the first time it was. A run in any other\n * state is returned as it is: a queued one is cancelled with `finishQueued`.\n */\n requestCancel(input: RequestAgentRunCancelInput): Promise<AgentRunRecord>\n /**\n * Finalize a run and release the thread's `activeRunId`. `finishReason: \"awaiting_approval\"`\n * needs a call the run holds (see `approvals.holdsRun`). A turn that ends any other way cancels\n * its pending approvals and stops resuming on the rest; a child that fails or is cancelled\n * cancels its own pending ones.\n */\n finish(input: FinishAgentRunInput): Promise<AgentRunRecord>\n getById(params: { projectId: string; id: string }): Promise<AgentRunRecord | null>\n getByIds(params: {\n projectId: string\n ids: readonly string[]\n }): Promise<readonly AgentRunRecord[]>\n /**\n * The children of a conversation's turns, the latest turn's first, by its effective start, and\n * within a turn the latest admitted first. Read by key (one per turn) or by finish reason.\n */\n listThreadSubagents(input: ListThreadSubagentsInput): Promise<readonly SubagentRunRecord[]>\n /** The newest run of each thread, by creation and id; a thread without one is absent. */\n latestByThread(input: ListLatestAgentRunsInput): Promise<readonly AgentRunRecord[]>\n list(input: ListAgentRunsInput): Promise<ListAgentRunsResult>\n}\n\nexport interface AgentMessageStore {\n /** Insert a message (its `parts` are the canonical content) and bump thread stats. */\n append(input: AppendAgentMessageInput): Promise<AgentMessageRecord>\n /**\n * Delete every message produced by one run and repair the thread's message stats. A reader's\n * place past the newest message left comes back to it: the next message reuses those numbers.\n */\n deleteByRunId(input: DeleteAgentMessagesByRunInput): Promise<number>\n /**\n * Delete every message at or after `fromSeq` and repair the thread's message stats. A reader's\n * place past the newest message left comes back to it: the edit that follows reuses the numbers.\n */\n deleteFromSeq(input: DeleteAgentMessagesFromSeqInput): Promise<number>\n getById(params: { projectId: string; id: string }): Promise<AgentMessageRecord | null>\n list(input: ListAgentMessagesInput): Promise<ListAgentMessagesResult>\n}\n\nexport interface DeleteAgentContextCheckpointsAfterSeqInput {\n readonly projectId: string\n readonly threadId: string\n /** Delete checkpoints whose observed head exceeds this retained sequence boundary. */\n readonly afterSeq: number\n}\n\nexport interface AgentContextCheckpointStore {\n /**\n * Append one checkpoint after atomically validating run ownership and both transcript anchors.\n * Repeating the same payload for the same creating run is idempotent.\n */\n create(input: CreateAgentContextCheckpointInput): Promise<AgentContextCheckpointRecord>\n /** The thread's checkpoints created by the requested runs, in first-occurrence input order. */\n getByRunIds(input: {\n readonly projectId: string\n readonly threadId: string\n readonly runIds: readonly string[]\n }): Promise<readonly AgentContextCheckpointRecord[]>\n getLatest(input: {\n readonly projectId: string\n readonly threadId: string\n }): Promise<AgentContextCheckpointRecord | null>\n /** Delete checkpoints that observed messages past `afterSeq`, newest first. */\n deleteAfterSeq(input: DeleteAgentContextCheckpointsAfterSeqInput): Promise<number>\n}\n\n// ── agent_approvals — calls of the Agent that wait for whoever asked ───────────────────────────\n\n/**\n * What the Agent may change without asking its requester: `manual` asks for every action and\n * workflow, `accept-edits` runs the actions that only change Sixb, `auto` runs everything.\n */\nexport const AGENT_APPROVAL_MODES = [\"manual\", \"accept-edits\", \"auto\"] as const\n\nexport type AgentApprovalMode = (typeof AGENT_APPROVAL_MODES)[number]\n\n/** The modes that hold some calls: the one that held a call is recorded on its approval. */\nexport const AGENT_HOLDING_APPROVAL_MODES = [\n \"manual\",\n \"accept-edits\",\n] as const satisfies readonly AgentApprovalMode[]\n\nexport type AgentHoldingApprovalMode = (typeof AGENT_HOLDING_APPROVAL_MODES)[number]\n\nexport const AGENT_APPROVAL_STATUSES = [\n \"pending\",\n \"approved\",\n \"denied\",\n \"cancelled\",\n \"superseded\",\n \"expired\",\n] as const\n\nexport type AgentApprovalStatus = (typeof AGENT_APPROVAL_STATUSES)[number]\n\n/** The statuses a pending approval is settled to without a decision. */\nexport type AgentApprovalSettledStatus = Extract<\n AgentApprovalStatus,\n \"cancelled\" | \"superseded\" | \"expired\"\n>\n\n/**\n * The held call, as it runs once approved. An action's params are normalized: what the user\n * approves is exactly what runs. Its run id is the one the Agent named, so a repeated request finds\n * the same approval and the same run.\n */\nexport type AgentApprovalCall =\n | {\n readonly kind: \"action\"\n readonly actionId: string\n readonly subject: ActionSubject\n readonly params: ActionRunParams\n readonly actionRunId: string\n /** `external` when the action has a writeback or effects: it reaches beyond Sixb. */\n readonly effect: \"ontology\" | \"external\"\n }\n | {\n readonly kind: \"workflow\"\n readonly workflowId: string\n readonly input: JsonObject\n readonly workflowRunId: string\n }\n\n/** What running an approved call gave. */\nexport type AgentApprovalOutcome =\n | {\n readonly kind: \"action-run\"\n readonly runId: string\n readonly status: \"succeeded\" | \"failed\"\n readonly error?: ActionRunFailure\n }\n | { readonly kind: \"workflow-run\"; readonly runId: string; readonly queuedAt: string }\n /** The call was refused when it ran, for example because its requester lost a grant. */\n | { readonly kind: \"error\"; readonly error: SixbFailure }\n\nexport interface AgentApprovalRecord {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n /** The conversation turn the call belongs to. */\n readonly runId: string\n /** The run that made the call: the turn itself, or one of its children. */\n readonly callerRunId: string\n /** Who asked for the turn: the only one who decides, as the call runs with their rights. */\n readonly requestedBy: Principal\n /** The mode that held the call. */\n readonly mode: AgentHoldingApprovalMode\n /** The call's run id, unique among a thread's pending, approved and denied approvals. */\n readonly callKey: string\n readonly call: AgentApprovalCall\n readonly status: AgentApprovalStatus\n readonly createdAt: Date\n readonly expiresAt: Date\n readonly decidedAt?: Date\n readonly decidedBy?: Principal\n /** Set once an approved call ran. */\n readonly outcome?: AgentApprovalOutcome\n /** The user message that told the model how the approval ended. */\n readonly reportedInMessageId?: string\n /** \"Always allow\": the mode its requester raised the turn's calls to when deciding this one. */\n readonly raisedMode?: AgentApprovalMode\n /**\n * The turn will not resume for it: stopped, its requester left, or another of its calls was set\n * aside. The thread's next message still reports it.\n */\n readonly turnStoppedAt?: Date\n /** When a process last took the approved call to run it; a stale claim can be taken again. */\n readonly executionClaimedAt?: Date\n}\n\nexport interface RequestAgentApprovalInput {\n readonly id: string\n readonly projectId: string\n readonly runId: string\n readonly callerRunId: string\n /** The caller run's current delivery token: a stale delivery holds nothing. */\n readonly executionToken: string\n readonly requestedBy: Principal\n readonly mode: AgentHoldingApprovalMode\n readonly call: AgentApprovalCall\n readonly createdAt?: Date\n readonly expiresAt: Date\n}\n\nexport interface RequestAgentApprovalResult {\n readonly approval: AgentApprovalRecord\n /** `false` when a pending, approved or denied approval of the thread had the same call key. */\n readonly created: boolean\n}\n\nexport interface DecideAgentApprovalInput {\n readonly projectId: string\n readonly id: string\n readonly decision: \"approved\" | \"denied\"\n readonly decidedBy: Principal\n readonly decidedAt?: Date\n /** With `approved`: \"Always allow\" raised the turn's mode to this one. */\n readonly raisedMode?: AgentApprovalMode\n}\n\nexport interface DecideAgentApprovalResult {\n /** The approval afterwards: `expired` when its time ran out before this decision. */\n readonly approval: AgentApprovalRecord\n /** Whether this call moved it out of `pending` with the decision. */\n readonly decided: boolean\n}\n\nexport interface SettleAgentApprovalsInput {\n readonly projectId: string\n readonly threadId: string\n readonly status: AgentApprovalSettledStatus\n}\n\n/** Stop a thread's turn, or a requester's turns there, from resuming on their calls. */\nexport interface StopAgentApprovalsInput {\n readonly projectId: string\n readonly threadId: string\n /** Only the calls of this conversation turn. */\n readonly runId?: string\n /** Only the calls this principal asked for. */\n readonly requestedBy?: Principal\n readonly stoppedAt?: Date\n}\n\nexport interface StopAgentApprovalsResult {\n /** The pending approvals it cancelled. */\n readonly cancelled: readonly AgentApprovalRecord[]\n /** How many unreported approvals it stopped, the cancelled ones included. */\n readonly stopped: number\n}\n\nexport interface RewindAgentApprovalsInput {\n readonly projectId: string\n readonly threadId: string\n /** Conversation runs removed from the thread: their approvals leave with them. */\n readonly runIds: readonly string[]\n /**\n * Message ids removed by the rewind: an earlier turn's approval reported in one becomes\n * unreported again so the replacement message carries its outcome.\n */\n readonly clearedMessageIds?: readonly string[]\n readonly cancelledAt?: Date\n}\n\nexport interface RewindAgentApprovalsResult {\n /** Pending approvals of the rewound runs, as `cancelled` records to announce. */\n readonly cancelled: readonly AgentApprovalRecord[]\n /** Total approvals deleted for the rewound runs. */\n readonly deleted: number\n}\n\n/** Where a keyset listing resumes: after this approval, in the order approvals are listed. */\nexport interface AgentApprovalCursor {\n readonly createdAt: Date\n readonly id: string\n}\n\nexport interface MarkAgentApprovalsReportedInput {\n readonly projectId: string\n readonly threadId: string\n readonly ids: readonly string[]\n readonly messageId: string\n /** A resume: an approval whose turn was stopped is not marked. */\n readonly resuming?: boolean\n}\n\nexport interface ListAgentApprovalsInput {\n readonly projectId: string\n readonly threadId?: string\n readonly runId?: string\n readonly requestedBy?: Principal\n readonly statuses?: readonly AgentApprovalStatus[]\n /** `false`: only the approvals no message reported yet. */\n readonly reported?: boolean\n readonly limit?: number\n readonly offset?: number\n}\n\nexport interface ListAgentApprovalsResult {\n /** Oldest first. */\n readonly approvals: readonly AgentApprovalRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n/**\n * Held calls and their decisions. `runs.finish` settles a run's approvals in its own transaction:\n * a turn that pauses keeps them for their decision, any other ending cancels its pending ones.\n */\nexport interface AgentApprovalStore {\n /**\n * Fenced like a checkpoint: the caller run is running with `executionToken`, and is the\n * conversation turn `runId` or one of its children. Returns the thread's pending, approved or\n * denied approval with the same call key when there is one, and creates one otherwise.\n */\n request(input: RequestAgentApprovalInput): Promise<RequestAgentApprovalResult>\n /** Compare-and-swap from `pending`; `null` when no such approval exists. */\n decide(input: DecideAgentApprovalInput): Promise<DecideAgentApprovalResult | null>\n /** Record what an approved call gave, once: an approval with an outcome is returned unchanged. */\n recordOutcome(input: {\n readonly projectId: string\n readonly id: string\n readonly outcome: AgentApprovalOutcome\n }): Promise<AgentApprovalRecord>\n /** Settle the thread's pending approvals, and return the ones it settled. */\n settle(input: SettleAgentApprovalsInput): Promise<readonly AgentApprovalRecord[]>\n /** Expire the project's pending approvals whose time ran out by `now`, and return them. */\n expireDue(input: {\n readonly projectId: string\n readonly now: Date\n readonly limit?: number\n }): Promise<readonly AgentApprovalRecord[]>\n /**\n * Cancel the matching pending approvals and mark every matching one no message reported yet as\n * stopped: their turn never resumes on them.\n */\n stop(input: StopAgentApprovalsInput): Promise<StopAgentApprovalsResult>\n /**\n * Remove approvals belonging to rewound turns and unmark earlier turns' approvals whose\n * reporting message was removed.\n */\n rewind(input: RewindAgentApprovalsInput): Promise<RewindAgentApprovalsResult>\n /** Mark the ones no message reported yet, and return their ids. */\n markReported(input: MarkAgentApprovalsReportedInput): Promise<readonly string[]>\n /**\n * Whether the run holds a call: one of its approvals, or one it made for its turn, pending, or\n * decided and not reported yet. `runs.finish` checks the same before `awaiting_approval`.\n */\n holdsRun(input: { readonly projectId: string; readonly runId: string }): Promise<boolean>\n /**\n * Take an approved call without an outcome to run it, unless another process took it after\n * `staleBefore`; its decision is its first claim. `null` when it is not there to take.\n */\n claimExecution(input: {\n readonly projectId: string\n readonly id: string\n readonly claimedAt: Date\n readonly staleBefore: Date\n }): Promise<AgentApprovalRecord | null>\n /**\n * What a repair pass works on, oldest first: approved calls without an outcome whose claim is\n * older than `claimableBefore`, and decided calls no message reported whose turn is not stopped.\n */\n listRepairable(input: {\n readonly projectId: string\n readonly claimableBefore: Date\n readonly after?: AgentApprovalCursor\n readonly limit: number\n }): Promise<readonly AgentApprovalRecord[]>\n getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<AgentApprovalRecord | null>\n list(input: ListAgentApprovalsInput): Promise<ListAgentApprovalsResult>\n}\n\n/** Each user's approval mode: a default, and their own choice in each thread. */\nexport interface AgentApprovalModeStore {\n getDefault(input: {\n readonly projectId: string\n readonly principal: Principal\n }): Promise<AgentApprovalMode | null>\n setDefault(input: {\n readonly projectId: string\n readonly principal: Principal\n readonly mode: AgentApprovalMode\n readonly updatedAt?: Date\n }): Promise<void>\n getForThread(input: {\n readonly projectId: string\n readonly threadId: string\n readonly principal: Principal\n }): Promise<AgentApprovalMode | null>\n /**\n * `null` clears the choice: the user's turns in the thread follow their default again. Throws\n * `thread_not_found` when the thread does not exist.\n */\n setForThread(input: {\n readonly projectId: string\n readonly threadId: string\n readonly principal: Principal\n readonly mode: AgentApprovalMode | null\n readonly updatedAt?: Date\n }): Promise<void>\n}\n\n// ── Memory ──────────────────────────────────────────────────────────────────────────────────────\n\n/** One file of a memory repo, at its path from the repo root. */\nexport interface AgentMemoryFile {\n readonly path: string\n readonly contents: string\n}\n\n/** A memory repo as of its latest revision. */\nexport interface AgentMemoryRepoRecord {\n /** 0 before the first save. */\n readonly revision: number\n /** Ordered by path. */\n readonly files: readonly AgentMemoryFile[]\n}\n\n/** One change of a save: the file's new contents, or `null` to delete it. */\nexport interface AgentMemoryChange {\n readonly path: string\n readonly contents: string | null\n}\n\nexport interface SaveAgentMemoryInput {\n readonly projectId: string\n /** `user:<userId>` or `project`. */\n readonly repoId: string\n /** The revision the caller loaded. */\n readonly baseRevision: number\n readonly message: string\n readonly author: Principal\n /** The conversation the save came from, `/agents/<threadId>`. */\n readonly source?: string\n readonly changes: readonly AgentMemoryChange[]\n readonly createdAt?: Date\n}\n\nexport type SaveAgentMemoryResult =\n | { readonly saved: true; readonly revision: number }\n | {\n readonly saved: false\n /** The repo's latest revision. */\n readonly revision: number\n /** Files in `changes` that another save changed after `baseRevision`, as they are now. */\n readonly conflicts: readonly AgentMemoryChange[]\n }\n\n/** One save: who made it, why, and which paths it wrote. A revision never changes. */\nexport interface AgentMemoryRevisionRecord {\n readonly revision: number\n readonly message: string\n readonly author: Principal\n readonly source?: string\n /** Ordered by path. */\n readonly changes: readonly { readonly path: string; readonly deleted: boolean }[]\n readonly createdAt: Date\n}\n\nexport interface ListAgentMemoryRevisionsInput {\n readonly projectId: string\n readonly repoId: string\n readonly limit?: number\n readonly offset?: number\n}\n\nexport interface ListAgentMemoryRevisionsResult {\n /** Newest first. */\n readonly revisions: readonly AgentMemoryRevisionRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\n/**\n * Memory repos as append-only revisions: a save inserts one revision and the files it wrote, and\n * never updates a row. Paths, sizes and who may save are decided in Core before a call reaches\n * storage.\n */\nexport interface AgentMemoryStore {\n /**\n * The repo at its latest revision, or with `asOf` at the latest revision saved by then, and with\n * `revision` at the latest up to that one: revision 0 and no files when none was. File versions\n * pruned from the history are missing from it.\n */\n get(input: {\n readonly projectId: string\n readonly repoId: string\n readonly asOf?: Date\n readonly revision?: number\n }): Promise<AgentMemoryRepoRecord>\n /**\n * In one transaction: reports a conflict when a path in `changes` was written after\n * `baseRevision`, or when the repo is behind `baseRevision` because it was deleted; otherwise\n * stores the next revision. The same transaction removes file versions older than\n * {@link AGENT_MEMORY_HISTORY_DAYS} days that are not their path's latest.\n */\n save(input: SaveAgentMemoryInput): Promise<SaveAgentMemoryResult>\n listRevisions(input: ListAgentMemoryRevisionsInput): Promise<ListAgentMemoryRevisionsResult>\n /** Deletes the repo with its history. */\n delete(input: { readonly projectId: string; readonly repoId: string }): Promise<void>\n}\n\n/** How long a file version that is not its path's latest stays in a repo's history. */\nexport const AGENT_MEMORY_HISTORY_DAYS = 90\n\n/** Each open `sixb` on its owner's computers, as a lease it renews. */\nexport interface AgentComputerSessionStore {\n /**\n * Open the session, or renew it until `expiresAt`; its computer, folder and background commands\n * are kept as given, and its stop requests as they are.\n */\n hold(input: Omit<AgentComputerSessionRecord, \"stopRequests\">): Promise<void>\n /**\n * Record that someone asked to stop one of its commands, once, keeping the newest\n * {@link AGENT_COMPUTER_BACKGROUND_COMMANDS_MAX}. Null when the owner holds no such session.\n */\n requestStop(input: {\n readonly projectId: string\n readonly id: string\n readonly ownerPrincipal: Principal\n readonly command: AgentBackgroundCommandRef\n }): Promise<AgentComputerSessionRecord | null>\n /** End the owner's session; null when it is not open. */\n release(input: {\n readonly projectId: string\n readonly id: string\n readonly ownerPrincipal: Principal\n }): Promise<AgentComputerSessionRecord | null>\n /** The owner's sessions live at `now`. */\n listLive(input: {\n readonly projectId: string\n readonly ownerPrincipal: Principal\n readonly now: Date\n }): Promise<readonly AgentComputerSessionRecord[]>\n /** Remove every session that lapsed before `now`, and return them. */\n removeLapsed(input: {\n readonly projectId: string\n readonly now: Date\n }): Promise<readonly AgentComputerSessionRecord[]>\n}\n\n// ── agent_token_rates — what each model's tokenizer measured on the project's agent runs ──────\n\n/** How many measurements a project keeps per model: its newest. */\nexport const AGENT_TOKEN_RATE_SAMPLES = 20\n\n/**\n * The band of bytes per token a measurement may show. Every tokenizer measured on agent turns\n * reads 2.1 to 4.7; a value outside is a broken measurement, and a single one would set its\n * model's rate for the whole project.\n */\nexport const AGENT_TOKEN_RATE_MIN_BYTES_PER_TOKEN = 1\nexport const AGENT_TOKEN_RATE_MAX_BYTES_PER_TOKEN = 8\n\n/**\n * One run's measurement of its model's tokenizer: the UTF-8 bytes of a request's text, as the\n * Agent's context estimator weighs them, against the text tokens the provider counted for it.\n */\nexport interface AgentTokenRateRecord {\n readonly projectId: string\n readonly providerId: string\n readonly modelId: string\n /** The agent run or workflow step that measured it: one measurement each. */\n readonly runId: string\n readonly bytes: number\n readonly tokens: number\n readonly measuredAt: Date\n}\n\n/**\n * The newest measurements of each model's bytes per token, per project. Agent runs start their\n * context estimate from them; losing them only makes the next estimates more conservative.\n */\nexport interface AgentTokenRateStore {\n /**\n * Keep a run's measurement, in place of one it recorded before, and drop the model's\n * measurements past its newest {@link AGENT_TOKEN_RATE_SAMPLES}.\n */\n record(input: AgentTokenRateRecord): Promise<void>\n /** The model's measurements, newest first: at most {@link AGENT_TOKEN_RATE_SAMPLES}. */\n listLatest(input: {\n readonly projectId: string\n readonly providerId: string\n readonly modelId: string\n }): Promise<readonly AgentTokenRateRecord[]>\n}\n\n// -- agent_thread_inbox: mid-run steers and queued follow-up messages -------------------------\n\nexport const AGENT_INBOX_MODES = [\"steer\", \"queue\"] as const\nexport type AgentInboxMode = (typeof AGENT_INBOX_MODES)[number]\n\n/** Maximum pending items one conversation thread holds in its inbox at once. */\nexport const AGENT_THREAD_INBOX_MAX_ITEMS = 50\n\n/** Optional per-turn overrides carried by a queued or immediate inbox item. */\nexport interface AgentInboxSpec {\n readonly model?: LanguageModelRef\n readonly reasoning?: AgentReasoning\n readonly approvalMode?: AgentApprovalMode\n}\n\n/** Claim recorded when a running conversation turn drains a `steer` item at a step boundary. */\nexport interface AgentInboxClaim {\n readonly runId: string\n readonly executionToken: string\n readonly stepIndex: number\n readonly afterAnswer?: boolean\n}\n\nexport interface AgentInboxItemRecord {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n /** Stable id reserved for `agent_messages` once this item is delivered. */\n readonly messageId: string\n readonly seq: number\n readonly authorPrincipal: Principal\n readonly mode: AgentInboxMode\n readonly parts: readonly AgentMessagePart[]\n readonly spec?: AgentInboxSpec\n readonly timeZone?: string\n readonly locale?: string\n /** Marked by Send now so `afterAgentRunFinished` dispatches it across a user cancel. */\n readonly immediate?: boolean\n /**\n * An edit waiting for the turn it stopped to end: the earlier message it replaces. When it\n * starts, the thread first rewinds to that message. Always sent now, as a queued message.\n */\n readonly replacesMessageId?: string\n /**\n * The execution of the request that sent it. A turn that starts it without a request of its\n * sender's runs as a child of this one, with the sender's grants as they are then.\n */\n readonly executionId?: string\n readonly claimedBy?: AgentInboxClaim\n readonly createdAt: Date\n readonly updatedAt: Date\n}\n\nexport interface EnqueueAgentInboxItemInput {\n readonly id: string\n readonly projectId: string\n readonly threadId: string\n readonly messageId: string\n readonly authorPrincipal: Principal\n readonly mode: AgentInboxMode\n readonly parts: readonly AgentMessagePart[]\n readonly spec?: AgentInboxSpec\n readonly timeZone?: string\n readonly locale?: string\n readonly immediate?: boolean\n /**\n * An edit waiting for the turn it stopped to end: the earlier message it replaces. When it\n * starts, the thread first rewinds to that message. Always sent now, as a queued message.\n */\n readonly replacesMessageId?: string\n readonly executionId?: string\n readonly createdAt?: Date\n}\n\nexport interface EnqueueAgentInboxItemResult {\n readonly item: AgentInboxItemRecord\n readonly created: boolean\n}\n\nexport interface ListAgentInboxItemsInput {\n readonly projectId: string\n readonly threadId: string\n /** Whether items already claimed by a running step are included; defaults to `true`. */\n readonly includeClaimed?: boolean\n}\n\nexport interface UpdateAgentInboxItemInput {\n readonly projectId: string\n readonly threadId: string\n readonly id: string\n readonly mode?: AgentInboxMode\n readonly parts?: readonly AgentMessagePart[]\n readonly spec?: AgentInboxSpec | null\n readonly immediate?: boolean\n readonly updatedAt?: Date\n}\n\nexport interface RemoveAgentInboxItemInput {\n readonly projectId: string\n readonly threadId: string\n readonly id: string\n}\n\nexport interface TakeAgentInboxSteersInput {\n readonly projectId: string\n readonly threadId: string\n readonly runId: string\n readonly executionToken: string\n readonly stepIndex: number\n readonly afterAnswer?: boolean\n /**\n * The run's requester: a turn runs as them, so it reads only the steers they sent. Another\n * participant's steer waits for a turn of theirs.\n */\n readonly authorPrincipal: Principal\n}\n\nexport interface ConsumeClaimedAgentInboxInput {\n readonly projectId: string\n readonly threadId: string\n readonly runId: string\n readonly executionToken: string\n /** Message ids persisted into `agent_messages`; other claims of this run are released. */\n readonly messageIds: readonly string[]\n}\n\nexport interface TakeNextQueuedAgentInboxInput {\n readonly projectId: string\n readonly threadId: string\n /** When `true`, only an item marked `immediate` is popped (used after a user cancel). */\n readonly onlyImmediate?: boolean\n /**\n * Only an item this person sent: a turn runs as its requester, so it starts the messages they\n * sent, and another participant's waits for a turn of theirs.\n */\n readonly authorPrincipal?: Principal\n}\n\nexport interface ListWaitingAgentInboxThreadsInput {\n readonly projectId: string\n /** Only threads holding an item created before this: newer ones a turn's end is still starting. */\n readonly createdBefore: Date\n /** Page after this thread id, in id order. */\n readonly afterThreadId?: string\n readonly limit: number\n}\n\nexport interface AgentInboxStore {\n enqueue(input: EnqueueAgentInboxItemInput): Promise<EnqueueAgentInboxItemResult>\n getById(params: { projectId: string; id: string }): Promise<AgentInboxItemRecord | null>\n list(input: ListAgentInboxItemsInput): Promise<readonly AgentInboxItemRecord[]>\n /** Update an unclaimed inbox item; throws `invalid_state` when already claimed. */\n update(input: UpdateAgentInboxItemInput): Promise<AgentInboxItemRecord | null>\n /** Remove an unclaimed inbox item; throws `invalid_state` when already claimed. */\n remove(input: RemoveAgentInboxItemInput): Promise<AgentInboxItemRecord | null>\n /**\n * Fenced by `(runId, executionToken)`: claim the non-immediate steers `authorPrincipal` sent, in\n * FIFO order. The thread's running turn holds it, so a claim any other execution left behind (one\n * this run replaced, or a turn whose release failed) was never written, and is taken over.\n */\n takeSteers(input: TakeAgentInboxSteersInput): Promise<readonly AgentInboxItemRecord[]>\n /** Consume persisted claims of `(runId, executionToken)` and release any unwritten ones. */\n consumeClaimed(input: ConsumeClaimedAgentInboxInput): Promise<readonly AgentInboxItemRecord[]>\n /** Release remaining claims held by `runId` after an interrupted, failed, or cancelled turn. */\n releaseClaimed(input: { projectId: string; runId: string }): Promise<number>\n /** Pop the next unclaimed item when `thread.activeRunId` is null; null when busy or empty. */\n takeNextQueued(input: TakeNextQueuedAgentInboxInput): Promise<AgentInboxItemRecord | null>\n /** Ids of threads no turn holds whose inbox still holds an item, for the repair pass. */\n listWaitingThreads(input: ListWaitingAgentInboxThreadsInput): Promise<readonly string[]>\n}\n\nexport interface AgentStorage {\n readonly threads: AgentThreadStore\n readonly reads: AgentThreadReadStore\n readonly runs: AgentRunStore\n readonly messages: AgentMessageStore\n readonly checkpoints: AgentContextCheckpointStore\n readonly memory: AgentMemoryStore\n readonly approvals: AgentApprovalStore\n readonly approvalModes: AgentApprovalModeStore\n readonly computers: AgentComputerSessionStore\n readonly tokenRates: AgentTokenRateStore\n readonly inbox: AgentInboxStore\n}\n"
6
6
  ],
7
- "mappings": ";;AAgRO,IAAM,0CAAyC;AA6C/C,IAAM,2BAA0B;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAYO,IAAM,4BAA2B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAQO,SAAS,2BAA0B,CACxC,OACkC;AAAA,EAClC,IAAI,UAAU,QAAQ,UAAU,WAAW;AAAA,IACzC;AAAA,EACF;AAAA,EACA,OAAQ,0BAA+C,SAAS,KAAK,IAChE,QACD;AAAA;AAIC,IAAM,8BAA6B,CAAC,sBAAsB,sBAAsB;AA8gBhF,IAAM,wBAAuB,CAAC,UAAU,gBAAgB,MAAM;AAK9D,IAAM,gCAA+B;AAAA,EAC1C;AAAA,EACA;AACF;AAIO,IAAM,2BAA0B;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAmXO,IAAM,4BAA4B;AAyClC,IAAM,4BAA2B;AAOjC,IAAM,wCAAuC;AAC7C,IAAM,uCAAuC;AAqC7C,IAAM,qBAAoB,CAAC,SAAS,OAAO;AAI3C,IAAM,gCAA+B;",
7
+ "mappings": ";;AAgRO,IAAM,0CAAyC;AAmH/C,IAAM,2BAA0B;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAYO,IAAM,4BAA2B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,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