@sixb/core 0.2.5 → 0.2.7

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 (427) 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 +3 -3
  9. package/dist/agents/index.d.ts.map +1 -1
  10. package/dist/agents/index.js +53 -45
  11. package/dist/agents/index.js.map +1 -1
  12. package/dist/agents/model-routing.d.ts +16 -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-token.d.ts +6 -0
  20. package/dist/agents/run-token.d.ts.map +1 -1
  21. package/dist/agents/run-turn.d.ts +9 -1
  22. package/dist/agents/run-turn.d.ts.map +1 -1
  23. package/dist/agents/streams/index.d.ts +1 -1
  24. package/dist/agents/streams/index.d.ts.map +1 -1
  25. package/dist/agents/streams/index.js +1 -1
  26. package/dist/agents/streams/internal.d.ts +2 -1
  27. package/dist/agents/streams/internal.d.ts.map +1 -1
  28. package/dist/agents/streams/internal.js +22 -2
  29. package/dist/agents/streams/internal.js.map +1 -1
  30. package/dist/agents/streams/protocol.d.ts +37 -0
  31. package/dist/agents/streams/protocol.d.ts.map +1 -1
  32. package/dist/agents/streams/steps.d.ts +24 -0
  33. package/dist/agents/streams/steps.d.ts.map +1 -0
  34. package/dist/agents/thread-access.d.ts +44 -2
  35. package/dist/agents/thread-access.d.ts.map +1 -1
  36. package/dist/artifacts/live/server.js +19 -18
  37. package/dist/artifacts/live/server.js.map +1 -1
  38. package/dist/artifacts/publish/index.js +18 -17
  39. package/dist/artifacts/publish/index.js.map +1 -1
  40. package/dist/artifacts/publish/merge.d.ts +2 -1
  41. package/dist/artifacts/publish/merge.d.ts.map +1 -1
  42. package/dist/artifacts/run-query.d.ts.map +1 -1
  43. package/dist/auth/index.js +6 -6
  44. package/dist/authorization/index.js +2 -2
  45. package/dist/bootstrap/discovery.d.ts +6 -0
  46. package/dist/bootstrap/discovery.d.ts.map +1 -1
  47. package/dist/bootstrap/index.js +40 -38
  48. package/dist/bootstrap/index.js.map +2 -2
  49. package/dist/calendar.d.ts +55 -0
  50. package/dist/calendar.d.ts.map +1 -0
  51. package/dist/calendar.js +19 -0
  52. package/dist/calendar.js.map +9 -0
  53. package/dist/chunk-04r2fdsd.js +386 -0
  54. package/dist/chunk-04r2fdsd.js.map +14 -0
  55. package/dist/{chunk-gjhrz66x.js → chunk-06kpaqg4.js} +248 -21
  56. package/dist/{chunk-gjhrz66x.js.map → chunk-06kpaqg4.js.map} +6 -6
  57. package/dist/{chunk-5a4a52tq.js → chunk-0pmpwn3g.js} +18 -2
  58. package/dist/chunk-0pmpwn3g.js.map +10 -0
  59. package/dist/{chunk-nxysqbt0.js → chunk-389ybvw9.js} +6 -2
  60. package/dist/chunk-389ybvw9.js.map +10 -0
  61. package/dist/{chunk-xcrnrpfh.js → chunk-394zjzjs.js} +20 -10
  62. package/dist/{chunk-xcrnrpfh.js.map → chunk-394zjzjs.js.map} +5 -5
  63. package/dist/{chunk-stmxh0hv.js → chunk-3neam1y5.js} +2 -2
  64. package/dist/{chunk-zeykm8my.js → chunk-3qtk0070.js} +16 -42
  65. package/dist/chunk-3qtk0070.js.map +14 -0
  66. package/dist/{chunk-0hkdtwqk.js → chunk-44hrfmbk.js} +5 -5
  67. package/dist/{chunk-ey1p8w68.js → chunk-5pz3htbe.js} +86 -5
  68. package/dist/chunk-5pz3htbe.js.map +13 -0
  69. package/dist/{chunk-s5pj68fa.js → chunk-5sswe5ej.js} +2 -2
  70. package/dist/{chunk-k3jh8gsg.js → chunk-5xkqasvn.js} +21 -4
  71. package/dist/chunk-5xkqasvn.js.map +10 -0
  72. package/dist/{chunk-5t9gm5tt.js → chunk-6md802cc.js} +38 -14
  73. package/dist/chunk-6md802cc.js.map +22 -0
  74. package/dist/{chunk-3zagkr6w.js → chunk-7mhbs9yy.js} +4 -4
  75. package/dist/{chunk-3zagkr6w.js.map → chunk-7mhbs9yy.js.map} +1 -1
  76. package/dist/{chunk-ewqn51gr.js → chunk-88xeh6zx.js} +6 -4
  77. package/dist/{chunk-ewqn51gr.js.map → chunk-88xeh6zx.js.map} +4 -4
  78. package/dist/{chunk-z1njfqqs.js → chunk-8qmp9fpa.js} +783 -171
  79. package/dist/{chunk-z1njfqqs.js.map → chunk-8qmp9fpa.js.map} +13 -13
  80. package/dist/{chunk-r2psmn42.js → chunk-95ps0k5q.js} +3 -3
  81. package/dist/{chunk-r2psmn42.js.map → chunk-95ps0k5q.js.map} +3 -3
  82. package/dist/{chunk-fpf57gca.js → chunk-9cyq87qa.js} +276 -68
  83. package/dist/{chunk-fpf57gca.js.map → chunk-9cyq87qa.js.map} +6 -6
  84. package/dist/{chunk-q9nkpr8k.js → chunk-9tpmfh3n.js} +1 -1
  85. package/dist/chunk-9wr3yajk.js.map +2 -2
  86. package/dist/{chunk-naxjka9v.js → chunk-brhp9d97.js} +2 -2
  87. package/dist/{chunk-8a8k38tz.js → chunk-brybqw5k.js} +1 -1
  88. package/dist/{chunk-vehcr9eb.js → chunk-cg7cygfj.js} +1 -1
  89. package/dist/{chunk-b4escq4c.js → chunk-cpy282b8.js} +6 -6
  90. package/dist/chunk-dq3t5sr3.js +114 -0
  91. package/dist/chunk-dq3t5sr3.js.map +11 -0
  92. package/dist/{chunk-68hm50qh.js → chunk-fdk0ks9p.js} +16 -46
  93. package/dist/chunk-fdk0ks9p.js.map +12 -0
  94. package/dist/{chunk-fzae1jpq.js → chunk-fycac8e9.js} +50 -16
  95. package/dist/{chunk-fzae1jpq.js.map → chunk-fycac8e9.js.map} +3 -3
  96. package/dist/{chunk-zft9bzbc.js → chunk-hkbks1xm.js} +2 -1
  97. package/dist/{chunk-zft9bzbc.js.map → chunk-hkbks1xm.js.map} +3 -3
  98. package/dist/{chunk-m3qx2pns.js → chunk-hvq8xs66.js} +28 -12
  99. package/dist/{chunk-m3qx2pns.js.map → chunk-hvq8xs66.js.map} +5 -5
  100. package/dist/{chunk-bc3y6gff.js → chunk-jka26v8c.js} +1 -1
  101. package/dist/{chunk-s1mqyqmm.js → chunk-js9e6487.js} +12 -8
  102. package/dist/chunk-js9e6487.js.map +18 -0
  103. package/dist/{chunk-zxhym8tr.js → chunk-k29rdc3h.js} +1 -1
  104. package/dist/{chunk-rg725hry.js → chunk-m1cwncee.js} +86 -34
  105. package/dist/{chunk-rg725hry.js.map → chunk-m1cwncee.js.map} +8 -8
  106. package/dist/{chunk-1yh6jgtz.js → chunk-mrs7jy17.js} +2 -2
  107. package/dist/{chunk-qavwr628.js → chunk-n1hbwc6y.js} +5 -6
  108. package/dist/chunk-n1hbwc6y.js.map +12 -0
  109. package/dist/{chunk-pqvvqc65.js → chunk-pfdq1ga6.js} +3 -3
  110. package/dist/{chunk-k29n4176.js → chunk-phs5fbff.js} +6 -6
  111. package/dist/{chunk-wqe9shx2.js → chunk-qbd282aa.js} +2 -2
  112. package/dist/{chunk-e91fmg6t.js → chunk-qsa7nw6f.js} +2 -1
  113. package/dist/{chunk-e91fmg6t.js.map → chunk-qsa7nw6f.js.map} +3 -3
  114. package/dist/chunk-r588h4ev.js +98 -0
  115. package/dist/chunk-r588h4ev.js.map +10 -0
  116. package/dist/{chunk-rtdrm592.js → chunk-t58sktr5.js} +12 -4
  117. package/dist/{chunk-rtdrm592.js.map → chunk-t58sktr5.js.map} +3 -3
  118. package/dist/{chunk-paxabbqd.js → chunk-tapdssb5.js} +1 -1
  119. package/dist/{chunk-dhkc9b23.js → chunk-v8a1qjzp.js} +1 -1
  120. package/dist/{chunk-q8d9p0tb.js → chunk-wzcjhv54.js} +8 -1
  121. package/dist/{chunk-q8d9p0tb.js.map → chunk-wzcjhv54.js.map} +3 -3
  122. package/dist/{chunk-pc7kra3k.js → chunk-xavet0qs.js} +1 -1
  123. package/dist/{chunk-m9ketb51.js → chunk-ygvay56w.js} +1 -1
  124. package/dist/{chunk-0mvjpgvm.js → chunk-yyj009tv.js} +4 -4
  125. package/dist/connectors/connections/capability.d.ts +11 -0
  126. package/dist/connectors/connections/capability.d.ts.map +1 -1
  127. package/dist/connectors/connections/internal.d.ts +2 -1
  128. package/dist/connectors/connections/internal.d.ts.map +1 -1
  129. package/dist/connectors/connections/internal.js +8 -4
  130. package/dist/connectors/connections/internal.js.map +1 -1
  131. package/dist/connectors/connections/service.d.ts +9 -1
  132. package/dist/connectors/connections/service.d.ts.map +1 -1
  133. package/dist/connectors/execution.d.ts +7 -1
  134. package/dist/connectors/execution.d.ts.map +1 -1
  135. package/dist/connectors/service.d.ts +5 -1
  136. package/dist/connectors/service.d.ts.map +1 -1
  137. package/dist/deploy/index.d.ts +1 -1
  138. package/dist/deploy/index.d.ts.map +1 -1
  139. package/dist/deploy/internal.js +2 -2
  140. package/dist/deploy/internal.js.map +2 -2
  141. package/dist/deploy/types.d.ts +12 -59
  142. package/dist/deploy/types.d.ts.map +1 -1
  143. package/dist/env/index.d.ts +10 -3
  144. package/dist/env/index.d.ts.map +1 -1
  145. package/dist/env/index.js.map +2 -2
  146. package/dist/events/execution.d.ts +8 -1
  147. package/dist/events/execution.d.ts.map +1 -1
  148. package/dist/events/types/syncs.d.ts +4 -0
  149. package/dist/events/types/syncs.d.ts.map +1 -1
  150. package/dist/execution/agent.js +37 -36
  151. package/dist/execution/agent.js.map +1 -1
  152. package/dist/execution/authorized-object-reader.d.ts +4 -0
  153. package/dist/execution/authorized-object-reader.d.ts.map +1 -1
  154. package/dist/execution/object-reader-ontology.d.ts +3 -0
  155. package/dist/execution/object-reader-ontology.d.ts.map +1 -1
  156. package/dist/execution/primitive.js +36 -35
  157. package/dist/execution/primitive.js.map +1 -1
  158. package/dist/execution/request.d.ts +1 -1
  159. package/dist/execution/request.d.ts.map +1 -1
  160. package/dist/execution/request.js +33 -32
  161. package/dist/execution/request.js.map +3 -3
  162. package/dist/http/api-routes.d.ts.map +1 -1
  163. package/dist/http/index.js +1 -1
  164. package/dist/index.d.ts +7 -7
  165. package/dist/index.d.ts.map +1 -1
  166. package/dist/index.js +63 -59
  167. package/dist/index.js.map +1 -1
  168. package/dist/maintenance/index.js +1 -1
  169. package/dist/materializer/index.js +22 -21
  170. package/dist/materializer/index.js.map +1 -1
  171. package/dist/models/audio/runtime.d.ts.map +1 -1
  172. package/dist/models/audio/types.d.ts +19 -0
  173. package/dist/models/audio/types.d.ts.map +1 -1
  174. package/dist/models/execution/index.js +20 -19
  175. package/dist/models/execution/index.js.map +1 -1
  176. package/dist/models/index.d.ts +1 -1
  177. package/dist/models/index.d.ts.map +1 -1
  178. package/dist/objects/index.js +36 -35
  179. package/dist/objects/index.js.map +1 -1
  180. package/dist/objects/query/executor.d.ts +3 -1
  181. package/dist/objects/query/executor.d.ts.map +1 -1
  182. package/dist/objects/query/explain.d.ts +3 -1
  183. package/dist/objects/query/explain.d.ts.map +1 -1
  184. package/dist/objects/query/index.d.ts +1 -1
  185. package/dist/objects/query/index.d.ts.map +1 -1
  186. package/dist/objects/query/index.js +19 -18
  187. package/dist/objects/query/index.js.map +1 -1
  188. package/dist/objects/query/link-query-clearance.d.ts +3 -0
  189. package/dist/objects/query/link-query-clearance.d.ts.map +1 -1
  190. package/dist/objects/query/links.d.ts +1 -1
  191. package/dist/objects/query/links.d.ts.map +1 -1
  192. package/dist/objects/query/validate.d.ts +17 -0
  193. package/dist/objects/query/validate.d.ts.map +1 -1
  194. package/dist/objects/sdk/runtime-query-executor.d.ts +1 -1
  195. package/dist/objects/sdk/runtime-query-executor.d.ts.map +1 -1
  196. package/dist/ontology/index.js +3 -3
  197. package/dist/ontology/internal.js +3 -3
  198. package/dist/pipelines/index.js +21 -20
  199. package/dist/pipelines/index.js.map +1 -1
  200. package/dist/projections/internal.js +20 -19
  201. package/dist/projections/internal.js.map +1 -1
  202. package/dist/queues/in-memory.d.ts +1 -1
  203. package/dist/queues/in-memory.d.ts.map +1 -1
  204. package/dist/runtime/create.d.ts.map +1 -1
  205. package/dist/runtime/definitions.d.ts +14 -0
  206. package/dist/runtime/definitions.d.ts.map +1 -1
  207. package/dist/runtime/host.d.ts +3 -1
  208. package/dist/runtime/host.d.ts.map +1 -1
  209. package/dist/runtime/index.d.ts +1 -1
  210. package/dist/runtime/index.d.ts.map +1 -1
  211. package/dist/runtime/internal.js +24 -23
  212. package/dist/runtime/internal.js.map +2 -2
  213. package/dist/runtime/locale.d.ts +0 -2
  214. package/dist/runtime/locale.d.ts.map +1 -1
  215. package/dist/runtime/resolve-definitions.d.ts +2 -1
  216. package/dist/runtime/resolve-definitions.d.ts.map +1 -1
  217. package/dist/runtime/sixb.d.ts.map +1 -1
  218. package/dist/sandboxes/auth.d.ts +26 -4
  219. package/dist/sandboxes/auth.d.ts.map +1 -1
  220. package/dist/sandboxes/errors.d.ts +19 -0
  221. package/dist/sandboxes/errors.d.ts.map +1 -1
  222. package/dist/sandboxes/exec.d.ts +2 -0
  223. package/dist/sandboxes/exec.d.ts.map +1 -1
  224. package/dist/sandboxes/index.d.ts +4 -2
  225. package/dist/sandboxes/index.d.ts.map +1 -1
  226. package/dist/sandboxes/index.js +13 -7
  227. package/dist/sandboxes/index.js.map +1 -1
  228. package/dist/sandboxes/sandbox.d.ts +15 -1
  229. package/dist/sandboxes/sandbox.d.ts.map +1 -1
  230. package/dist/security/view-conditions.d.ts.map +1 -1
  231. package/dist/shares/internal.js +16 -15
  232. package/dist/shares/internal.js.map +2 -2
  233. package/dist/storage/agents/in-memory.d.ts +18 -1
  234. package/dist/storage/agents/in-memory.d.ts.map +1 -1
  235. package/dist/storage/agents/index.d.ts +1 -1
  236. package/dist/storage/agents/index.d.ts.map +1 -1
  237. package/dist/storage/agents/provider.d.ts +43 -9
  238. package/dist/storage/agents/provider.d.ts.map +1 -1
  239. package/dist/storage/agents/provider.js +19 -3
  240. package/dist/storage/agents/provider.js.map +1 -1
  241. package/dist/storage/agents/types.d.ts +150 -4
  242. package/dist/storage/agents/types.d.ts.map +1 -1
  243. package/dist/storage/ai-cost/analytics.d.ts +3 -2
  244. package/dist/storage/ai-cost/analytics.d.ts.map +1 -1
  245. package/dist/storage/ai-cost/provider.js +4 -3
  246. package/dist/storage/ai-cost/provider.js.map +1 -1
  247. package/dist/storage/ai-cost/types.d.ts +5 -1
  248. package/dist/storage/ai-cost/types.d.ts.map +1 -1
  249. package/dist/storage/artifacts/in-memory.d.ts.map +1 -1
  250. package/dist/storage/artifacts/record.d.ts +3 -1
  251. package/dist/storage/artifacts/record.d.ts.map +1 -1
  252. package/dist/storage/artifacts/types.d.ts +7 -0
  253. package/dist/storage/artifacts/types.d.ts.map +1 -1
  254. package/dist/storage/file-upload-sessions/provider.js +7 -7
  255. package/dist/storage/index.d.ts +2 -2
  256. package/dist/storage/index.d.ts.map +1 -1
  257. package/dist/storage/index.js +23 -22
  258. package/dist/storage/index.js.map +1 -1
  259. package/dist/storage/internal.js +8 -8
  260. package/dist/storage/operation-scope.d.ts.map +1 -1
  261. package/dist/storage/operation-scope.js +1 -1
  262. package/dist/storage/sync-runs/idempotency.d.ts.map +1 -1
  263. package/dist/storage/sync-runs/in-memory.d.ts +2 -1
  264. package/dist/storage/sync-runs/in-memory.d.ts.map +1 -1
  265. package/dist/storage/sync-runs/index.d.ts +1 -1
  266. package/dist/storage/sync-runs/index.d.ts.map +1 -1
  267. package/dist/storage/sync-runs/types.d.ts +27 -2
  268. package/dist/storage/sync-runs/types.d.ts.map +1 -1
  269. package/dist/storage/workflow-runs/provider.js +7 -7
  270. package/dist/syncs/accounts.d.ts +36 -0
  271. package/dist/syncs/accounts.d.ts.map +1 -0
  272. package/dist/syncs/builders.d.ts.map +1 -1
  273. package/dist/syncs/connections.d.ts +36 -0
  274. package/dist/syncs/connections.d.ts.map +1 -0
  275. package/dist/syncs/execution.d.ts +14 -4
  276. package/dist/syncs/execution.d.ts.map +1 -1
  277. package/dist/syncs/index.d.ts +2 -1
  278. package/dist/syncs/index.d.ts.map +1 -1
  279. package/dist/syncs/index.js +22 -21
  280. package/dist/syncs/index.js.map +1 -1
  281. package/dist/syncs/request.d.ts +16 -2
  282. package/dist/syncs/request.d.ts.map +1 -1
  283. package/dist/syncs/run-dispatch.d.ts +14 -2
  284. package/dist/syncs/run-dispatch.d.ts.map +1 -1
  285. package/dist/testing/agent-approval-storage-contract.d.ts.map +1 -1
  286. package/dist/testing/agent-inbox-storage-contract.d.ts.map +1 -1
  287. package/dist/testing/agent-storage-contract.d.ts.map +1 -1
  288. package/dist/testing/ai-cost-storage-contract.d.ts.map +1 -1
  289. package/dist/testing/artifact-storage-contract.d.ts.map +1 -1
  290. package/dist/testing/index.js +1157 -100
  291. package/dist/testing/index.js.map +9 -9
  292. package/dist/testing/run-claim-storage-contract.d.ts.map +1 -1
  293. package/dist/testing/sandboxes-contract.d.ts.map +1 -1
  294. package/dist/webhooks/internal.js +17 -16
  295. package/dist/webhooks/internal.js.map +2 -2
  296. package/dist/workers/index.js +66 -13
  297. package/dist/workers/index.js.map +4 -4
  298. package/dist/workers/queue-worker.d.ts +5 -0
  299. package/dist/workers/queue-worker.d.ts.map +1 -1
  300. package/dist/workers/worker.d.ts +8 -0
  301. package/dist/workers/worker.d.ts.map +1 -1
  302. package/dist/workflows/index.js +42 -40
  303. package/dist/workflows/index.js.map +1 -1
  304. package/package.json +7 -1
  305. package/src/actions/validation.ts +3 -1
  306. package/src/agents/children.ts +6 -0
  307. package/src/agents/errors.ts +3 -0
  308. package/src/agents/execution.ts +170 -20
  309. package/src/agents/index.ts +5 -0
  310. package/src/agents/model-routing.ts +116 -34
  311. package/src/agents/request.ts +783 -38
  312. package/src/agents/run-events.ts +235 -38
  313. package/src/agents/run-session-children.ts +13 -2
  314. package/src/agents/run-token.ts +7 -0
  315. package/src/agents/run-turn.ts +140 -23
  316. package/src/agents/streams/index.ts +2 -0
  317. package/src/agents/streams/internal.ts +12 -0
  318. package/src/agents/streams/protocol.ts +69 -1
  319. package/src/agents/streams/steps.ts +131 -0
  320. package/src/agents/thread-access.ts +57 -2
  321. package/src/artifacts/publish/merge.ts +14 -3
  322. package/src/artifacts/run-query.ts +5 -2
  323. package/src/bootstrap/discovery.ts +61 -11
  324. package/src/calendar.ts +195 -0
  325. package/src/connectors/connections/capability.ts +40 -0
  326. package/src/connectors/connections/internal.ts +3 -0
  327. package/src/connectors/connections/service.ts +74 -5
  328. package/src/connectors/execution.ts +5 -6
  329. package/src/connectors/service.ts +23 -0
  330. package/src/deploy/index.ts +0 -5
  331. package/src/deploy/types.ts +12 -64
  332. package/src/deploy/validation.ts +1 -1
  333. package/src/env/index.ts +10 -4
  334. package/src/events/execution.ts +42 -2
  335. package/src/events/types/syncs.ts +4 -0
  336. package/src/execution/authorized-object-reader.ts +33 -5
  337. package/src/execution/object-reader-ontology.ts +6 -0
  338. package/src/execution/request.ts +1 -0
  339. package/src/http/api-routes.ts +8 -0
  340. package/src/index.ts +21 -2
  341. package/src/models/audio/runtime.ts +57 -14
  342. package/src/models/audio/types.ts +20 -0
  343. package/src/models/index.ts +1 -0
  344. package/src/objects/query/executor.ts +4 -0
  345. package/src/objects/query/explain.ts +5 -0
  346. package/src/objects/query/index.ts +1 -0
  347. package/src/objects/query/link-query-clearance.ts +4 -1
  348. package/src/objects/query/links.ts +5 -1
  349. package/src/objects/query/validate.ts +33 -1
  350. package/src/objects/sdk/runtime-query-executor.ts +7 -3
  351. package/src/runtime/create.ts +1 -0
  352. package/src/runtime/definitions.ts +25 -0
  353. package/src/runtime/host.ts +16 -8
  354. package/src/runtime/index.ts +6 -1
  355. package/src/runtime/locale.ts +0 -10
  356. package/src/runtime/resolve-definitions.ts +7 -1
  357. package/src/runtime/sixb.ts +12 -2
  358. package/src/sandboxes/README.md +12 -1
  359. package/src/sandboxes/auth.ts +32 -4
  360. package/src/sandboxes/errors.ts +27 -0
  361. package/src/sandboxes/exec.ts +3 -1
  362. package/src/sandboxes/index.ts +18 -1
  363. package/src/sandboxes/sandbox.ts +15 -1
  364. package/src/security/view-conditions.ts +2 -1
  365. package/src/storage/agents/in-memory.ts +271 -6
  366. package/src/storage/agents/index.ts +10 -0
  367. package/src/storage/agents/provider.ts +178 -13
  368. package/src/storage/agents/types.ts +166 -4
  369. package/src/storage/ai-cost/analytics.ts +22 -43
  370. package/src/storage/ai-cost/types.ts +5 -1
  371. package/src/storage/artifacts/in-memory.ts +20 -5
  372. package/src/storage/artifacts/record.ts +8 -2
  373. package/src/storage/artifacts/types.ts +7 -0
  374. package/src/storage/index.ts +11 -0
  375. package/src/storage/operation-scope.ts +1 -0
  376. package/src/storage/sync-runs/idempotency.ts +1 -0
  377. package/src/storage/sync-runs/in-memory.ts +43 -1
  378. package/src/storage/sync-runs/index.ts +1 -0
  379. package/src/storage/sync-runs/types.ts +30 -1
  380. package/src/syncs/accounts.ts +85 -0
  381. package/src/syncs/builders.ts +18 -1
  382. package/src/syncs/connections.ts +123 -0
  383. package/src/syncs/execution.ts +64 -22
  384. package/src/syncs/index.ts +3 -0
  385. package/src/syncs/request.ts +81 -23
  386. package/src/syncs/run-dispatch.ts +69 -7
  387. package/src/testing/agent-approval-storage-contract.ts +123 -0
  388. package/src/testing/agent-inbox-storage-contract.ts +59 -0
  389. package/src/testing/agent-storage-contract.ts +794 -8
  390. package/src/testing/ai-cost-storage-contract.ts +80 -0
  391. package/src/testing/artifact-storage-contract.ts +139 -0
  392. package/src/testing/run-claim-storage-contract.ts +116 -0
  393. package/src/testing/sandboxes-contract.ts +50 -0
  394. package/src/workers/README.md +4 -1
  395. package/src/workers/lost-runs.ts +1 -0
  396. package/src/workers/queue-worker.ts +16 -5
  397. package/src/workers/worker.ts +67 -7
  398. package/dist/chunk-5a4a52tq.js.map +0 -10
  399. package/dist/chunk-5t9gm5tt.js.map +0 -22
  400. package/dist/chunk-68hm50qh.js.map +0 -13
  401. package/dist/chunk-aw1z0gre.js +0 -234
  402. package/dist/chunk-aw1z0gre.js.map +0 -12
  403. package/dist/chunk-ey1p8w68.js.map +0 -13
  404. package/dist/chunk-k3jh8gsg.js.map +0 -10
  405. package/dist/chunk-nxysqbt0.js.map +0 -10
  406. package/dist/chunk-qavwr628.js.map +0 -12
  407. package/dist/chunk-s1mqyqmm.js.map +0 -18
  408. package/dist/chunk-zeykm8my.js.map +0 -14
  409. /package/dist/{chunk-stmxh0hv.js.map → chunk-3neam1y5.js.map} +0 -0
  410. /package/dist/{chunk-0hkdtwqk.js.map → chunk-44hrfmbk.js.map} +0 -0
  411. /package/dist/{chunk-s5pj68fa.js.map → chunk-5sswe5ej.js.map} +0 -0
  412. /package/dist/{chunk-q9nkpr8k.js.map → chunk-9tpmfh3n.js.map} +0 -0
  413. /package/dist/{chunk-naxjka9v.js.map → chunk-brhp9d97.js.map} +0 -0
  414. /package/dist/{chunk-8a8k38tz.js.map → chunk-brybqw5k.js.map} +0 -0
  415. /package/dist/{chunk-vehcr9eb.js.map → chunk-cg7cygfj.js.map} +0 -0
  416. /package/dist/{chunk-b4escq4c.js.map → chunk-cpy282b8.js.map} +0 -0
  417. /package/dist/{chunk-bc3y6gff.js.map → chunk-jka26v8c.js.map} +0 -0
  418. /package/dist/{chunk-zxhym8tr.js.map → chunk-k29rdc3h.js.map} +0 -0
  419. /package/dist/{chunk-1yh6jgtz.js.map → chunk-mrs7jy17.js.map} +0 -0
  420. /package/dist/{chunk-pqvvqc65.js.map → chunk-pfdq1ga6.js.map} +0 -0
  421. /package/dist/{chunk-k29n4176.js.map → chunk-phs5fbff.js.map} +0 -0
  422. /package/dist/{chunk-wqe9shx2.js.map → chunk-qbd282aa.js.map} +0 -0
  423. /package/dist/{chunk-paxabbqd.js.map → chunk-tapdssb5.js.map} +0 -0
  424. /package/dist/{chunk-dhkc9b23.js.map → chunk-v8a1qjzp.js.map} +0 -0
  425. /package/dist/{chunk-pc7kra3k.js.map → chunk-xavet0qs.js.map} +0 -0
  426. /package/dist/{chunk-m9ketb51.js.map → chunk-ygvay56w.js.map} +0 -0
  427. /package/dist/{chunk-0mvjpgvm.js.map → chunk-yyj009tv.js.map} +0 -0
@@ -35,11 +35,11 @@ import {
35
35
  normalizeLinkProperties2,
36
36
  validateLinkProperties2,
37
37
  assertTelemetryProperty2
38
- } from "./chunk-3zagkr6w.js";
38
+ } from "./chunk-7mhbs9yy.js";
39
39
  import {
40
40
  isObjectRefSchema2,
41
41
  validateSchemaOrRefValue2
42
- } from "./chunk-8a8k38tz.js";
42
+ } from "./chunk-brybqw5k.js";
43
43
  import {
44
44
  ActionDefinitionError2,
45
45
  missingActionMutationMessage,
@@ -60,7 +60,7 @@ import {
60
60
  createUsersRuntime,
61
61
  SYSTEM_PRINCIPAL2,
62
62
  principalsEqual2
63
- } from "./chunk-xcrnrpfh.js";
63
+ } from "./chunk-394zjzjs.js";
64
64
  import {
65
65
  ActionValidationError2,
66
66
  SIXB_ERROR_CODES2,
@@ -97,7 +97,7 @@ import {
97
97
  canViewProjectionRun2,
98
98
  canViewPrimitiveRun2,
99
99
  canViewProjection2
100
- } from "./chunk-paxabbqd.js";
100
+ } from "./chunk-tapdssb5.js";
101
101
  import {
102
102
  compileSelectedObjectReadScope2
103
103
  } from "./chunk-rt9deb92.js";
@@ -107,7 +107,7 @@ import {
107
107
  resolveAgentExecutionAuthorization2,
108
108
  userCanRunAgent2,
109
109
  resolveInheritedAgentExecutionAuthorization2
110
- } from "./chunk-s5pj68fa.js";
110
+ } from "./chunk-5sswe5ej.js";
111
111
  import {
112
112
  ACTION_RUN_FAILURE_CODES2,
113
113
  parseActionRunFailure2
@@ -145,15 +145,22 @@ import {
145
145
  createAgentMessageId2,
146
146
  createAgentInboxItemId,
147
147
  AGENT_REASONING_LEVELS2,
148
+ countsAsThreadMessage2,
148
149
  movesComputerPlace2,
150
+ turnPlace2,
151
+ runPlaceKey2,
149
152
  isAgentApprovalMode2,
150
153
  agentApprovalHoldsRun2
151
- } from "./chunk-ey1p8w68.js";
154
+ } from "./chunk-5pz3htbe.js";
155
+ import {
156
+ canonicalLocale,
157
+ canonicalTimeZone2
158
+ } from "./chunk-dq3t5sr3.js";
152
159
  import {
153
160
  actionRunRequestsEqual,
154
161
  ObjectNotFoundError2,
155
162
  ArtifactStorageError
156
- } from "./chunk-ewqn51gr.js";
163
+ } from "./chunk-88xeh6zx.js";
157
164
  import {
158
165
  ExecutionStorageError2
159
166
  } from "./chunk-c29729me.js";
@@ -167,20 +174,22 @@ import {
167
174
  objectBatchKey2,
168
175
  matchesPredicate,
169
176
  WORKFLOW_RUN_FAILURE_CODES2
170
- } from "./chunk-gjhrz66x.js";
177
+ } from "./chunk-06kpaqg4.js";
171
178
  import {
172
179
  explainObjectQuery2
173
- } from "./chunk-s1mqyqmm.js";
180
+ } from "./chunk-js9e6487.js";
174
181
  import {
175
182
  redactDomainEvent,
176
183
  uniqueLookupKeyOf,
177
184
  assertAuthorizedObjectReaderBinding,
178
185
  getAuthorizedOntologyView,
186
+ getQueryDiscovery,
179
187
  readerClearance,
180
188
  readerEventClearance,
181
189
  readerViewConditions
182
- } from "./chunk-5t9gm5tt.js";
190
+ } from "./chunk-6md802cc.js";
183
191
  import {
192
+ agentRunEndedShort,
184
193
  createAgentThreadAccessRule,
185
194
  assertConversationThread2,
186
195
  agentThreadViews,
@@ -191,7 +200,7 @@ import {
191
200
  transactionArtifactAccessRules,
192
201
  updatableArtifactIds,
193
202
  createArtifactsRuntime
194
- } from "./chunk-m3qx2pns.js";
203
+ } from "./chunk-hvq8xs66.js";
195
204
  import {
196
205
  shareSixbErrorReporter2,
197
206
  reportActionPhaseFailure2,
@@ -213,14 +222,14 @@ import {
213
222
  createActivityCaptureRuntime,
214
223
  registerActivityCaptureRuntime,
215
224
  ModelExecutionSession
216
- } from "./chunk-k29n4176.js";
225
+ } from "./chunk-phs5fbff.js";
217
226
  import {
218
227
  publishAgentThreadMoved2,
219
228
  publishAgentApprovalActivity,
220
229
  publishAgentRunActivity2,
221
230
  publishAgentRunCancel2,
222
231
  publishAgentRunFinished2
223
- } from "./chunk-k3jh8gsg.js";
232
+ } from "./chunk-5xkqasvn.js";
224
233
  import {
225
234
  aiLimitSubjectsFromAttribution2,
226
235
  applicableAiLimitPolicyStatuses2,
@@ -236,10 +245,10 @@ import {
236
245
  } from "./chunk-8ncg20rd.js";
237
246
  import {
238
247
  registerConnectorConnectionsRuntime
239
- } from "./chunk-5a4a52tq.js";
248
+ } from "./chunk-0pmpwn3g.js";
240
249
  import {
241
250
  createConnectorRuntime
242
- } from "./chunk-qavwr628.js";
251
+ } from "./chunk-n1hbwc6y.js";
243
252
  import {
244
253
  DatasetValidationError2
245
254
  } from "./chunk-wx7smkn2.js";
@@ -256,7 +265,7 @@ import {
256
265
  aiModelCallOutputTokenAllowance,
257
266
  ModelUsageRecordingError2,
258
267
  LanguageModelCallMeter
259
- } from "./chunk-1yh6jgtz.js";
268
+ } from "./chunk-mrs7jy17.js";
260
269
  import {
261
270
  createLinkScopeFingerprint2,
262
271
  normalizeJsonProperties2,
@@ -266,7 +275,15 @@ import {
266
275
  resolveEffectiveLink,
267
276
  resolveEffectiveLinkSlotMember,
268
277
  linkCardinality
269
- } from "./chunk-b4escq4c.js";
278
+ } from "./chunk-cpy282b8.js";
279
+ import {
280
+ createSyncConnections,
281
+ mayRunConnection,
282
+ visibleSyncConnectionIds,
283
+ seesConnection,
284
+ SyncValidationError2,
285
+ requestSyncRun2
286
+ } from "./chunk-04r2fdsd.js";
270
287
  import {
271
288
  resolveLoggingService2
272
289
  } from "./chunk-1vg43g9q.js";
@@ -274,13 +291,15 @@ import {
274
291
  EditBatchError2,
275
292
  lowerEditBatch2
276
293
  } from "./chunk-m427qgq0.js";
277
- import {
278
- SyncValidationError2,
279
- requestSyncRun2
280
- } from "./chunk-aw1z0gre.js";
281
294
  import {
282
295
  compileShareAccessPlan
283
- } from "./chunk-wqe9shx2.js";
296
+ } from "./chunk-qbd282aa.js";
297
+ import {
298
+ requestPipelineRun2
299
+ } from "./chunk-pfdq1ga6.js";
300
+ import {
301
+ PipelineError2
302
+ } from "./chunk-hke9aeen.js";
284
303
  import {
285
304
  createObjectQueryBuilder2,
286
305
  decorateObjectQueryExecutor
@@ -289,25 +308,19 @@ import {
289
308
  SandboxError2,
290
309
  sandboxCredentialIssue2,
291
310
  staticSandboxRecipe2
292
- } from "./chunk-rtdrm592.js";
311
+ } from "./chunk-t58sktr5.js";
312
+ import {
313
+ executionRecordInputFromRuntime,
314
+ ensureExecutionRecord2,
315
+ createPrimitiveExecutionRecord,
316
+ restoreTrustedPrimitiveExecutionScope
317
+ } from "./chunk-xavet0qs.js";
293
318
  import {
294
319
  resolveLanguageModel2
295
320
  } from "./chunk-3723kgba.js";
296
321
  import {
297
322
  schemaRecordToJsonSchema2
298
323
  } from "./chunk-0kgrghqx.js";
299
- import {
300
- requestPipelineRun2
301
- } from "./chunk-pqvvqc65.js";
302
- import {
303
- PipelineError2
304
- } from "./chunk-hke9aeen.js";
305
- import {
306
- executionRecordInputFromRuntime,
307
- ensureExecutionRecord2,
308
- createPrimitiveExecutionRecord,
309
- restoreTrustedPrimitiveExecutionScope
310
- } from "./chunk-pc7kra3k.js";
311
324
  import {
312
325
  lineageColumn,
313
326
  isUnknownLineage,
@@ -340,18 +353,25 @@ import {
340
353
  import {
341
354
  eventAttribution2
342
355
  } from "./chunk-q7g9cqwt.js";
356
+ import {
357
+ isOAuthConnectorDefinition2
358
+ } from "./chunk-pvpq483h.js";
343
359
  import {
344
360
  ObjectQueryPlanningError2
345
361
  } from "./chunk-0k1h5hmr.js";
346
362
  import {
347
363
  normalizeParams
348
- } from "./chunk-stmxh0hv.js";
364
+ } from "./chunk-3neam1y5.js";
349
365
  import {
350
366
  MaterializationValidationError2,
351
367
  MaterializationObjectNotFoundError2,
352
368
  UniqueValueViolationError2,
353
369
  isMaterializationConflictError2
354
370
  } from "./chunk-y7dbmaqh.js";
371
+ import {
372
+ OntologyValidationError2,
373
+ OntologyNotFoundError2
374
+ } from "./chunk-cqr3acm1.js";
355
375
  import {
356
376
  ModelProviderError2,
357
377
  ModelStreamError2,
@@ -359,17 +379,13 @@ import {
359
379
  StructuredOutputError2,
360
380
  sameEmbeddingModel
361
381
  } from "./chunk-rtkqczbr.js";
362
- import {
363
- OntologyValidationError2,
364
- OntologyNotFoundError2
365
- } from "./chunk-cqr3acm1.js";
366
382
  import {
367
383
  AgentRequestError2,
368
384
  AgentMemoryError2
369
385
  } from "./chunk-9wr3yajk.js";
370
386
  import {
371
387
  AGENT_APPROVAL_MODES2
372
- } from "./chunk-nxysqbt0.js";
388
+ } from "./chunk-389ybvw9.js";
373
389
  import {
374
390
  resolveFileRefAtPath2,
375
391
  openFileRef2,
@@ -1941,10 +1957,16 @@ async function questionState(agents, conversationId, thread, runs) {
1941
1957
  const waiting = [...runs].reverse().find((run) => run.status !== "failed" && run.status !== "cancelled");
1942
1958
  if (!waiting || !isAwaitingAnswerRun2(waiting))
1943
1959
  return {};
1960
+ const { total } = await agents.messages.list({
1961
+ projectId: waiting.projectId,
1962
+ threadId: conversationId,
1963
+ limit: 1
1964
+ });
1944
1965
  const [latest] = await agents.runs.listThreadSubagents({
1945
1966
  projectId: waiting.projectId,
1946
1967
  threadId: conversationId,
1947
1968
  spawnKey: waiting.spawnKey,
1969
+ ...total > 0 ? { retainedTurnsOnly: true } : {},
1948
1970
  limit: 1
1949
1971
  });
1950
1972
  if (latest && latest.threadId !== thread.id)
@@ -2299,22 +2321,35 @@ var HEAVY_FROM = 0.4;
2299
2321
  var LIGHT_FROM = 0.8;
2300
2322
  var DECISION_TIMEOUT_MS = 2000;
2301
2323
  var PROMPT_CACHE_TTL_MS = 5 * 60000;
2302
- var TIER_QUESTIONS = {
2303
- tier: question2.choice({
2304
- instructions: "A user sent this message to a data agent. The agent answers from the project's data with " + "tools: it searches and reads objects, queries and aggregates datasets, follows links, runs " + "actions and writes reports. Pick the model tier the answer needs. Judge the work the " + "answer takes, not the length or tone of the message.",
2305
- options: {
2306
- light: "A lookup, a count, a filter or a list: one or two queries with an obvious answer. " + "Greetings, thanks and short follow-ups.",
2307
- standard: "Usual analysis: several queries, comparisons, trends or aggregations, a short summary, " + "or a simple action, with a clear path to the answer.",
2308
- heavy: "Open-ended work: a multi-step investigation, explaining why something happened, " + "weighing trade-offs, building a plan, or writing a long report."
2309
- }
2310
- })
2324
+ var PREVIOUS_MESSAGE_CHARS = 2000;
2325
+ var TIER_WORK = {
2326
+ light: "A lookup, a count, a filter or a list with an obvious answer. Greetings, thanks, and short " + "questions that start no new work.",
2327
+ standard: "Usual work with a clear path: several queries or reads, a comparison, a short summary, a " + "simple action, or a small change to a few files.",
2328
+ heavy: "Open-ended or long work: a multi-step investigation, explaining why something happened, " + "weighing trade-offs, building a plan, writing a long report, or changes across many files " + "that must be checked."
2311
2329
  };
2330
+ function tierQuestions(language) {
2331
+ return {
2332
+ tier: question2.choice({
2333
+ instructions: "A user sent this message to an agent that works in a project with tools: it reads and " + "changes the project's data, runs actions, writes documents, and in a workspace runs " + "commands and edits files. Pick the model tier the answer needs. Judge the work the " + "answer takes, not the length or tone of the message. When the input holds the " + "previous message, with the tier it ran on, judge the <message> in its light: a short " + "message that carries on that work, such as approving a plan or asking for the next " + "step, takes the tier the work needs.",
2334
+ options: {
2335
+ light: tierOption(language, "light"),
2336
+ standard: tierOption(language, "standard"),
2337
+ heavy: tierOption(language, "heavy")
2338
+ }
2339
+ })
2340
+ };
2341
+ }
2342
+ function tierOption(language, tier) {
2343
+ const description = language.tiers.includes(tier) ? language.getByTier(tier).model.definition.description?.trim() : undefined;
2344
+ return description ? `${TIER_WORK[tier]} This tier's model: ${description}` : TIER_WORK[tier];
2345
+ }
2312
2346
  function assertTurnModelRouting(models) {
2313
- const tiers = models?.language?.tiers ?? [];
2347
+ const language = models?.language;
2314
2348
  const decision = models?.decision?.default;
2315
- if (tiers.length === 0 || !decision)
2349
+ if (!language || language.tiers.length === 0 || !decision)
2316
2350
  return;
2317
- if (supportsQuestion(decision.model.definition.capabilities, TIER_QUESTIONS.tier))
2351
+ const { tier } = tierQuestions(language);
2352
+ if (supportsQuestion(decision.model.definition.capabilities, tier))
2318
2353
  return;
2319
2354
  throw new RuntimeError2(`[Sixb] The default decision model '${decision.provider}/${decision.modelId}' cannot pick the tier of an Agent turn: it needs 'choice' questions with ${LANGUAGE_MODEL_TIERS2.length} options. Put a decision model that supports them first in 'models.decision', or configure 'models.language' as a list.`);
2320
2355
  }
@@ -2322,25 +2357,44 @@ function createTurnModelRouter(models, decision) {
2322
2357
  const language = models?.language;
2323
2358
  if (!language || language.tiers.length === 0 || !models?.decision)
2324
2359
  return;
2360
+ const questions = tierQuestions(language);
2325
2361
  return {
2326
- async choose(text, previous) {
2327
- const tierProbabilities = text.trim() ? await askTier(decision, text) : undefined;
2362
+ async choose(turn) {
2363
+ const last = turn.previous && previousTurn(language, turn.previous.run, turn.place);
2364
+ const tierProbabilities = turn.text.trim() ? await askTier(decision, questions, decisionInput(turn, last)) : undefined;
2328
2365
  const tier = tierProbabilities ? tierFor(tierProbabilities) : "standard";
2329
2366
  return {
2330
- model: turnModel(language, tier, previous),
2367
+ model: turnModel(language, tier, last),
2331
2368
  ...tierProbabilities ? { tierProbabilities } : {}
2332
2369
  };
2333
2370
  }
2334
2371
  };
2335
2372
  }
2336
- async function askTier(decision, text) {
2373
+ function decisionInput(turn, last) {
2374
+ const before = turn.previous?.text?.trim();
2375
+ if (!before)
2376
+ return turn.text;
2377
+ const clipped = before.length > PREVIOUS_MESSAGE_CHARS ? `${before.slice(0, PREVIOUS_MESSAGE_CHARS)}\u2026` : before;
2378
+ const tier = last ? ` tier="${last.tier}"` : "";
2379
+ return [
2380
+ `<previous_message${tier}>`,
2381
+ clipped,
2382
+ "</previous_message>",
2383
+ "",
2384
+ "<message>",
2385
+ turn.text,
2386
+ "</message>"
2387
+ ].join(`
2388
+ `);
2389
+ }
2390
+ async function askTier(decision, questions, input) {
2337
2391
  const timeout = new AbortController;
2338
2392
  const timer = setTimeout(() => {
2339
2393
  timeout.abort(new DOMException("[Sixb] The decision model did not answer in time.", "TimeoutError"));
2340
2394
  }, DECISION_TIMEOUT_MS);
2341
2395
  try {
2342
2396
  const { output } = await Promise.race([
2343
- decision.evaluate({ input: text, questions: TIER_QUESTIONS, signal: timeout.signal }),
2397
+ decision.evaluate({ input, questions, signal: timeout.signal }),
2344
2398
  rejectOnAbort(timeout.signal)
2345
2399
  ]);
2346
2400
  const { light, standard, heavy } = output.tier.probabilities;
@@ -2361,9 +2415,8 @@ function tierFor(probabilities) {
2361
2415
  return "light";
2362
2416
  return "standard";
2363
2417
  }
2364
- function turnModel(language, tier, previous) {
2418
+ function turnModel(language, tier, last) {
2365
2419
  const target = language.getByTier(tier);
2366
- const last = previous && previousTurn(language, previous);
2367
2420
  if (!last)
2368
2421
  return target;
2369
2422
  const change = tierRank(target.tier ?? tier) - tierRank(last.tier);
@@ -2373,7 +2426,7 @@ function turnModel(language, tier, previous) {
2373
2426
  return last.model;
2374
2427
  return target;
2375
2428
  }
2376
- function previousTurn(language, run) {
2429
+ function previousTurn(language, run, place) {
2377
2430
  if (!run.spec)
2378
2431
  return;
2379
2432
  const model = language.getByRef(run.spec.model);
@@ -2381,7 +2434,12 @@ function previousTurn(language, run) {
2381
2434
  if (tier === undefined)
2382
2435
  return;
2383
2436
  const lastCallAt = run.completedAt ?? run.startedAt ?? run.createdAt;
2384
- return { model, tier, cacheWarm: Date.now() - lastCallAt.getTime() < PROMPT_CACHE_TTL_MS };
2437
+ const samePlace = runPlaceKey2(run.spec) === runPlaceKey2(place);
2438
+ return {
2439
+ model,
2440
+ tier,
2441
+ cacheWarm: samePlace && Date.now() - lastCallAt.getTime() < PROMPT_CACHE_TTL_MS
2442
+ };
2385
2443
  }
2386
2444
  function tierRank(tier) {
2387
2445
  return LANGUAGE_MODEL_TIERS2.indexOf(tier);
@@ -2538,29 +2596,6 @@ function startQueuedAgentTurn2(sixb, runId, options) {
2538
2596
  // src/agents/request.ts
2539
2597
  import { randomUUID as randomUUID5 } from "crypto";
2540
2598
 
2541
- // src/runtime/locale.ts
2542
- var DEFAULT_PROJECT_LOCALE = "en";
2543
- var DEFAULT_PROJECT_TIME_ZONE = "UTC";
2544
- function canonicalLocale(value) {
2545
- if (typeof value !== "string")
2546
- return;
2547
- try {
2548
- const [locale] = Intl.getCanonicalLocales(value);
2549
- return locale;
2550
- } catch {
2551
- return;
2552
- }
2553
- }
2554
- function canonicalTimeZone(value) {
2555
- if (typeof value !== "string" || value.trim() !== value || value === "")
2556
- return;
2557
- try {
2558
- return new Intl.DateTimeFormat("en-US", { timeZone: value }).resolvedOptions().timeZone;
2559
- } catch {
2560
- return;
2561
- }
2562
- }
2563
-
2564
2599
  // src/agents/context-resolution.ts
2565
2600
  async function resolveAgentContextParts2(runtime, input) {
2566
2601
  const entries = normalizeAgentContextEntries2(input);
@@ -2713,18 +2748,17 @@ async function requestAgentRun2(runtime, execution, models, input) {
2713
2748
  assertComputerPlaceRequest(input.runsOn, input.computer);
2714
2749
  const runsOn = existingThread ? existingThread.runsOn : input.runsOn;
2715
2750
  const approvalMode = input.approvalMode ?? (await resolveAgentApprovalMode(agents, { projectId, principal, threadId: existingThread?.id })).approvalMode;
2716
- const selected = "router" in requested ? await routedConversationRunSpec(agents, {
2751
+ const place = turnPlace2(runsOn, existingThread ? existingThread.computer : input.computer);
2752
+ const selected = "router" in requested ? await routedConversationRunSpec({
2717
2753
  ...requested,
2754
+ agents,
2718
2755
  projectId,
2719
- threadId: existingThread?.id,
2756
+ previous: existingThread ? await latestConversationRun(agents, projectId, existingThread.id) : undefined,
2757
+ place,
2720
2758
  settings,
2721
2759
  language: models.language
2722
2760
  }) : requested;
2723
- const spec = Object.freeze({
2724
- ...selected,
2725
- approvalMode,
2726
- ...runsOn === undefined ? {} : { runsOn }
2727
- });
2761
+ const spec = Object.freeze({ ...selected, approvalMode, ...place });
2728
2762
  const createdThread = existingThread === null;
2729
2763
  const thread = existingThread ?? await createThread(agents, {
2730
2764
  projectId,
@@ -2788,11 +2822,356 @@ async function requestAgentRun2(runtime, execution, models, input) {
2788
2822
  createdThread
2789
2823
  };
2790
2824
  }
2825
+ function isEditableAgentMessage2(message) {
2826
+ if (message.role !== "user")
2827
+ return false;
2828
+ if (message.parts.some((part) => part.type === "continuation"))
2829
+ return false;
2830
+ return countsAsThreadMessage2(message);
2831
+ }
2832
+ async function editAgentMessage2(runtime, execution, models, input, blobStorage) {
2833
+ const authority = resolveExecutionScopeAuthorization(runtime.projectId, {
2834
+ execution,
2835
+ authorization: runtime.runtimeAuthorization
2836
+ });
2837
+ assertNoAgentSelector(input);
2838
+ assertAuthorized2(runtime, { kind: "agent.run" });
2839
+ assertRequestAuthorityCanRunAgent(runtime);
2840
+ const trigger = triggerParts(input);
2841
+ const selection = { model: input.model, reasoning: input.reasoning };
2842
+ const settings = requesterSettings(input);
2843
+ if (input.approvalMode !== undefined)
2844
+ assertAgentApprovalMode(input.approvalMode);
2845
+ const routed = routedTurn(models.router, selection, input);
2846
+ const requested = routed ?? await resolveConversationRunSpec({ models: models.language, selection, settings });
2847
+ assertAttachments(input.attachments);
2848
+ const contextParts = await resolveAgentContextParts2(runtime, input.context);
2849
+ const agents = requireAgentStorage(runtime);
2850
+ const projectId = runtime.projectId;
2851
+ const principal = authority.type === "principal" ? authority.context.principal : input.principal ?? SYSTEM_PRINCIPAL2;
2852
+ const thread = await agents.threads.getById({ projectId, id: input.threadId });
2853
+ if (!thread) {
2854
+ throw new AgentRequestError2("thread_not_found", `[Sixb] Agent thread '${input.threadId}' not found.`);
2855
+ }
2856
+ assertThreadAcceptsMessages(thread, principal);
2857
+ const target = await agents.messages.getById({ projectId, id: input.messageId });
2858
+ if (!target || target.threadId !== thread.id) {
2859
+ throw new AgentRequestError2("message_not_found", `[Sixb] Agent message '${input.messageId}' not found in thread '${thread.id}'.`);
2860
+ }
2861
+ assertEditableMessageAuthority(thread, target, principal);
2862
+ const tail = await listAllThreadMessagesFromSeq(agents, projectId, thread.id, target.seq);
2863
+ assertParticipantCanRewindTail(thread, tail, principal);
2864
+ const rewoundRuns = await listRewoundConversationRuns(agents, projectId, thread.id, tail);
2865
+ assertRewindsWholeTurns(target, tail, rewoundRuns);
2866
+ const approvalMode = input.approvalMode ?? (await resolveAgentApprovalMode(agents, { projectId, principal, threadId: thread.id })).approvalMode;
2867
+ const place = turnPlace2(thread.runsOn, thread.computer);
2868
+ const selected = "router" in requested ? await routedConversationRunSpec({
2869
+ ...requested,
2870
+ agents,
2871
+ projectId,
2872
+ previous: await latestRetainedConversationRun(agents, projectId, thread.id, tail),
2873
+ place,
2874
+ settings,
2875
+ language: models.language
2876
+ }) : requested;
2877
+ const spec = Object.freeze({ ...selected, approvalMode, ...place });
2878
+ const edit = {
2879
+ target,
2880
+ messageId: input.nextMessageId ?? createAgentMessageId2(),
2881
+ authorPrincipal: principal,
2882
+ parts: [
2883
+ ...contextParts,
2884
+ ...trigger,
2885
+ ...(input.attachments ?? []).map((fileRef) => ({ type: "file", fileRef }))
2886
+ ]
2887
+ };
2888
+ const runId = createAgentRunId2();
2889
+ const durableExecution = await prepareDurableAgentExecution(runtime, execution, runId);
2890
+ await assertAiLimitPreflight(runtime, durableExecution);
2891
+ if (thread.activeRunId !== null) {
2892
+ const item = await deferAgentMessageEdit(runtime, execution, thread, edit, {
2893
+ spec,
2894
+ settings,
2895
+ blobStorage
2896
+ });
2897
+ return { kind: "inbox", item };
2898
+ }
2899
+ const documents = await rewoundTurnDocuments(runtime, blobStorage, rewoundRuns, tail);
2900
+ let run;
2901
+ let rewind;
2902
+ let superseded = [];
2903
+ try {
2904
+ run = await runtime.storage.transaction(async (tx) => {
2905
+ const txAgents = tx.agents;
2906
+ if (!txAgents) {
2907
+ throw new AgentRequestError2("storage_unavailable", "[Sixb] Agent storage is not configured.");
2908
+ }
2909
+ rewind = await rewindAgentThread(tx, txAgents, {
2910
+ projectId,
2911
+ thread,
2912
+ messageId: edit.target.id,
2913
+ editor: principal,
2914
+ documents
2915
+ });
2916
+ await tx.executions.create(durableExecution);
2917
+ const reported = await reportAgentApprovals(txAgents, {
2918
+ projectId,
2919
+ threadId: thread.id,
2920
+ messageId: edit.messageId
2921
+ });
2922
+ superseded = reported.superseded;
2923
+ await txAgents.messages.append({
2924
+ id: edit.messageId,
2925
+ projectId,
2926
+ threadId: thread.id,
2927
+ runId: null,
2928
+ role: "user",
2929
+ parts: [...reported.parts, ...edit.parts],
2930
+ authorPrincipal: principal
2931
+ });
2932
+ return txAgents.runs.create({
2933
+ id: runId,
2934
+ projectId,
2935
+ executionId: durableExecution.id,
2936
+ threadId: thread.id,
2937
+ triggerMessageId: edit.messageId,
2938
+ spec
2939
+ });
2940
+ });
2941
+ } catch (error) {
2942
+ if (error instanceof AgentStorageError2 && error.code === "active_run_exists") {
2943
+ throw new AgentRequestError2("active_run_exists", error.message);
2944
+ }
2945
+ throw error;
2946
+ }
2947
+ await announceAgentThreadRewind(runtime, rewind, superseded);
2948
+ await publishRunActivity(runtime, run);
2949
+ await dispatchAgentRun(runtime, agents, runId);
2950
+ return { kind: "turn", run, createdThread: false };
2951
+ }
2952
+ async function deferAgentMessageEdit(runtime, execution, thread, edit, options) {
2953
+ const { spec, settings } = options;
2954
+ const agents = requireAgentStorage(runtime);
2955
+ const projectId = runtime.projectId;
2956
+ const active = thread.activeRunId ? await agents.runs.getById({ projectId, id: thread.activeRunId }) : null;
2957
+ if (active?.kind !== "conversation") {
2958
+ throw new AgentRequestError2("active_run_exists", `[Sixb] Agent thread '${thread.id}' already has an active run '${thread.activeRunId}'.`);
2959
+ }
2960
+ if (!execution.requestedBy) {
2961
+ throw new AgentRequestError2("active_run_exists", `[Sixb] Agent thread '${thread.id}' is answering, and an edit without a signed-in sender cannot wait for it: stop the answer, then edit.`);
2962
+ }
2963
+ const mayStop = principalsEqual2(edit.authorPrincipal, thread.ownerPrincipal) || await askedForTurn(runtime, active, edit.authorPrincipal);
2964
+ if (!mayStop) {
2965
+ throw new AgentRequestError2("not_run_requester", `[Sixb] Agent thread '${thread.id}' runs a turn someone else asked for: only they or the thread's owner can stop it. Edit the message once it ends.`);
2966
+ }
2967
+ const request = await ensureExecutionRecord2(runtime.storage.executions, executionRecordInputFromRuntime({
2968
+ execution,
2969
+ runtimeAuthorization: runtime.runtimeAuthorization
2970
+ }));
2971
+ for (const waiting of await agents.inbox.list({ projectId, threadId: thread.id })) {
2972
+ if (waiting.replacesMessageId !== undefined && principalsEqual2(waiting.authorPrincipal, edit.authorPrincipal)) {
2973
+ await agents.inbox.remove({ projectId, threadId: thread.id, id: waiting.id });
2974
+ }
2975
+ }
2976
+ const { item } = await agents.inbox.enqueue({
2977
+ id: createAgentInboxItemId(),
2978
+ projectId,
2979
+ threadId: thread.id,
2980
+ messageId: edit.messageId,
2981
+ authorPrincipal: edit.authorPrincipal,
2982
+ mode: "queue",
2983
+ immediate: true,
2984
+ replacesMessageId: edit.target.id,
2985
+ parts: edit.parts,
2986
+ spec: {
2987
+ model: spec.model,
2988
+ ...spec.reasoning === undefined ? {} : { reasoning: spec.reasoning },
2989
+ approvalMode: spec.approvalMode
2990
+ },
2991
+ ...settings,
2992
+ executionId: request.id
2993
+ });
2994
+ await queueWaitingSteers(agents, projectId, thread.id, edit.authorPrincipal);
2995
+ await stopTurnBefore(runtime, execution, active, options.blobStorage);
2996
+ await startIfThreadIdle(runtime, execution, thread.id, options.blobStorage);
2997
+ return item;
2998
+ }
2999
+ async function rewindAgentThread(tx, agents, input) {
3000
+ const { projectId, thread, editor } = input;
3001
+ const target = await agents.messages.getById({ projectId, id: input.messageId });
3002
+ if (!target || target.threadId !== thread.id) {
3003
+ throw new AgentRequestError2("message_not_found", `[Sixb] Agent message '${input.messageId}' not found in thread '${thread.id}'.`);
3004
+ }
3005
+ assertEditableMessageAuthority(thread, target, editor);
3006
+ const tail = await listAllThreadMessagesFromSeq(agents, projectId, thread.id, target.seq);
3007
+ assertParticipantCanRewindTail(thread, tail, editor);
3008
+ const rewoundRuns = await listRewoundConversationRuns(agents, projectId, thread.id, tail);
3009
+ assertRewindsWholeTurns(target, tail, rewoundRuns);
3010
+ const restored = new Map;
3011
+ if (tx.artifacts) {
3012
+ for (const { run, later } of oldestFirst(rewoundRuns, tail)) {
3013
+ const trigger = tail.find((message) => message.id === run.triggerMessageId);
3014
+ const undone = await tx.artifacts.undoTurnWrites({
3015
+ projectId,
3016
+ turnRunId: run.id,
3017
+ laterTurnRunIds: later,
3018
+ documents: input.documents.get(run.id) ?? {},
3019
+ ...trigger?.authorPrincipal ? { requester: trigger.authorPrincipal } : {}
3020
+ });
3021
+ for (const entry of undone.restored)
3022
+ restored.set(entry.artifact.id, entry.version);
3023
+ for (const deletedId of undone.deleted)
3024
+ restored.delete(deletedId);
3025
+ }
3026
+ }
3027
+ const approvals = await agents.approvals.rewind({
3028
+ projectId,
3029
+ threadId: thread.id,
3030
+ runIds: rewoundRuns.map((run) => run.id),
3031
+ clearedMessageIds: tail.map((message) => message.id)
3032
+ });
3033
+ await agents.checkpoints.deleteAfterSeq({
3034
+ projectId,
3035
+ threadId: thread.id,
3036
+ afterSeq: target.seq - 1
3037
+ });
3038
+ await agents.messages.deleteFromSeq({ projectId, threadId: thread.id, fromSeq: target.seq });
3039
+ await queueWaitingSteers(agents, projectId, thread.id, editor);
3040
+ return { restoredVersions: [...restored.values()], cancelledApprovals: approvals.cancelled };
3041
+ }
3042
+ async function queueWaitingSteers(agents, projectId, threadId, editor) {
3043
+ const waiting = await agents.inbox.list({ projectId, threadId, includeClaimed: false });
3044
+ for (const item of waiting) {
3045
+ if (item.mode !== "steer" || item.immediate)
3046
+ continue;
3047
+ if (!principalsEqual2(item.authorPrincipal, editor))
3048
+ continue;
3049
+ try {
3050
+ await agents.inbox.update({ projectId, threadId, id: item.id, mode: "queue" });
3051
+ } catch (error) {
3052
+ if (error instanceof AgentStorageError2 && error.code === "invalid_state")
3053
+ continue;
3054
+ throw error;
3055
+ }
3056
+ }
3057
+ }
3058
+ async function rewoundTurnDocuments(runtime, blobStorage, rewoundRuns, tail) {
3059
+ const documents = new Map;
3060
+ const artifacts = runtime.storage.artifacts;
3061
+ if (!artifacts || !blobStorage)
3062
+ return documents;
3063
+ for (const { run, later } of oldestFirst(rewoundRuns, tail)) {
3064
+ documents.set(run.id, await undoneTurnDocuments({ projectId: runtime.projectId, storage: artifacts, blobStorage }, run.id, later));
3065
+ }
3066
+ return documents;
3067
+ }
3068
+ function oldestFirst(rewoundRuns, tail) {
3069
+ const seqOf = new Map(tail.map((message) => [message.id, message.seq]));
3070
+ const started = (run) => (run.startedAt ?? run.createdAt).getTime();
3071
+ const ordered = [...rewoundRuns].sort((left, right) => (seqOf.get(left.triggerMessageId) ?? 0) - (seqOf.get(right.triggerMessageId) ?? 0) || started(left) - started(right) || left.attempt - right.attempt);
3072
+ return ordered.map((run, index) => ({
3073
+ run,
3074
+ later: ordered.slice(index + 1).map((each) => each.id)
3075
+ }));
3076
+ }
3077
+ async function announceAgentThreadRewind(runtime, rewind, superseded) {
3078
+ await announceArtifactUpdates(runtime.events, rewind?.restoredVersions ?? []);
3079
+ await announceAgentApprovals2(runtime.broker, [
3080
+ ...rewind?.cancelledApprovals ?? [],
3081
+ ...superseded
3082
+ ]);
3083
+ }
3084
+ function assertEditableMessageAuthority(_thread, target, principal) {
3085
+ if (!isEditableAgentMessage2(target)) {
3086
+ throw new AgentRequestError2("message_not_editable", `[Sixb] Only user-authored messages can be edited.`);
3087
+ }
3088
+ if (principal.type === "user" && (!target.authorPrincipal || !principalsEqual2(target.authorPrincipal, principal))) {
3089
+ throw new AgentRequestError2("not_message_author", `[Sixb] Only the author of message '${target.id}' can edit it.`);
3090
+ }
3091
+ }
3092
+ function assertParticipantCanRewindTail(thread, tail, principal) {
3093
+ if (principal.type !== "user" || principalsEqual2(principal, thread.ownerPrincipal))
3094
+ return;
3095
+ const erasesOthers = tail.some((message) => message.role === "user" && countsAsThreadMessage2(message) && message.authorPrincipal !== undefined && !principalsEqual2(message.authorPrincipal, principal));
3096
+ if (erasesOthers) {
3097
+ throw new AgentRequestError2("not_thread_owner", "[Sixb] Only the thread's owner can rewind past another person's messages.");
3098
+ }
3099
+ }
3100
+ function assertRewindsWholeTurns(target, tail, rewoundRuns) {
3101
+ const removed = new Set(tail.map((message) => message.id));
3102
+ const cut = rewoundRuns.find((run) => !removed.has(run.triggerMessageId));
3103
+ if (!cut)
3104
+ return;
3105
+ throw new AgentRequestError2("message_not_editable", `[Sixb] Agent message '${target.id}' came in while the Agent was answering message '${cut.triggerMessageId}': edit that message instead.`);
3106
+ }
3107
+ async function listAllThreadMessagesFromSeq(agents, projectId, threadId, fromSeq) {
3108
+ const messages = [];
3109
+ const afterSeq = fromSeq - 1;
3110
+ for (;; ) {
3111
+ const page = await agents.messages.list({
3112
+ projectId,
3113
+ threadId,
3114
+ afterSeq,
3115
+ order: "asc",
3116
+ limit: 200,
3117
+ offset: messages.length
3118
+ });
3119
+ messages.push(...page.messages);
3120
+ if (!page.hasMore || page.messages.length === 0)
3121
+ return messages;
3122
+ }
3123
+ }
3124
+ async function listRewoundConversationRuns(agents, projectId, threadId, tail) {
3125
+ const removedMessageIds = new Set(tail.map((message) => message.id));
3126
+ const removedRunIds = new Set(tail.flatMap((message) => message.runId === null ? [] : [message.runId]));
3127
+ const found = [];
3128
+ for (let offset = 0;; ) {
3129
+ const page = await agents.runs.list({
3130
+ projectId,
3131
+ threadId,
3132
+ kinds: ["conversation"],
3133
+ order: "desc",
3134
+ limit: 100,
3135
+ offset
3136
+ });
3137
+ for (const run of page.runs) {
3138
+ if (run.kind === "conversation" && (removedMessageIds.has(run.triggerMessageId) || removedRunIds.has(run.id))) {
3139
+ found.push(run);
3140
+ }
3141
+ }
3142
+ offset += page.runs.length;
3143
+ if (!page.hasMore || page.runs.length === 0)
3144
+ return found;
3145
+ }
3146
+ }
3147
+ async function latestRetainedConversationRun(agents, projectId, threadId, tail) {
3148
+ const notRetained = new Set(tail.map((message) => message.id));
3149
+ for (let offset = 0;; ) {
3150
+ const page = await agents.runs.list({
3151
+ projectId,
3152
+ threadId,
3153
+ kinds: ["conversation"],
3154
+ order: "desc",
3155
+ limit: 50,
3156
+ offset
3157
+ });
3158
+ for (const run of page.runs) {
3159
+ if (run.kind !== "conversation" || notRetained.has(run.triggerMessageId))
3160
+ continue;
3161
+ if (await agents.messages.getById({ projectId, id: run.triggerMessageId }))
3162
+ return run;
3163
+ notRetained.add(run.triggerMessageId);
3164
+ }
3165
+ offset += page.runs.length;
3166
+ if (!page.hasMore || page.runs.length === 0)
3167
+ return;
3168
+ }
3169
+ }
2791
3170
  function isRetryableAgentRun2(run) {
2792
3171
  return run.status === "failed" || run.status === "cancelled" && run.finishReason === "interrupted";
2793
3172
  }
2794
3173
  async function retryAgentRun2(runtime, execution, models, failedRun, blobStorage) {
2795
- resolveExecutionScopeAuthorization(runtime.projectId, {
3174
+ const authority = resolveExecutionScopeAuthorization(runtime.projectId, {
2796
3175
  execution,
2797
3176
  authorization: runtime.runtimeAuthorization
2798
3177
  });
@@ -2810,6 +3189,9 @@ async function retryAgentRun2(runtime, execution, models, failedRun, blobStorage
2810
3189
  throw new AgentRequestError2("thread_not_found", `[Sixb] Agent thread '${failedRun.threadId}' was not found.`);
2811
3190
  }
2812
3191
  assertSandboxExecutionAvailable(thread);
3192
+ if (authority.type === "principal" && thread.runsOn === "computer" && !principalsEqual2(authority.context.principal, thread.ownerPrincipal)) {
3193
+ throw new AgentRequestError2("not_thread_owner", `[Sixb] Agent thread '${thread.id}' runs on its owner's computer, as them: only its owner can retry a turn in it.`);
3194
+ }
2813
3195
  const runId = createAgentRunId2();
2814
3196
  const durableExecution = await prepareDurableAgentExecution(runtime, execution, runId);
2815
3197
  await assertAiLimitPreflight(runtime, durableExecution);
@@ -2853,7 +3235,7 @@ async function retryAgentRun2(runtime, execution, models, failedRun, blobStorage
2853
3235
  return { run, ...jobId ? { jobId } : {}, createdThread: false };
2854
3236
  }
2855
3237
  var AGENT_MESSAGE_DELIVERIES2 = ["auto", "steer", "queue", "send_now"];
2856
- async function sendAgentMessage2(runtime, execution, models, input) {
3238
+ async function sendAgentMessage2(runtime, execution, models, input, blobStorage) {
2857
3239
  const delivery = input.delivery ?? "auto";
2858
3240
  const agents = requireAgentStorage(runtime);
2859
3241
  const projectId = runtime.projectId;
@@ -2904,12 +3286,12 @@ async function sendAgentMessage2(runtime, execution, models, input) {
2904
3286
  executionId: request.id
2905
3287
  });
2906
3288
  if (delivery === "send_now") {
2907
- await stopTurnBefore(runtime, execution, active);
3289
+ await stopTurnBefore(runtime, execution, active, blobStorage);
2908
3290
  }
2909
- await startIfThreadIdle(runtime, execution, thread.id);
3291
+ await startIfThreadIdle(runtime, execution, thread.id, blobStorage);
2910
3292
  return { kind: "inbox", item };
2911
3293
  }
2912
- async function promoteAgentInboxItem2(runtime, execution, input) {
3294
+ async function promoteAgentInboxItem2(runtime, execution, input, blobStorage) {
2913
3295
  const agents = requireAgentStorage(runtime);
2914
3296
  const projectId = runtime.projectId;
2915
3297
  const thread = await agents.threads.getById({ projectId, id: input.threadId });
@@ -2956,9 +3338,9 @@ async function promoteAgentInboxItem2(runtime, execution, input) {
2956
3338
  throw new AgentRequestError2("invalid_message", `[Sixb] Agent inbox item '${item.id}' is no longer waiting in thread '${thread.id}'.`);
2957
3339
  }
2958
3340
  if (input.immediate === true && turn) {
2959
- await stopTurnBefore(runtime, execution, turn);
3341
+ await stopTurnBefore(runtime, execution, turn, blobStorage);
2960
3342
  }
2961
- await startIfThreadIdle(runtime, execution, thread.id);
3343
+ await startIfThreadIdle(runtime, execution, thread.id, blobStorage);
2962
3344
  return updated;
2963
3345
  }
2964
3346
  async function withdrawAgentInboxItem2(runtime, execution, input) {
@@ -2992,7 +3374,7 @@ async function askedForTurn(runtime, run, principal) {
2992
3374
  const requester = (await runtime.storage.executions.getById({ projectId: runtime.projectId, id: run.executionId }))?.requestedBy;
2993
3375
  return requester !== undefined && principalsEqual2(requester, principal);
2994
3376
  }
2995
- async function stopTurnBefore(runtime, execution, active) {
3377
+ async function stopTurnBefore(runtime, execution, active, blobStorage) {
2996
3378
  if (active.status === "running") {
2997
3379
  await cancelAgentRun(runtime, active);
2998
3380
  return;
@@ -3000,9 +3382,9 @@ async function stopTurnBefore(runtime, execution, active) {
3000
3382
  await cancelAgentRun(runtime, active).catch(() => {
3001
3383
  return;
3002
3384
  });
3003
- await startQueuedAgentTurnFromInbox2(runtime, execution, active, { onlyImmediate: true });
3385
+ await startQueuedAgentTurnFromInbox2(runtime, execution, active, { onlyImmediate: true }, blobStorage);
3004
3386
  }
3005
- async function startIfThreadIdle(runtime, execution, threadId) {
3387
+ async function startIfThreadIdle(runtime, execution, threadId, blobStorage) {
3006
3388
  const agents = requireAgentStorage(runtime);
3007
3389
  const projectId = runtime.projectId;
3008
3390
  try {
@@ -3021,7 +3403,7 @@ async function startIfThreadIdle(runtime, execution, threadId) {
3021
3403
  if (last?.kind !== "conversation")
3022
3404
  return;
3023
3405
  const onlyImmediate = isAwaitingApprovalRun2(last) || !await turnAnsweredEveryMessage(agents, last);
3024
- await startQueuedAgentTurnFromInbox2(runtime, execution, last, { onlyImmediate });
3406
+ await startQueuedAgentTurnFromInbox2(runtime, execution, last, { onlyImmediate }, blobStorage);
3025
3407
  } catch (error) {
3026
3408
  console.error(`[Sixb] Could not start what waits in Agent thread '${threadId}'; the repair pass retries.`, error);
3027
3409
  }
@@ -3038,7 +3420,7 @@ function deliveredParts(input, delivery) {
3038
3420
  }
3039
3421
  return [...text, ...files];
3040
3422
  }
3041
- async function startQueuedAgentTurnFromInbox2(runtime, execution, finishedRun, input) {
3423
+ async function startQueuedAgentTurnFromInbox2(runtime, execution, finishedRun, input, blobStorage) {
3042
3424
  resolveExecutionScopeAuthorization(runtime.projectId, {
3043
3425
  execution,
3044
3426
  authorization: runtime.runtimeAuthorization
@@ -3063,7 +3445,10 @@ async function startQueuedAgentTurnFromInbox2(runtime, execution, finishedRun, i
3063
3445
  const runId = createAgentRunId2();
3064
3446
  const durableExecution = await prepareResumedExecution(runtime, execution, runId);
3065
3447
  await assertAiLimitPreflight(runtime, durableExecution);
3448
+ const documents = await waitingEditDocuments(runtime, blobStorage, thread, principal);
3066
3449
  let started;
3450
+ let rewind;
3451
+ let dropped;
3067
3452
  let superseded = [];
3068
3453
  try {
3069
3454
  started = await runtime.storage.transaction(async (tx) => {
@@ -3079,6 +3464,22 @@ async function startQueuedAgentTurnFromInbox2(runtime, execution, finishedRun, i
3079
3464
  });
3080
3465
  if (!item)
3081
3466
  return null;
3467
+ if (item.replacesMessageId !== undefined) {
3468
+ try {
3469
+ rewind = await rewindAgentThread(tx, agents, {
3470
+ projectId,
3471
+ thread,
3472
+ messageId: item.replacesMessageId,
3473
+ editor: item.authorPrincipal,
3474
+ documents
3475
+ });
3476
+ } catch (error) {
3477
+ if (!(error instanceof AgentRequestError2))
3478
+ throw error;
3479
+ dropped = { item, reason: error };
3480
+ return null;
3481
+ }
3482
+ }
3082
3483
  const inherited = await resolveAgentApprovalMode(agents, {
3083
3484
  projectId,
3084
3485
  principal,
@@ -3124,16 +3525,35 @@ async function startQueuedAgentTurnFromInbox2(runtime, execution, finishedRun, i
3124
3525
  }
3125
3526
  throw error;
3126
3527
  }
3528
+ if (dropped) {
3529
+ console.warn(`[Sixb] Dropped the edit of Agent message '${dropped.item.replacesMessageId}' waiting in thread '${thread.id}': it no longer applies.`, dropped.reason);
3530
+ }
3127
3531
  if (!started)
3128
3532
  return { status: "nothing" };
3129
- await announceAgentApprovals2(runtime.broker, superseded);
3533
+ await announceAgentThreadRewind(runtime, rewind, superseded);
3130
3534
  await publishRunActivity(runtime, started);
3131
3535
  await dispatchAgentRun(runtime, agents, runId);
3132
3536
  return { status: "started", run: started };
3133
3537
  }
3538
+ async function waitingEditDocuments(runtime, blobStorage, thread, principal) {
3539
+ if (!runtime.storage.artifacts || !blobStorage)
3540
+ return new Map;
3541
+ const agents = requireAgentStorage(runtime);
3542
+ const projectId = runtime.projectId;
3543
+ const waiting = await agents.inbox.list({ projectId, threadId: thread.id, includeClaimed: false });
3544
+ const next = waiting.filter((item) => item.immediate && principalsEqual2(item.authorPrincipal, principal)).sort((left, right) => left.seq - right.seq)[0];
3545
+ if (next?.replacesMessageId === undefined)
3546
+ return new Map;
3547
+ const target = await agents.messages.getById({ projectId, id: next.replacesMessageId });
3548
+ if (!target || target.threadId !== thread.id)
3549
+ return new Map;
3550
+ const tail = await listAllThreadMessagesFromSeq(agents, projectId, thread.id, target.seq);
3551
+ const rewoundRuns = await listRewoundConversationRuns(agents, projectId, thread.id, tail);
3552
+ return rewoundTurnDocuments(runtime, blobStorage, rewoundRuns, tail);
3553
+ }
3134
3554
  function queuedConversationRunSpec(thread, kept, item, approvalMode) {
3135
3555
  const model = item.spec?.model ?? kept.model;
3136
- const reasoning = item.spec?.reasoning ?? kept.reasoning;
3556
+ const reasoning = item.spec?.reasoning ?? (item.replacesMessageId === undefined ? kept.reasoning : undefined);
3137
3557
  const timeZone = item.timeZone ?? kept.timeZone;
3138
3558
  const locale = item.locale ?? kept.locale;
3139
3559
  return inPlace(thread, {
@@ -3244,8 +3664,8 @@ async function prepareResumedExecution(runtime, execution, runId) {
3244
3664
  return createInheritedAgentExecutionRecord2({ id: `exec_${randomUUID5()}`, parent, runId });
3245
3665
  }
3246
3666
  function inPlace(thread, spec) {
3247
- const { runsOn: _runsOn, ...rest } = spec;
3248
- return Object.freeze(thread.runsOn === undefined ? rest : { ...rest, runsOn: thread.runsOn });
3667
+ const { runsOn: _runsOn, computer: _computer, ...rest } = spec;
3668
+ return Object.freeze({ ...rest, ...turnPlace2(thread.runsOn, thread.computer) });
3249
3669
  }
3250
3670
  async function resumedConversationRunSpec(models, paused, approvalMode) {
3251
3671
  const kept = paused && models?.getByRef(paused.model) ? paused : await resolveConversationRunSpec({
@@ -3281,9 +3701,12 @@ function routedTurn(router, selection, input) {
3281
3701
  return;
3282
3702
  return { router, text: input.text ?? "" };
3283
3703
  }
3284
- async function routedConversationRunSpec(agents, input) {
3285
- const previous = input.threadId ? await latestConversationRun(agents, input.projectId, input.threadId) : undefined;
3286
- const choice = await input.router.choose(input.text, previous);
3704
+ async function routedConversationRunSpec(input) {
3705
+ const previous = input.previous && {
3706
+ run: input.previous,
3707
+ text: await messageWords(input.agents, input.projectId, input.previous.triggerMessageId)
3708
+ };
3709
+ const choice = await input.router.choose({ text: input.text, previous, place: input.place });
3287
3710
  return resolveConversationRunSpec({
3288
3711
  models: input.language,
3289
3712
  selection: { model: choice.model },
@@ -3291,6 +3714,14 @@ async function routedConversationRunSpec(agents, input) {
3291
3714
  tierProbabilities: choice.tierProbabilities
3292
3715
  });
3293
3716
  }
3717
+ async function messageWords(agents, projectId, messageId) {
3718
+ const message = await agents.messages.getById({ projectId, id: messageId });
3719
+ if (!message)
3720
+ return;
3721
+ const words = message.parts.flatMap((part) => part.type === "text" ? [part.text] : []).join(`
3722
+ `).trim();
3723
+ return words || undefined;
3724
+ }
3294
3725
  async function latestConversationRun(agents, projectId, threadId) {
3295
3726
  const { runs } = await agents.runs.list({
3296
3727
  projectId,
@@ -3323,17 +3754,20 @@ function assertAttachments(attachments) {
3323
3754
  }
3324
3755
  }
3325
3756
  function assertThreadAcceptsRun(thread, principal) {
3757
+ assertThreadAcceptsMessages(thread, principal);
3758
+ if (thread.activeRunId !== null) {
3759
+ throw new AgentRequestError2("active_run_exists", `[Sixb] Agent thread '${thread.id}' already has an active run '${thread.activeRunId}'.`);
3760
+ }
3761
+ }
3762
+ function assertThreadAcceptsMessages(thread, principal) {
3326
3763
  assertConversationThread2(thread);
3327
3764
  assertSandboxExecutionAvailable(thread);
3328
3765
  if (thread.runsOn === "computer" && !principalsEqual2(principal, thread.ownerPrincipal)) {
3329
3766
  throw new AgentRequestError2("not_thread_owner", `[Sixb] Agent thread '${thread.id}' runs on its owner's computer, as them: only its owner can message it. Shared with you, it is yours to read and follow.`);
3330
3767
  }
3331
- if (thread.activeRunId !== null) {
3332
- throw new AgentRequestError2("active_run_exists", `[Sixb] Agent thread '${thread.id}' already has an active run '${thread.activeRunId}'.`);
3333
- }
3334
3768
  }
3335
3769
  function assertSandboxExecutionAvailable(thread) {
3336
- if (thread.sandboxState && !["new", "ready"].includes(thread.sandboxState.status)) {
3770
+ if (thread.runsOn !== "computer" && thread.sandboxState && !["new", "ready"].includes(thread.sandboxState.status)) {
3337
3771
  throw new AgentRequestError2("sandbox_execution_unavailable", "[Sixb] Sandbox recovery is required before another run. Reload the thread, then resume its previous sandbox or recreate it to start fresh.");
3338
3772
  }
3339
3773
  }
@@ -3383,7 +3817,7 @@ async function resolveConversationRunSpec(input) {
3383
3817
  });
3384
3818
  }
3385
3819
  function requesterSettings(input) {
3386
- const timeZone = requestedSetting("timeZone", input.timeZone, canonicalTimeZone, "an IANA time zone");
3820
+ const timeZone = requestedSetting("timeZone", input.timeZone, canonicalTimeZone2, "an IANA time zone");
3387
3821
  const locale = requestedSetting("locale", input.locale, canonicalLocale, "a BCP 47 language tag");
3388
3822
  return {
3389
3823
  ...timeZone === undefined ? {} : { timeZone },
@@ -3734,7 +4168,7 @@ function createAgentRuntime(runtime, execution, models, decision, sandbox, secur
3734
4168
  try {
3735
4169
  if (!await rule.read(run.threadId))
3736
4170
  return { status: "closed" };
3737
- return await startQueuedAgentTurnFromInbox2(runtime, execution, run, options);
4171
+ return await startQueuedAgentTurnFromInbox2(runtime, execution, run, options, blobStorage);
3738
4172
  } catch (error) {
3739
4173
  console.error(`[Sixb] Could not start a queued message of Agent run '${run.id}'.`, error);
3740
4174
  return { status: "closed" };
@@ -3762,6 +4196,47 @@ function createAgentRuntime(runtime, execution, models, decision, sandbox, secur
3762
4196
  return preferences.get();
3763
4197
  }
3764
4198
  };
4199
+ const readViewer = () => principal.type === "user" ? principal : undefined;
4200
+ const lastRunView = async (run) => {
4201
+ const view = {
4202
+ id: run.id,
4203
+ status: run.status,
4204
+ ...run.finishReason === undefined ? {} : { finishReason: run.finishReason },
4205
+ ...run.error === undefined ? {} : { errorCode: run.error.code },
4206
+ ...run.completedAt === undefined ? {} : { completedAt: run.completedAt }
4207
+ };
4208
+ if (!agentRunEndedShort(run))
4209
+ return view;
4210
+ const execution = await runtime.storage.executions.getById({
4211
+ projectId: runtime.projectId,
4212
+ id: run.executionId
4213
+ });
4214
+ if (!execution?.requestedBy)
4215
+ return view;
4216
+ return { ...view, requestedBy: structuredClone(execution.requestedBy) };
4217
+ };
4218
+ const withThreadState = async (threads, viewer) => {
4219
+ const agents = runtime.storage.agents;
4220
+ if (!viewer || !agents || threads.length === 0)
4221
+ return threads;
4222
+ const threadIds = threads.map((thread) => thread.id);
4223
+ const [reads, runs] = await Promise.all([
4224
+ agents.reads.list({ projectId: runtime.projectId, threadIds, principal: viewer }),
4225
+ agents.runs.latestByThread({ projectId: runtime.projectId, threadIds })
4226
+ ]);
4227
+ const lastRuns = await Promise.all(runs.map(lastRunView));
4228
+ const readOf = new Map(reads.map((read) => [read.threadId, read]));
4229
+ const runOf = new Map(runs.map((run, index) => [run.threadId, lastRuns[index]]));
4230
+ return threads.map((thread) => {
4231
+ const read = readOf.get(thread.id);
4232
+ const lastRun = runOf.get(thread.id);
4233
+ return {
4234
+ ...thread,
4235
+ ...read === undefined ? {} : { read },
4236
+ ...lastRun === undefined ? {} : { lastRun }
4237
+ };
4238
+ });
4239
+ };
3765
4240
  const recoverSandbox = async (threadId, choice, transition) => {
3766
4241
  const readable = await rule.read(threadId);
3767
4242
  if (!readable)
@@ -3776,19 +4251,17 @@ function createAgentRuntime(runtime, execution, models, decision, sandbox, secur
3776
4251
  }
3777
4252
  const thread = readable.thread;
3778
4253
  const sandboxState = await transition(storage);
3779
- const [view] = await agentThreadViews(runtime, [{ ...thread, sandboxState }]);
4254
+ const [view] = await withThreadState(await agentThreadViews(runtime, [{ ...thread, sandboxState }]), readViewer());
3780
4255
  return view ?? thread;
3781
4256
  };
3782
- const ownedComputerThread = async (threadId) => {
4257
+ const ownedMovableThread = async (threadId) => {
3783
4258
  const readable = await rule.read(threadId);
3784
4259
  if (!readable)
3785
4260
  throw new AgentRequestError2("thread_not_found", "[Sixb] Agent thread not found.");
4261
+ assertConversationThread2(readable.thread);
3786
4262
  if (readable.access !== "owner") {
3787
4263
  throw new AgentRequestError2("not_thread_owner", `[Sixb] Only the owner of Agent thread '${threadId}' moves it.`);
3788
4264
  }
3789
- if (readable.thread.runsOn !== "computer") {
3790
- throw new AgentRequestError2("invalid_message", `[Sixb] Agent thread '${threadId}' runs in the cloud, on no computer.`);
3791
- }
3792
4265
  return readable.thread;
3793
4266
  };
3794
4267
  const moveThread = (thread, moves, move) => runtime.storage.transaction(async (tx) => {
@@ -3797,7 +4270,7 @@ function createAgentRuntime(runtime, execution, models, decision, sandbox, secur
3797
4270
  throw new AgentRequestError2("storage_unavailable", "[Sixb] Agent storage is not configured.");
3798
4271
  }
3799
4272
  const moved = await move(agents).catch((error) => {
3800
- throw error instanceof AgentStorageError2 && error.code === "active_run_exists" ? new AgentRequestError2("active_run_exists", "[Sixb] A turn is running on the computer: stop it, or let it end, first.") : error;
4273
+ throw error instanceof AgentStorageError2 && error.code === "active_run_exists" ? new AgentRequestError2("active_run_exists", thread.runsOn === "computer" ? "[Sixb] A turn is running on the computer: stop it, or let it end, first." : "[Sixb] A turn is running in the cloud: stop it, or let it end, first.") : error;
3801
4274
  });
3802
4275
  if (moves && await threadHoldsPausedTurn(agents, thread)) {
3803
4276
  throw new AgentRequestError2("active_run_exists", "[Sixb] A turn is waiting for your approval: answer or stop it first.");
@@ -3833,21 +4306,24 @@ function createAgentRuntime(runtime, execution, models, decision, sandbox, secur
3833
4306
  name: input.expectedSandboxName
3834
4307
  })),
3835
4308
  moveToComputer: async (threadId, computer) => {
3836
- const thread = await ownedComputerThread(threadId);
4309
+ const thread = await ownedMovableThread(threadId);
3837
4310
  const moves = movesComputerPlace2(thread, computer);
3838
4311
  const moved = await moveThread(thread, moves, (agents) => agents.threads.assignComputer({ projectId: runtime.projectId, id: threadId, computer }));
3839
4312
  if (moves)
3840
4313
  await announceThreadMoved(thread);
3841
- const [view] = await agentThreadViews(runtime, [moved]);
4314
+ const [view] = await withThreadState(await agentThreadViews(runtime, [moved]), readViewer());
3842
4315
  return view ?? moved;
3843
4316
  },
3844
4317
  moveToCloud: async (threadId) => {
3845
- const thread = await ownedComputerThread(threadId);
4318
+ const thread = await ownedMovableThread(threadId);
4319
+ if (thread.runsOn !== "computer") {
4320
+ throw new AgentRequestError2("invalid_message", `[Sixb] Agent thread '${threadId}' runs in the cloud, on no computer.`);
4321
+ }
3846
4322
  const { thread: moved, queued } = await moveThread(thread, true, (agents) => agents.threads.moveToCloud({ projectId: runtime.projectId, id: threadId }));
3847
4323
  if (queued)
3848
4324
  await dispatchAgentRun(runtime, requireAgents(), queued.id);
3849
4325
  await announceThreadMoved(thread);
3850
- const [view] = await agentThreadViews(runtime, [moved]);
4326
+ const [view] = await withThreadState(await agentThreadViews(runtime, [moved]), readViewer());
3851
4327
  return view ?? moved;
3852
4328
  },
3853
4329
  create: async (input) => {
@@ -3880,7 +4356,8 @@ function createAgentRuntime(runtime, execution, models, decision, sandbox, secur
3880
4356
  ...input.runsOn === undefined ? {} : { runsOn: input.runsOn },
3881
4357
  ...input.computer === undefined ? {} : { computer: input.computer }
3882
4358
  });
3883
- return { ...created, participants: [] };
4359
+ const [view] = await withThreadState([{ ...created, participants: [] }], readViewer());
4360
+ return view ?? { ...created, participants: [] };
3884
4361
  },
3885
4362
  listChildren: async (threadId, { runId } = {}) => {
3886
4363
  const thread = await getVisibleThreadRecord(threadId);
@@ -3911,10 +4388,36 @@ function createAgentRuntime(runtime, execution, models, decision, sandbox, secur
3911
4388
  ownerPrincipal: principal,
3912
4389
  sandbox
3913
4390
  });
3914
- const [view] = await agentThreadViews(runtime, [fork]);
4391
+ const [view] = await withThreadState(await agentThreadViews(runtime, [fork]), readViewer());
3915
4392
  return view ?? { ...fork, participants: [] };
3916
4393
  },
3917
- getById: getVisibleThreadRecord,
4394
+ getById: async (threadId) => {
4395
+ const thread = await getVisibleThreadRecord(threadId);
4396
+ if (!thread)
4397
+ return null;
4398
+ const [view] = await withThreadState([thread], readViewer());
4399
+ return view ?? null;
4400
+ },
4401
+ markRead: async (threadId, input = {}) => {
4402
+ const readable = await rule.read(threadId);
4403
+ if (!readable) {
4404
+ throw new AgentRequestError2("thread_not_found", "[Sixb] Agent thread not found.");
4405
+ }
4406
+ assertConversationThread2(readable.thread);
4407
+ const reader = settingsPrincipal();
4408
+ if (reader.type !== "user") {
4409
+ throw new AgentRequestError2("agent_not_found", "[Sixb] The project Agent is unavailable.");
4410
+ }
4411
+ if (input.throughMessageId !== undefined && input.throughMessageId.trim().length === 0) {
4412
+ throw new AgentRequestError2("invalid_message", "[Sixb] 'throughMessageId' must name a message of the thread.");
4413
+ }
4414
+ return requireAgents().reads.mark({
4415
+ projectId: runtime.projectId,
4416
+ threadId,
4417
+ principal: reader,
4418
+ ...input.throughMessageId === undefined ? {} : { throughMessageId: input.throughMessageId }
4419
+ });
4420
+ },
3918
4421
  list: async ({ sharedWithMe, ...input } = {}) => {
3919
4422
  assertNoAgentSelector(input);
3920
4423
  const none = { threads: [], hasMore: false, total: 0 };
@@ -3931,7 +4434,8 @@ function createAgentRuntime(runtime, execution, models, decision, sandbox, secur
3931
4434
  projectId: runtime.projectId,
3932
4435
  ...sharedWithMe && caller?.type === "user" ? { participantPrincipal: caller } : { ownerPrincipal: caller }
3933
4436
  });
3934
- return { ...result, threads: await agentThreadViews(runtime, result.threads) };
4437
+ const views = await agentThreadViews(runtime, result.threads);
4438
+ return { ...result, threads: await withThreadState(views, readViewer()) };
3935
4439
  },
3936
4440
  participants: {
3937
4441
  add: (threadId, users) => addAgentThreadParticipants(runtime, rule, security, threadId, users),
@@ -3956,7 +4460,7 @@ function createAgentRuntime(runtime, execution, models, decision, sandbox, secur
3956
4460
  if (!await getVisibleThreadRecord(threadId)) {
3957
4461
  throw new AgentRequestError2("thread_not_found", `[Sixb] Agent thread '${threadId}' not found.`);
3958
4462
  }
3959
- return promoteAgentInboxItem2(runtime, execution, { ...input, threadId, itemId });
4463
+ return promoteAgentInboxItem2(runtime, execution, { ...input, threadId, itemId }, blobStorage);
3960
4464
  },
3961
4465
  remove: async (threadId, itemId) => {
3962
4466
  if (!await getVisibleThreadRecord(threadId)) {
@@ -3975,7 +4479,7 @@ function createAgentRuntime(runtime, execution, models, decision, sandbox, secur
3975
4479
  if (!await getVisibleThreadRecord(input.threadId)) {
3976
4480
  throw new AgentRequestError2("thread_not_found", `[Sixb] Agent thread '${input.threadId}' not found.`);
3977
4481
  }
3978
- const result = await sendAgentMessage2(runtime, execution, turnModels, input);
4482
+ const result = await sendAgentMessage2(runtime, execution, turnModels, input, blobStorage);
3979
4483
  return result.kind === "turn" ? { ...result, run: await attachRunView(runtime, result.run) } : result;
3980
4484
  },
3981
4485
  request: async (input) => {
@@ -3994,6 +4498,19 @@ function createAgentRuntime(runtime, execution, models, decision, sandbox, secur
3994
4498
  });
3995
4499
  return { ...result, run: await attachRunView(runtime, result.run) };
3996
4500
  },
4501
+ editMessage: async (input) => {
4502
+ assertNoAgentSelector(input);
4503
+ const agent = getAgent();
4504
+ if (!agent) {
4505
+ throw new AgentRequestError2("agent_not_found", "[Sixb] The project Agent is unavailable.");
4506
+ }
4507
+ assertAuthorized2(runtime, { kind: "agent.run" });
4508
+ if (!await getVisibleThreadRecord(input.threadId)) {
4509
+ throw new AgentRequestError2("thread_not_found", `[Sixb] Agent thread '${input.threadId}' not found.`);
4510
+ }
4511
+ const result = await editAgentMessage2(runtime, execution, turnModels, { ...input, principal }, blobStorage);
4512
+ return result.kind === "turn" ? { ...result, run: await attachRunView(runtime, result.run) } : result;
4513
+ },
3997
4514
  retry: async (runId) => {
3998
4515
  const failedRun = await getControllableRun(runId, "retry");
3999
4516
  const agent = getAgent();
@@ -4696,7 +5213,7 @@ function lastState(changes) {
4696
5213
  }
4697
5214
 
4698
5215
  // src/events/execution.ts
4699
- function createEventsRuntime(runtime) {
5216
+ function createEventsRuntime(runtime, access) {
4700
5217
  const authority = resolveRuntimeAuthorizationForProject(runtime);
4701
5218
  const history = {
4702
5219
  existing: async (objects) => {
@@ -4720,7 +5237,8 @@ function createEventsRuntime(runtime) {
4720
5237
  case "unrestricted":
4721
5238
  return events;
4722
5239
  case "principal": {
4723
- const shown = await visibleByGrants(authority.context, events);
5240
+ const granted = await visibleByGrants(authority.context, events);
5241
+ const shown = await withoutHiddenSyncRuns(granted, access);
4724
5242
  if (!events.some((event) => event.topic === "artifacts"))
4725
5243
  return shown;
4726
5244
  const readable = await readableArtifactEvents(runtime, events);
@@ -4821,6 +5339,20 @@ async function readableArtifactEvents(runtime, events) {
4821
5339
  }
4822
5340
  return shown;
4823
5341
  }
5342
+ async function withoutHiddenSyncRuns(events, access) {
5343
+ const connectionOf = (event) => event.topic === "syncs" ? event.payload.connectionId : undefined;
5344
+ const syncIds = new Set(events.flatMap((event) => event.topic === "syncs" && connectionOf(event) !== undefined ? [event.payload.syncId] : []));
5345
+ if (syncIds.size === 0)
5346
+ return events;
5347
+ const visible = await access.visibleSyncConnectionIds([...syncIds]);
5348
+ if (visible === undefined)
5349
+ return events;
5350
+ const shown = new Set(visible);
5351
+ return events.filter((event) => {
5352
+ const connectionId = connectionOf(event);
5353
+ return connectionId === undefined || shown.has(connectionId);
5354
+ });
5355
+ }
4824
5356
  async function eventClearances(reader, events, clearance) {
4825
5357
  const kinds = new Map;
4826
5358
  for (const event of events) {
@@ -7254,17 +7786,38 @@ function createAudioRuntime(runtime, execution, catalog, session, blobs) {
7254
7786
  }
7255
7787
  const event = await recordTranscription(accounting, model, callId, result ?? {});
7256
7788
  signal.throwIfAborted();
7257
- if (typeof result?.output?.text !== "string") {
7258
- throw new TranscriptionModelResponseError2("[SixbModels] Invalid transcription response.", model.providerId, model.modelId, result ?? {});
7259
- }
7260
- return {
7261
- output: { text: result.output.text },
7262
- usage: event.usage,
7263
- cost: event.cost,
7264
- callId
7265
- };
7266
- }
7267
- };
7789
+ const output = transcriptOutput(result, model);
7790
+ return { output, usage: event.usage, cost: event.cost, callId };
7791
+ }
7792
+ };
7793
+ }
7794
+ function transcriptOutput(result, model) {
7795
+ const refuse = () => new TranscriptionModelResponseError2("[SixbModels] Invalid transcription response.", model.providerId, model.modelId, result ?? {});
7796
+ const output = result?.output;
7797
+ if (typeof output?.text !== "string")
7798
+ throw refuse();
7799
+ const words = output.words;
7800
+ if (words === undefined)
7801
+ return { text: output.text };
7802
+ if (!Array.isArray(words))
7803
+ throw refuse();
7804
+ const timed = [];
7805
+ for (const word of words) {
7806
+ const entry = word;
7807
+ if (typeof entry?.text !== "string" || !entry.text || !isMillisecond(entry.startMs) || !isMillisecond(entry.endMs) || entry.endMs < entry.startMs || entry.speaker !== undefined && (typeof entry.speaker !== "string" || !entry.speaker)) {
7808
+ throw refuse();
7809
+ }
7810
+ timed.push({
7811
+ text: entry.text,
7812
+ startMs: entry.startMs,
7813
+ endMs: entry.endMs,
7814
+ ...entry.speaker === undefined ? {} : { speaker: entry.speaker }
7815
+ });
7816
+ }
7817
+ return timed.length ? { text: output.text, words: timed } : { text: output.text };
7818
+ }
7819
+ function isMillisecond(value) {
7820
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
7268
7821
  }
7269
7822
  function prepareAudio(input, blobs) {
7270
7823
  if (typeof input === "object" && input !== null && "data" in input) {
@@ -9391,6 +9944,7 @@ function resolveLinkContext2(objCtx, linkId) {
9391
9944
  // src/objects/sdk/runtime-query-executor.ts
9392
9945
  function createRuntimeQueryExecutor(params) {
9393
9946
  const { ontology, objectReader } = params;
9947
+ const discovery = getQueryDiscovery(objectReader);
9394
9948
  return {
9395
9949
  async list(query, options) {
9396
9950
  try {
@@ -9425,10 +9979,10 @@ function createRuntimeQueryExecutor(params) {
9425
9979
  };
9426
9980
  },
9427
9981
  validate(query) {
9428
- return validateObjectQuery2(query, { ontology, normalize: false });
9982
+ return validateObjectQuery2(query, { ontology, discovery, normalize: false });
9429
9983
  },
9430
9984
  explain(query) {
9431
- return explainObjectQuery2(query, { ontology, normalize: false });
9985
+ return explainObjectQuery2(query, { ontology, discovery, normalize: false });
9432
9986
  }
9433
9987
  };
9434
9988
  }
@@ -10295,26 +10849,70 @@ function storageFailure(operation, cause) {
10295
10849
  });
10296
10850
  }
10297
10851
 
10852
+ // src/syncs/accounts.ts
10853
+ function createSyncAccountsRuntime(input) {
10854
+ const { runtime, execution, connections } = input;
10855
+ const latestByConnection = (syncIds, connectionIds) => runtime.storage.syncRuns ? runtime.storage.syncRuns.listLatestByConnection({
10856
+ projectId: runtime.projectId,
10857
+ syncIds,
10858
+ ...connectionIds === undefined ? {} : { connectionIds }
10859
+ }).then(({ runs }) => runs) : Promise.resolve([]);
10860
+ return {
10861
+ async list(connectorId) {
10862
+ const syncs = input.syncs().filter((sync) => sync.connector.id === connectorId && input.runnable(sync.id));
10863
+ const connector = syncs[0]?.connector;
10864
+ if (!connections || !connector || !isOAuthConnectorDefinition2(connector))
10865
+ return [];
10866
+ const accounts = (await connections.list(connector)).filter((connection) => mayRunConnection(runtime, execution, connection));
10867
+ const runs = await latestByConnection(syncs.map(({ id }) => id), accounts.map(({ id }) => id));
10868
+ return accounts.map((connection) => ({
10869
+ connection,
10870
+ latestRuns: runs.filter((run) => run.connectionId === connection.id)
10871
+ }));
10872
+ },
10873
+ async latestRuns(connectorId, connectionId) {
10874
+ const syncs = input.syncs().filter((sync) => sync.connector.id === connectorId);
10875
+ const connector = syncs[0]?.connector;
10876
+ if (!connections || !connector || !isOAuthConnectorDefinition2(connector))
10877
+ return [];
10878
+ const connection = (await connections.list(connector)).find(({ id }) => id === connectionId);
10879
+ if (!connection || !seesConnection(runtime, execution, connection))
10880
+ return [];
10881
+ return latestByConnection(syncs.map(({ id }) => id), [connection.id]);
10882
+ }
10883
+ };
10884
+ }
10885
+
10298
10886
  // src/syncs/execution.ts
10299
- function createSyncsRuntime(runtime, execution, source) {
10887
+ function createSyncsRuntime(runtime, execution, source, connections) {
10300
10888
  const authority = resolveRuntimeAuthorizationForProject(runtime);
10301
10889
  const allowed = (syncId) => isRuntimeAllowed2(runtime, { kind: "sync.run", syncId });
10302
10890
  const visibleIds = () => source.list().filter((sync) => allowed(sync.id)).map((sync) => sync.id);
10303
10891
  const historyFilterIds = () => authority.type === "unrestricted" ? undefined : authority.type === "principal" ? visibleIds() : [];
10892
+ const getById = (syncId) => {
10893
+ if (authority.type === "denied" || authority.type === "delegated")
10894
+ return null;
10895
+ const sync = source.getById(syncId);
10896
+ return sync && allowed(syncId) ? sync : null;
10897
+ };
10898
+ const visibleConnectionIds = (syncs) => visibleSyncConnectionIds(runtime, execution, syncs, connections);
10304
10899
  return {
10305
10900
  list: () => authority.type === "denied" || authority.type === "delegated" ? [] : source.list().filter((sync) => allowed(sync.id)),
10306
- getById: (syncId) => {
10307
- if (authority.type === "denied" || authority.type === "delegated")
10308
- return null;
10309
- const sync = source.getById(syncId);
10310
- return sync && allowed(syncId) ? sync : null;
10311
- },
10901
+ getById,
10902
+ accounts: createSyncAccountsRuntime({
10903
+ runtime,
10904
+ execution,
10905
+ syncs: () => source.list(),
10906
+ runnable: getById,
10907
+ ...connections === undefined ? {} : { connections }
10908
+ }),
10312
10909
  request: async (input) => {
10313
10910
  assertAuthorized2(runtime, { kind: "sync.run", syncId: input.syncId });
10314
10911
  const sync = source.getById(input.syncId);
10315
10912
  if (!sync)
10316
10913
  throw new SyncValidationError2(`[Sixb] Unknown sync '${input.syncId}'`);
10317
- return requestSyncRun2(runtime, execution, sync, input);
10914
+ const { syncId: _syncId, ...options } = input;
10915
+ return requestSyncRun2(runtime, execution, sync, options, connections);
10318
10916
  },
10319
10917
  runs: {
10320
10918
  getById: async (runId) => {
@@ -10324,30 +10922,41 @@ function createSyncsRuntime(runtime, execution, source) {
10324
10922
  projectId: runtime.projectId,
10325
10923
  id: runId
10326
10924
  }) ?? null;
10327
- return run && allowed(run.syncId) ? run : null;
10925
+ if (!run || !allowed(run.syncId))
10926
+ return null;
10927
+ const visible = await visibleConnectionIds([source.getById(run.syncId)]);
10928
+ const hidden = run.connectionId !== undefined && visible?.includes(run.connectionId) === false;
10929
+ return hidden ? null : run;
10328
10930
  },
10329
- list: (input = {}) => {
10931
+ list: async (input = {}) => {
10330
10932
  if (authority.type === "denied" || authority.type === "delegated") {
10331
- return Promise.resolve({ runs: [], hasMore: false, total: 0 });
10933
+ return { runs: [], hasMore: false, total: 0 };
10332
10934
  }
10333
10935
  const storage = runtime.storage.syncRuns;
10334
10936
  if (!storage)
10335
- return Promise.resolve({ runs: [], hasMore: false, total: 0 });
10937
+ return { runs: [], hasMore: false, total: 0 };
10938
+ const syncs = input.syncId === undefined ? source.list().filter((sync) => allowed(sync.id)) : [getById(input.syncId)];
10939
+ const visible = await visibleConnectionIds(syncs);
10336
10940
  return storage.list({
10337
10941
  ...input,
10338
10942
  syncIds: historyFilterIds(),
10943
+ ...visible === undefined ? {} : { visibleConnectionIds: visible },
10339
10944
  projectId: runtime.projectId
10340
10945
  });
10341
10946
  },
10342
- listLatest: (syncIds) => {
10343
- if (authority.type === "denied" || authority.type === "delegated") {
10344
- return Promise.resolve({ runs: [] });
10345
- }
10947
+ listLatest: async (syncIds) => {
10948
+ if (authority.type === "denied" || authority.type === "delegated")
10949
+ return { runs: [] };
10346
10950
  const storage = runtime.storage.syncRuns;
10347
- if (!storage || syncIds.length === 0)
10348
- return Promise.resolve({ runs: [] });
10349
10951
  const allowedIds = syncIds.filter(allowed);
10350
- return allowedIds.length === 0 ? Promise.resolve({ runs: [] }) : storage.listLatestBySyncIds({ projectId: runtime.projectId, syncIds: allowedIds });
10952
+ if (!storage || allowedIds.length === 0)
10953
+ return { runs: [] };
10954
+ const visible = await visibleConnectionIds(allowedIds.map((syncId) => source.getById(syncId)));
10955
+ return storage.listLatestBySyncIds({
10956
+ projectId: runtime.projectId,
10957
+ syncIds: allowedIds,
10958
+ ...visible === undefined ? {} : { visibleConnectionIds: visible }
10959
+ });
10351
10960
  }
10352
10961
  }
10353
10962
  };
@@ -10581,6 +11190,7 @@ function isBoundSixb(value) {
10581
11190
  }
10582
11191
  function createExecutionFacades(runtime, execution, dependencies) {
10583
11192
  const actions = createActionsRuntime(runtime, execution);
11193
+ const syncConnections = createSyncConnections(dependencies.connectorService);
10584
11194
  const workflows = createWorkflowsRuntime(runtime, execution, dependencies.definitions.workflows);
10585
11195
  const session = runtime.modelExecution ?? new ModelExecutionSession(runtime, execution);
10586
11196
  const agent = createAgentRuntime(runtime, execution, dependencies.definitions.models, createDecisionRuntime(runtime, execution, dependencies.definitions.models, session, "agent.run"), dependencies.sandbox, dependencies.definitions.security, dependencies.blobStorage);
@@ -10592,7 +11202,7 @@ function createExecutionFacades(runtime, execution, dependencies) {
10592
11202
  actions,
10593
11203
  datasets: createDatasetsRuntime(runtime, execution, dependencies.definitions.datasets, dependencies.lakeStorage, dependencies.blobStorage, dependencies.datasetVersionMarkings, dependencies.datasetIngest),
10594
11204
  workflows,
10595
- syncs: createSyncsRuntime(runtime, execution, dependencies.definitions.syncs),
11205
+ syncs: createSyncsRuntime(runtime, execution, dependencies.definitions.syncs, syncConnections),
10596
11206
  pipelines: createPipelinesRuntime(runtime, execution, dependencies.definitions.pipelines),
10597
11207
  projections: createProjectionsRuntime(runtime, dependencies.definitions.projections),
10598
11208
  rules: createRulesRuntime(runtime, dependencies.definitions.rules),
@@ -10606,7 +11216,9 @@ function createExecutionFacades(runtime, execution, dependencies) {
10606
11216
  canViewAgentRun: async (id) => await agent.runs.getById(id) !== null
10607
11217
  }, dependencies.blobStorage),
10608
11218
  aiUsage: createAiUsageRuntime(runtime, dependencies.definitions.security),
10609
- events: createEventsRuntime(runtime),
11219
+ events: createEventsRuntime(runtime, {
11220
+ visibleSyncConnectionIds: (syncIds) => visibleSyncConnectionIds(runtime, execution, syncIds.map((syncId) => dependencies.definitions.syncs.getById(syncId)), syncConnections)
11221
+ }),
10610
11222
  logs: createLogsRuntime(runtime, dependencies.logging),
10611
11223
  activity: createActivityRuntime(runtime, dependencies.activity),
10612
11224
  schedules: createSchedulesRuntime(runtime, dependencies.definitions.schedules),
@@ -12324,6 +12936,6 @@ function snapshotActionRequest(input) {
12324
12936
  ...onRequested === undefined ? {} : { onRequested }
12325
12937
  };
12326
12938
  }
12327
- export { defineAction2, param2, optional2, ActionRegistry2, bindRequestClient, bindModelExecutionAttempt, canInheritAgentRequestAuthorization2, createAgentExecutionRecord2, createInheritedAgentExecutionRecord2, bindDurableAgentExecution2, bindAgentRunRequestExecution2, bindAgentModelExecution2, restoreAgentExecutionScope2, assertAgentExecutionRecord2, resumeDecidedAgentTurn2, agentRunApprovalMode2, holdAgentApprovalCall2, approvalCallSummary2, listChildApprovalsAwaiting2, isAwaitingApprovalRun2, isPausedSubagentRun2, AGENT_APPROVAL_EXECUTION_LEASE_MS2, turnResumeReadiness2, turnPausesOnHeldCalls2, hasActiveChildren2, listTurnApprovals2, stopAgentTurn2, announceAgentApprovals2, agentApprovalCallers2, AgentRunScopeError2, resolveAgentRunExecutionScope2, createAgentApprovalExecutor, registerAgentApprovalExecutor, getAgentApprovalExecutor2, requestAgentRunCancel2, cancelQueuedRun, AGENT_QUESTION_LIMITS2, agentQuestionsText2, isChildAskTool2, isAwaitingAnswerRun2, deferredChildQuestion2, listSubagentThreadRuns2, subagentSandboxFiles2, assertTurnModelRouting, registerAgentQueuedTurn2, startQueuedAgentTurn2, DEFAULT_PROJECT_LOCALE, DEFAULT_PROJECT_TIME_ZONE, canonicalLocale, canonicalTimeZone, resolveAgentContextParts2, agentRunQueueJobId2, workflowAgentNodeQueueJobId2, dispatchQueuedAgentRuns2, assertNoAgentDefinitions, turnAnsweredEveryMessage, requestAgentRun2, isRetryableAgentRun2, retryAgentRun2, AGENT_MESSAGE_DELIVERIES2, sendAgentMessage2, promoteAgentInboxItem2, withdrawAgentInboxItem2, startQueuedAgentTurnFromInbox2, WorkflowDefinitionError2, WorkflowValidationError2, assertNonEmpty, isStepDefinition2, isAgentStepDefinition2, isInterventionDefinition2, isWorkflowDefinition2, validateWorkflowDefinition2, validateWorkflowsAtStartup2, validateWorkflowAgentStepGroupReferences2, validateWorkflowInput2, validateWorkflowStepInput2, validateWorkflowStepOutput2, validateWorkflowInterventionInput2, validateWorkflowInterventionResponse2, validateWorkflowInterventionDefaultResponse2, assertAgentStepSandbox, validateWorkflowAgentStepInput2, validateWorkflowAgentStepOutput2, snapshotWorkflowAgentStepInput2, snapshotWorkflowAgentStepOutput2, snapshotWorkflowInput2, snapshotWorkflowStepInput2, snapshotWorkflowStepOutput2, snapshotWorkflowInterventionInput2, snapshotWorkflowInterventionResponse2, snapshotWorkflowInterventionDefaultResponse2, snapshotWorkflowActionInput2, WorkflowRunDispatcher2, requestWorkflowRun2, prepareBoundActionRequest2, prepareBoundWorkflowRequest2, runModelLoop2, requestAction2, ObjectError2, removeLink2, upsertLink2, upsertLinkBatch2, deleteObject2, restoreObject2, upsertObject2, upsertObjectBatch2, writeTelemetryBatch2, appendTelemetryBatch2, getTelemetryHistoryBatch2, requireLinkDefinition2, resolveObjectContext2, resolveLinkContext2, createObjectSet2, exports_service, ShareError2, createBoundSixb, isBoundSixb, bindDurablePrimitiveExecution2, ACTION_RUN_DRAIN_TIMEOUT_MS2, ActionRunExecutor, registerActionRunExecutor, drainActionRuns2, requestAction3 };
12939
+ export { defineAction2, param2, optional2, ActionRegistry2, bindRequestClient, bindModelExecutionAttempt, canInheritAgentRequestAuthorization2, createAgentExecutionRecord2, createInheritedAgentExecutionRecord2, bindDurableAgentExecution2, bindAgentRunRequestExecution2, bindAgentModelExecution2, restoreAgentExecutionScope2, assertAgentExecutionRecord2, resumeDecidedAgentTurn2, agentRunApprovalMode2, holdAgentApprovalCall2, approvalCallSummary2, listChildApprovalsAwaiting2, isAwaitingApprovalRun2, isPausedSubagentRun2, AGENT_APPROVAL_EXECUTION_LEASE_MS2, turnResumeReadiness2, turnPausesOnHeldCalls2, hasActiveChildren2, listTurnApprovals2, stopAgentTurn2, announceAgentApprovals2, agentApprovalCallers2, AgentRunScopeError2, resolveAgentRunExecutionScope2, createAgentApprovalExecutor, registerAgentApprovalExecutor, getAgentApprovalExecutor2, requestAgentRunCancel2, cancelQueuedRun, AGENT_QUESTION_LIMITS2, agentQuestionsText2, isChildAskTool2, isAwaitingAnswerRun2, deferredChildQuestion2, listSubagentThreadRuns2, subagentSandboxFiles2, assertTurnModelRouting, registerAgentQueuedTurn2, startQueuedAgentTurn2, resolveAgentContextParts2, agentRunQueueJobId2, workflowAgentNodeQueueJobId2, dispatchQueuedAgentRuns2, assertNoAgentDefinitions, turnAnsweredEveryMessage, requestAgentRun2, isEditableAgentMessage2, editAgentMessage2, isRetryableAgentRun2, retryAgentRun2, AGENT_MESSAGE_DELIVERIES2, sendAgentMessage2, promoteAgentInboxItem2, withdrawAgentInboxItem2, startQueuedAgentTurnFromInbox2, WorkflowDefinitionError2, WorkflowValidationError2, assertNonEmpty, isStepDefinition2, isAgentStepDefinition2, isInterventionDefinition2, isWorkflowDefinition2, validateWorkflowDefinition2, validateWorkflowsAtStartup2, validateWorkflowAgentStepGroupReferences2, validateWorkflowInput2, validateWorkflowStepInput2, validateWorkflowStepOutput2, validateWorkflowInterventionInput2, validateWorkflowInterventionResponse2, validateWorkflowInterventionDefaultResponse2, assertAgentStepSandbox, validateWorkflowAgentStepInput2, validateWorkflowAgentStepOutput2, snapshotWorkflowAgentStepInput2, snapshotWorkflowAgentStepOutput2, snapshotWorkflowInput2, snapshotWorkflowStepInput2, snapshotWorkflowStepOutput2, snapshotWorkflowInterventionInput2, snapshotWorkflowInterventionResponse2, snapshotWorkflowInterventionDefaultResponse2, snapshotWorkflowActionInput2, WorkflowRunDispatcher2, requestWorkflowRun2, prepareBoundActionRequest2, prepareBoundWorkflowRequest2, runModelLoop2, requestAction2, ObjectError2, removeLink2, upsertLink2, upsertLinkBatch2, deleteObject2, restoreObject2, upsertObject2, upsertObjectBatch2, writeTelemetryBatch2, appendTelemetryBatch2, getTelemetryHistoryBatch2, requireLinkDefinition2, resolveObjectContext2, resolveLinkContext2, createObjectSet2, exports_service, ShareError2, createBoundSixb, isBoundSixb, bindDurablePrimitiveExecution2, ACTION_RUN_DRAIN_TIMEOUT_MS2, ActionRunExecutor, registerActionRunExecutor, drainActionRuns2, requestAction3 };
12328
12940
 
12329
- //# debugId=769CBCF3562DBFDA64756E2164756E21
12941
+ //# debugId=F06C1A95F7E3542964756E2164756E21