@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
@@ -7,6 +7,7 @@ import { assertAuthorized } from "../authorization"
7
7
  import type { FileRef } from "../blob-storage"
8
8
  import type { BlobStorage } from "../blob-storage/types"
9
9
  import { isValidFileRef } from "../blob-storage/validation"
10
+ import { canonicalTimeZone } from "../calendar"
10
11
  import {
11
12
  canInheritAgentRequestAuthorization,
12
13
  createInheritedAgentExecutionRecord,
@@ -22,12 +23,13 @@ import type {
22
23
  } from "../models"
23
24
  import { isModelReasoning, modelReasoningSupportIssue } from "../models/language-model"
24
25
  import { resolveLanguageModel } from "../models/resolve"
25
- import { canonicalLocale, canonicalTimeZone } from "../runtime/locale"
26
+ import { canonicalLocale } from "../runtime/locale"
26
27
  import type { SixbRuntimeContext } from "../runtime/types"
27
28
  import {
28
29
  type AgentApprovalMode,
29
30
  type AgentApprovalRecord,
30
31
  type AgentInboxItemRecord,
32
+ type AgentMessageRecord,
31
33
  type AgentStorage,
32
34
  AgentStorageError,
33
35
  type AgentThreadComputer,
@@ -35,6 +37,7 @@ import {
35
37
  type ConversationAgentRunRecord,
36
38
  type ConversationAgentRunSpec,
37
39
  } from "../storage/agents"
40
+ import { type AgentTurnPlace, countsAsThreadMessage, turnPlace } from "../storage/agents/provider"
38
41
  import {
39
42
  aiLimitSubjectsFromAttribution,
40
43
  aiUsageLimitExceededError,
@@ -42,7 +45,9 @@ import {
42
45
  applicableAiLimitPolicyStatuses,
43
46
  } from "../storage/ai-limits/enforcement"
44
47
  import type { AiLimitPolicyStatus } from "../storage/ai-limits/types"
48
+ import type { PublishedArtifactVersion } from "../storage/artifacts/types"
45
49
  import type { ExecutionRecord } from "../storage/executions"
50
+ import type { Storage } from "../storage/types"
46
51
  import {
47
52
  type AgentTurnReadiness,
48
53
  announceAgentApprovals,
@@ -121,6 +126,31 @@ export interface RequestAgentRunInput {
121
126
  readonly principal?: Principal
122
127
  }
123
128
 
129
+ /** An earlier message to replace, and the turn its new text starts. */
130
+ export interface EditAgentMessageInput {
131
+ /** The conversation thread containing the message to edit. */
132
+ readonly threadId: string
133
+ /** The existing user message to replace and rewind from. */
134
+ readonly messageId: string
135
+ /** Updated user text. Omitted when attachments are the whole message. */
136
+ readonly text?: string
137
+ /** Blob-backed files attached to the edited message. */
138
+ readonly attachments?: readonly FileRef[]
139
+ /** Structured page/object context snapshotted onto the edited user message. */
140
+ readonly context?: readonly AgentContextEntryInput[]
141
+ /** Configured language model selected for the re-run. Omitted uses routing or the agent default. */
142
+ readonly model?: LanguageModelRef
143
+ /** Reasoning effort or token budget for the re-run. Omitted uses the model's default. */
144
+ readonly reasoning?: AgentReasoning
145
+ readonly timeZone?: string
146
+ readonly locale?: string
147
+ readonly approvalMode?: AgentApprovalMode
148
+ /** Explicit id for the replacement user message. Defaults to a generated id. */
149
+ readonly nextMessageId?: string
150
+ /** Caller principal for privileged integrations; scoped runtimes use their authorization principal. */
151
+ readonly principal?: Principal
152
+ }
153
+
124
154
  /** What a turn's model is chosen from. */
125
155
  export interface AgentRequestModels {
126
156
  readonly language?: LanguageModelCatalog
@@ -206,24 +236,26 @@ export async function requestAgentRun(
206
236
  (await resolveAgentApprovalMode(agents, { projectId, principal, threadId: existingThread?.id }))
207
237
  .approvalMode
208
238
 
239
+ const place = turnPlace(runsOn, existingThread ? existingThread.computer : input.computer)
240
+
209
241
  // Last before anything is written, so a message the checks above refuse never reaches the
210
242
  // decision model. Concurrent messages to an idle thread can still each ask before one of them is
211
243
  // refused with `active_run_exists` below.
212
244
  const selected =
213
245
  "router" in requested
214
- ? await routedConversationRunSpec(agents, {
246
+ ? await routedConversationRunSpec({
215
247
  ...requested,
248
+ agents,
216
249
  projectId,
217
- threadId: existingThread?.id,
250
+ previous: existingThread
251
+ ? await latestConversationRun(agents, projectId, existingThread.id)
252
+ : undefined,
253
+ place,
218
254
  settings,
219
255
  language: models.language,
220
256
  })
221
257
  : requested
222
- const spec: ConversationAgentRunSpec = Object.freeze({
223
- ...selected,
224
- approvalMode,
225
- ...(runsOn === undefined ? {} : { runsOn }),
226
- })
258
+ const spec: ConversationAgentRunSpec = Object.freeze({ ...selected, approvalMode, ...place })
227
259
 
228
260
  const createdThread = existingThread === null
229
261
  const thread =
@@ -301,6 +333,610 @@ export async function requestAgentRun(
301
333
  }
302
334
  }
303
335
 
336
+ /** Whether a stored message is a user-authored prompt that can be edited in place. */
337
+ export function isEditableAgentMessage(
338
+ message: Pick<AgentMessageRecord, "role" | "parts">
339
+ ): boolean {
340
+ if (message.role !== "user") return false
341
+ if (message.parts.some((part) => part.type === "continuation")) return false
342
+ return countsAsThreadMessage(message)
343
+ }
344
+
345
+ /**
346
+ * Edit an earlier user message in place: the thread loses that message and everything after it,
347
+ * and the edited message starts a new turn.
348
+ *
349
+ * On an idle thread the rewind and the new turn are one transaction. While a turn runs, the edit
350
+ * waits in the thread's inbox, sent now: the turn stops, and its end rewinds the thread and starts
351
+ * the edited message (see `startQueuedAgentTurnFromInbox`), so nothing the stopped turn still
352
+ * writes lands after the edit.
353
+ *
354
+ * Historical `agent_runs` and `executions` remain intact for AI usage and cost accounting.
355
+ */
356
+ export async function editAgentMessage(
357
+ runtime: SixbRuntimeContext,
358
+ execution: ExecutionContext,
359
+ models: AgentRequestModels,
360
+ input: EditAgentMessageInput,
361
+ blobStorage?: RewindBlobStorage
362
+ ): Promise<SendAgentMessageResult> {
363
+ const authority = resolveExecutionScopeAuthorization(runtime.projectId, {
364
+ execution,
365
+ authorization: runtime.runtimeAuthorization,
366
+ })
367
+ assertNoAgentSelector(input)
368
+ assertAuthorized(runtime, { kind: "agent.run" })
369
+ assertRequestAuthorityCanRunAgent(runtime)
370
+
371
+ const trigger = triggerParts(input)
372
+ const selection = { model: input.model, reasoning: input.reasoning }
373
+ const settings = requesterSettings(input)
374
+ if (input.approvalMode !== undefined) assertAgentApprovalMode(input.approvalMode)
375
+
376
+ const routed = routedTurn(models.router, selection, input)
377
+ const requested =
378
+ routed ?? (await resolveConversationRunSpec({ models: models.language, selection, settings }))
379
+ assertAttachments(input.attachments)
380
+
381
+ const contextParts = await resolveAgentContextParts(runtime, input.context)
382
+ const agents = requireAgentStorage(runtime)
383
+ const projectId = runtime.projectId
384
+ const principal =
385
+ authority.type === "principal"
386
+ ? authority.context.principal
387
+ : (input.principal ?? SYSTEM_PRINCIPAL)
388
+
389
+ const thread = await agents.threads.getById({ projectId, id: input.threadId })
390
+ if (!thread) {
391
+ throw new AgentRequestError(
392
+ "thread_not_found",
393
+ `[Sixb] Agent thread '${input.threadId}' not found.`
394
+ )
395
+ }
396
+ assertThreadAcceptsMessages(thread, principal)
397
+
398
+ const target = await agents.messages.getById({ projectId, id: input.messageId })
399
+ if (!target || target.threadId !== thread.id) {
400
+ throw new AgentRequestError(
401
+ "message_not_found",
402
+ `[Sixb] Agent message '${input.messageId}' not found in thread '${thread.id}'.`
403
+ )
404
+ }
405
+ assertEditableMessageAuthority(thread, target, principal)
406
+
407
+ const tail = await listAllThreadMessagesFromSeq(agents, projectId, thread.id, target.seq)
408
+ assertParticipantCanRewindTail(thread, tail, principal)
409
+ const rewoundRuns = await listRewoundConversationRuns(agents, projectId, thread.id, tail)
410
+ assertRewindsWholeTurns(target, tail, rewoundRuns)
411
+
412
+ const approvalMode =
413
+ input.approvalMode ??
414
+ (await resolveAgentApprovalMode(agents, { projectId, principal, threadId: thread.id }))
415
+ .approvalMode
416
+
417
+ // The edited turn runs where the thread runs now, like any message sent to it, and is routed
418
+ // against the turn it continues: the newest one the rewind keeps.
419
+ const place = turnPlace(thread.runsOn, thread.computer)
420
+ const selected =
421
+ "router" in requested
422
+ ? await routedConversationRunSpec({
423
+ ...requested,
424
+ agents,
425
+ projectId,
426
+ previous: await latestRetainedConversationRun(agents, projectId, thread.id, tail),
427
+ place,
428
+ settings,
429
+ language: models.language,
430
+ })
431
+ : requested
432
+ const spec: ConversationAgentRunSpec = Object.freeze({ ...selected, approvalMode, ...place })
433
+
434
+ const edit: AgentMessageEdit = {
435
+ target,
436
+ messageId: input.nextMessageId ?? createAgentMessageId(),
437
+ authorPrincipal: principal,
438
+ parts: [
439
+ ...contextParts,
440
+ ...trigger,
441
+ ...(input.attachments ?? []).map((fileRef) => ({ type: "file" as const, fileRef })),
442
+ ],
443
+ }
444
+
445
+ // Checked before anything stops: an edit the budget refuses must not end the turn it replaces.
446
+ const runId = createAgentRunId()
447
+ const durableExecution = await prepareDurableAgentExecution(runtime, execution, runId)
448
+ await assertAiLimitPreflight(runtime, durableExecution)
449
+
450
+ if (thread.activeRunId !== null) {
451
+ const item = await deferAgentMessageEdit(runtime, execution, thread, edit, {
452
+ spec,
453
+ settings,
454
+ blobStorage,
455
+ })
456
+ return { kind: "inbox", item }
457
+ }
458
+
459
+ const documents = await rewoundTurnDocuments(runtime, blobStorage, rewoundRuns, tail)
460
+
461
+ let run: ConversationAgentRunRecord
462
+ let rewind: AgentThreadRewind | undefined
463
+ let superseded: readonly AgentApprovalRecord[] = []
464
+ try {
465
+ run = await runtime.storage.transaction(async (tx) => {
466
+ const txAgents = tx.agents
467
+ if (!txAgents) {
468
+ throw new AgentRequestError(
469
+ "storage_unavailable",
470
+ "[Sixb] Agent storage is not configured."
471
+ )
472
+ }
473
+
474
+ rewind = await rewindAgentThread(tx, txAgents, {
475
+ projectId,
476
+ thread,
477
+ messageId: edit.target.id,
478
+ editor: principal,
479
+ documents,
480
+ })
481
+
482
+ await tx.executions.create(durableExecution)
483
+ const reported = await reportAgentApprovals(txAgents, {
484
+ projectId,
485
+ threadId: thread.id,
486
+ messageId: edit.messageId,
487
+ })
488
+ superseded = reported.superseded
489
+
490
+ await txAgents.messages.append({
491
+ id: edit.messageId,
492
+ projectId,
493
+ threadId: thread.id,
494
+ runId: null,
495
+ role: "user",
496
+ parts: [...reported.parts, ...edit.parts],
497
+ authorPrincipal: principal,
498
+ })
499
+
500
+ return txAgents.runs.create({
501
+ id: runId,
502
+ projectId,
503
+ executionId: durableExecution.id,
504
+ threadId: thread.id,
505
+ triggerMessageId: edit.messageId,
506
+ spec,
507
+ })
508
+ })
509
+ } catch (error) {
510
+ if (error instanceof AgentStorageError && error.code === "active_run_exists") {
511
+ throw new AgentRequestError("active_run_exists", error.message)
512
+ }
513
+ throw error
514
+ }
515
+
516
+ await announceAgentThreadRewind(runtime, rewind, superseded)
517
+ await publishRunActivity(runtime, run)
518
+ await dispatchAgentRun(runtime, agents, runId)
519
+ return { kind: "turn", run, createdThread: false }
520
+ }
521
+
522
+ /** Where a rewind reads the documents that restore the canvases a rewound turn wrote. */
523
+ type RewindBlobStorage = Pick<BlobStorage, "open" | "put">
524
+
525
+ /** An edit of an earlier message: the message it replaces, and the one that replaces it. */
526
+ interface AgentMessageEdit {
527
+ readonly target: AgentMessageRecord
528
+ readonly messageId: string
529
+ readonly authorPrincipal: Principal
530
+ readonly parts: readonly AgentMessagePart[]
531
+ }
532
+
533
+ /**
534
+ * Stop the running turn so the edit starts after it: the edit waits in the thread's inbox, sent
535
+ * now, and the turn's end rewinds the thread and starts it. Stopping a turn is for whoever may: the
536
+ * person who asked for it, or the thread's owner. A newer edit replaces one still waiting.
537
+ */
538
+ async function deferAgentMessageEdit(
539
+ runtime: SixbRuntimeContext,
540
+ execution: ExecutionContext,
541
+ thread: AgentThreadRecord,
542
+ edit: AgentMessageEdit,
543
+ options: {
544
+ readonly spec: ConversationAgentRunSpec
545
+ readonly settings: RequesterSettings
546
+ readonly blobStorage: RewindBlobStorage | undefined
547
+ }
548
+ ): Promise<AgentInboxItemRecord> {
549
+ const { spec, settings } = options
550
+ const agents = requireAgentStorage(runtime)
551
+ const projectId = runtime.projectId
552
+ const active = thread.activeRunId
553
+ ? await agents.runs.getById({ projectId, id: thread.activeRunId })
554
+ : null
555
+ if (active?.kind !== "conversation") {
556
+ throw new AgentRequestError(
557
+ "active_run_exists",
558
+ `[Sixb] Agent thread '${thread.id}' already has an active run '${thread.activeRunId}'.`
559
+ )
560
+ }
561
+ // The turn's end starts the edit as the person who sent it: a request no person sent, with sign-in
562
+ // off, leaves no one to start it as.
563
+ if (!execution.requestedBy) {
564
+ throw new AgentRequestError(
565
+ "active_run_exists",
566
+ `[Sixb] Agent thread '${thread.id}' is answering, and an edit without a signed-in sender cannot wait for it: stop the answer, then edit.`
567
+ )
568
+ }
569
+
570
+ const mayStop =
571
+ principalsEqual(edit.authorPrincipal, thread.ownerPrincipal) ||
572
+ (await askedForTurn(runtime, active, edit.authorPrincipal))
573
+ if (!mayStop) {
574
+ throw new AgentRequestError(
575
+ "not_run_requester",
576
+ `[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.`
577
+ )
578
+ }
579
+
580
+ // The request that sends it is recorded with it: the turn that starts it once this request is
581
+ // gone runs as that request's child.
582
+ const request = await ensureExecutionRecord(
583
+ runtime.storage.executions,
584
+ executionRecordInputFromRuntime({
585
+ execution,
586
+ runtimeAuthorization: runtime.runtimeAuthorization,
587
+ })
588
+ )
589
+
590
+ for (const waiting of await agents.inbox.list({ projectId, threadId: thread.id })) {
591
+ if (
592
+ waiting.replacesMessageId !== undefined &&
593
+ principalsEqual(waiting.authorPrincipal, edit.authorPrincipal)
594
+ ) {
595
+ await agents.inbox.remove({ projectId, threadId: thread.id, id: waiting.id })
596
+ }
597
+ }
598
+
599
+ const { item } = await agents.inbox.enqueue({
600
+ id: createAgentInboxItemId(),
601
+ projectId,
602
+ threadId: thread.id,
603
+ messageId: edit.messageId,
604
+ authorPrincipal: edit.authorPrincipal,
605
+ mode: "queue",
606
+ immediate: true,
607
+ replacesMessageId: edit.target.id,
608
+ parts: edit.parts,
609
+ // Routed now, against the turn the edit continues: the stopped turn is not one of those.
610
+ spec: {
611
+ model: spec.model,
612
+ ...(spec.reasoning === undefined ? {} : { reasoning: spec.reasoning }),
613
+ approvalMode: spec.approvalMode,
614
+ },
615
+ ...settings,
616
+ executionId: request.id,
617
+ })
618
+
619
+ // Taken from the turn before it stops: it would read them at its next step.
620
+ await queueWaitingSteers(agents, projectId, thread.id, edit.authorPrincipal)
621
+ await stopTurnBefore(runtime, execution, active, options.blobStorage)
622
+ // The turn may have ended before the edit reached the inbox, its end reading none of it.
623
+ await startIfThreadIdle(runtime, execution, thread.id, options.blobStorage)
624
+ return item
625
+ }
626
+
627
+ /** What a rewind took back, for the events that tell watchers. */
628
+ interface AgentThreadRewind {
629
+ readonly restoredVersions: readonly PublishedArtifactVersion["version"][]
630
+ readonly cancelledApprovals: readonly AgentApprovalRecord[]
631
+ }
632
+
633
+ /**
634
+ * Take the thread back to just before the edited message, in the caller's transaction: undo the
635
+ * artifact writes of the turns it removes, newest first, drop their approvals and the summaries
636
+ * that saw them, then delete the message and everything after it. It checks again what the edit
637
+ * checked, as the thread may have moved on since, and writes nothing when a check fails.
638
+ */
639
+ async function rewindAgentThread(
640
+ tx: Storage,
641
+ agents: AgentStorage,
642
+ input: {
643
+ readonly projectId: string
644
+ readonly thread: AgentThreadRecord
645
+ /** The edited message: the thread keeps what came before it. */
646
+ readonly messageId: string
647
+ readonly editor: Principal
648
+ /** Restore documents of the rewound turns' canvases, read before the transaction. */
649
+ readonly documents: ReadonlyMap<string, Record<string, FileRef>>
650
+ }
651
+ ): Promise<AgentThreadRewind> {
652
+ const { projectId, thread, editor } = input
653
+
654
+ const target = await agents.messages.getById({ projectId, id: input.messageId })
655
+ if (!target || target.threadId !== thread.id) {
656
+ throw new AgentRequestError(
657
+ "message_not_found",
658
+ `[Sixb] Agent message '${input.messageId}' not found in thread '${thread.id}'.`
659
+ )
660
+ }
661
+ assertEditableMessageAuthority(thread, target, editor)
662
+
663
+ const tail = await listAllThreadMessagesFromSeq(agents, projectId, thread.id, target.seq)
664
+ assertParticipantCanRewindTail(thread, tail, editor)
665
+ const rewoundRuns = await listRewoundConversationRuns(agents, projectId, thread.id, tail)
666
+ assertRewindsWholeTurns(target, tail, rewoundRuns)
667
+
668
+ const restored = new Map<string, PublishedArtifactVersion["version"]>()
669
+ if (tx.artifacts) {
670
+ for (const { run, later } of oldestFirst(rewoundRuns, tail)) {
671
+ const trigger = tail.find((message) => message.id === run.triggerMessageId)
672
+ const undone = await tx.artifacts.undoTurnWrites({
673
+ projectId,
674
+ turnRunId: run.id,
675
+ laterTurnRunIds: later,
676
+ documents: input.documents.get(run.id) ?? {},
677
+ ...(trigger?.authorPrincipal ? { requester: trigger.authorPrincipal } : {}),
678
+ })
679
+ for (const entry of undone.restored) restored.set(entry.artifact.id, entry.version)
680
+ for (const deletedId of undone.deleted) restored.delete(deletedId)
681
+ }
682
+ }
683
+
684
+ const approvals = await agents.approvals.rewind({
685
+ projectId,
686
+ threadId: thread.id,
687
+ runIds: rewoundRuns.map((run) => run.id),
688
+ clearedMessageIds: tail.map((message) => message.id),
689
+ })
690
+ await agents.checkpoints.deleteAfterSeq({
691
+ projectId,
692
+ threadId: thread.id,
693
+ afterSeq: target.seq - 1,
694
+ })
695
+ await agents.messages.deleteFromSeq({ projectId, threadId: thread.id, fromSeq: target.seq })
696
+ await queueWaitingSteers(agents, projectId, thread.id, editor)
697
+
698
+ return { restoredVersions: [...restored.values()], cancelledApprovals: approvals.cancelled }
699
+ }
700
+
701
+ /**
702
+ * The editor's steers still waiting were written for a turn the edit takes back: they wait for the
703
+ * next turn instead, where the tray shows them to keep or withdraw. Someone else's stay as they are.
704
+ */
705
+ async function queueWaitingSteers(
706
+ agents: AgentStorage,
707
+ projectId: string,
708
+ threadId: string,
709
+ editor: Principal
710
+ ): Promise<void> {
711
+ const waiting = await agents.inbox.list({ projectId, threadId, includeClaimed: false })
712
+ for (const item of waiting) {
713
+ if (item.mode !== "steer" || item.immediate) continue
714
+ if (!principalsEqual(item.authorPrincipal, editor)) continue
715
+
716
+ try {
717
+ await agents.inbox.update({ projectId, threadId, id: item.id, mode: "queue" })
718
+ } catch (error) {
719
+ // The stopping turn took it meanwhile: its end lets it go, and the rewind queues it then.
720
+ if (error instanceof AgentStorageError && error.code === "invalid_state") continue
721
+ throw error
722
+ }
723
+ }
724
+ }
725
+
726
+ /** The documents that restore the canvases the rewound turns wrote, read before the rewind. */
727
+ async function rewoundTurnDocuments(
728
+ runtime: SixbRuntimeContext,
729
+ blobStorage: RewindBlobStorage | undefined,
730
+ rewoundRuns: readonly ConversationAgentRunRecord[],
731
+ tail: readonly AgentMessageRecord[]
732
+ ): Promise<ReadonlyMap<string, Record<string, FileRef>>> {
733
+ const documents = new Map<string, Record<string, FileRef>>()
734
+ const artifacts = runtime.storage.artifacts
735
+ if (!artifacts || !blobStorage) return documents
736
+
737
+ for (const { run, later } of oldestFirst(rewoundRuns, tail)) {
738
+ documents.set(
739
+ run.id,
740
+ await undoneTurnDocuments(
741
+ { projectId: runtime.projectId, storage: artifacts, blobStorage },
742
+ run.id,
743
+ later
744
+ )
745
+ )
746
+ }
747
+ return documents
748
+ }
749
+
750
+ /**
751
+ * The rewound turns oldest first, each with the turns after it: undone together, an artifact
752
+ * several of them wrote goes back to before the first, as no one else wrote it in between. Turns
753
+ * follow their trigger messages through the thread, and a retry follows the attempt it replaced.
754
+ */
755
+ function oldestFirst(
756
+ rewoundRuns: readonly ConversationAgentRunRecord[],
757
+ tail: readonly AgentMessageRecord[]
758
+ ): readonly { readonly run: ConversationAgentRunRecord; readonly later: readonly string[] }[] {
759
+ const seqOf = new Map(tail.map((message) => [message.id, message.seq]))
760
+ const started = (run: ConversationAgentRunRecord) => (run.startedAt ?? run.createdAt).getTime()
761
+ const ordered = [...rewoundRuns].sort(
762
+ (left, right) =>
763
+ (seqOf.get(left.triggerMessageId) ?? 0) - (seqOf.get(right.triggerMessageId) ?? 0) ||
764
+ started(left) - started(right) ||
765
+ left.attempt - right.attempt
766
+ )
767
+
768
+ return ordered.map((run, index) => ({
769
+ run,
770
+ later: ordered.slice(index + 1).map((each) => each.id),
771
+ }))
772
+ }
773
+
774
+ async function announceAgentThreadRewind(
775
+ runtime: SixbRuntimeContext,
776
+ rewind: AgentThreadRewind | undefined,
777
+ superseded: readonly AgentApprovalRecord[]
778
+ ): Promise<void> {
779
+ await announceArtifactUpdates(runtime.events, rewind?.restoredVersions ?? [])
780
+ await announceAgentApprovals(runtime.broker, [
781
+ ...(rewind?.cancelledApprovals ?? []),
782
+ ...superseded,
783
+ ])
784
+ }
785
+
786
+ function assertEditableMessageAuthority(
787
+ _thread: AgentThreadRecord,
788
+ target: AgentMessageRecord,
789
+ principal: Principal
790
+ ): void {
791
+ if (!isEditableAgentMessage(target)) {
792
+ throw new AgentRequestError(
793
+ "message_not_editable",
794
+ `[Sixb] Only user-authored messages can be edited.`
795
+ )
796
+ }
797
+ if (
798
+ principal.type === "user" &&
799
+ (!target.authorPrincipal || !principalsEqual(target.authorPrincipal, principal))
800
+ ) {
801
+ throw new AgentRequestError(
802
+ "not_message_author",
803
+ `[Sixb] Only the author of message '${target.id}' can edit it.`
804
+ )
805
+ }
806
+ }
807
+
808
+ function assertParticipantCanRewindTail(
809
+ thread: AgentThreadRecord,
810
+ tail: readonly AgentMessageRecord[],
811
+ principal: Principal
812
+ ): void {
813
+ if (principal.type !== "user" || principalsEqual(principal, thread.ownerPrincipal)) return
814
+
815
+ const erasesOthers = tail.some(
816
+ (message) =>
817
+ message.role === "user" &&
818
+ countsAsThreadMessage(message) &&
819
+ message.authorPrincipal !== undefined &&
820
+ !principalsEqual(message.authorPrincipal, principal)
821
+ )
822
+ if (erasesOthers) {
823
+ throw new AgentRequestError(
824
+ "not_thread_owner",
825
+ "[Sixb] Only the thread's owner can rewind past another person's messages."
826
+ )
827
+ }
828
+ }
829
+
830
+ /**
831
+ * An edit takes back whole turns: each turn it rewinds answered a message it removes. A message a
832
+ * turn read while it was answering, as a steer, sits inside that turn: rewinding from it would
833
+ * keep the turn's first part in the chat and undo everything the turn did.
834
+ */
835
+ function assertRewindsWholeTurns(
836
+ target: AgentMessageRecord,
837
+ tail: readonly AgentMessageRecord[],
838
+ rewoundRuns: readonly ConversationAgentRunRecord[]
839
+ ): void {
840
+ const removed = new Set(tail.map((message) => message.id))
841
+ const cut = rewoundRuns.find((run) => !removed.has(run.triggerMessageId))
842
+ if (!cut) return
843
+
844
+ throw new AgentRequestError(
845
+ "message_not_editable",
846
+ `[Sixb] Agent message '${target.id}' came in while the Agent was answering message '${cut.triggerMessageId}': edit that message instead.`
847
+ )
848
+ }
849
+
850
+ async function listAllThreadMessagesFromSeq(
851
+ agents: AgentStorage,
852
+ projectId: string,
853
+ threadId: string,
854
+ fromSeq: number
855
+ ): Promise<readonly AgentMessageRecord[]> {
856
+ const messages: AgentMessageRecord[] = []
857
+ const afterSeq = fromSeq - 1
858
+ for (;;) {
859
+ const page = await agents.messages.list({
860
+ projectId,
861
+ threadId,
862
+ afterSeq,
863
+ order: "asc",
864
+ limit: 200,
865
+ offset: messages.length,
866
+ })
867
+ messages.push(...page.messages)
868
+ if (!page.hasMore || page.messages.length === 0) return messages
869
+ }
870
+ }
871
+
872
+ /** Conversation runs triggered at or after the rewound message, newest first. */
873
+ async function listRewoundConversationRuns(
874
+ agents: AgentStorage,
875
+ projectId: string,
876
+ threadId: string,
877
+ tail: readonly AgentMessageRecord[]
878
+ ): Promise<readonly ConversationAgentRunRecord[]> {
879
+ const removedMessageIds = new Set(tail.map((message) => message.id))
880
+ const removedRunIds = new Set(
881
+ tail.flatMap((message) => (message.runId === null ? [] : [message.runId]))
882
+ )
883
+ const found: ConversationAgentRunRecord[] = []
884
+ for (let offset = 0; ; ) {
885
+ const page = await agents.runs.list({
886
+ projectId,
887
+ threadId,
888
+ kinds: ["conversation"],
889
+ order: "desc",
890
+ limit: 100,
891
+ offset,
892
+ })
893
+ for (const run of page.runs) {
894
+ if (
895
+ run.kind === "conversation" &&
896
+ (removedMessageIds.has(run.triggerMessageId) || removedRunIds.has(run.id))
897
+ ) {
898
+ found.push(run)
899
+ }
900
+ }
901
+ offset += page.runs.length
902
+ if (!page.hasMore || page.runs.length === 0) return found
903
+ }
904
+ }
905
+
906
+ /**
907
+ * The newest turn an edit keeps: its trigger message is still in the thread, before the edited one.
908
+ * Turns the edit rewinds answered a message of `tail`; turns an earlier edit rewound answered a
909
+ * message that is gone.
910
+ */
911
+ async function latestRetainedConversationRun(
912
+ agents: AgentStorage,
913
+ projectId: string,
914
+ threadId: string,
915
+ tail: readonly AgentMessageRecord[]
916
+ ): Promise<ConversationAgentRunRecord | undefined> {
917
+ const notRetained = new Set(tail.map((message) => message.id))
918
+
919
+ for (let offset = 0; ; ) {
920
+ const page = await agents.runs.list({
921
+ projectId,
922
+ threadId,
923
+ kinds: ["conversation"],
924
+ order: "desc",
925
+ limit: 50,
926
+ offset,
927
+ })
928
+
929
+ for (const run of page.runs) {
930
+ if (run.kind !== "conversation" || notRetained.has(run.triggerMessageId)) continue
931
+ if (await agents.messages.getById({ projectId, id: run.triggerMessageId })) return run
932
+ notRetained.add(run.triggerMessageId)
933
+ }
934
+
935
+ offset += page.runs.length
936
+ if (!page.hasMore || page.runs.length === 0) return undefined
937
+ }
938
+ }
939
+
304
940
  /** A failed turn, or one its worker died during, can run again from the same trigger message. */
305
941
  export function isRetryableAgentRun(
306
942
  run: Pick<ConversationAgentRunRecord, "status" | "finishReason">
@@ -322,7 +958,7 @@ export async function retryAgentRun(
322
958
  */
323
959
  blobStorage?: Pick<BlobStorage, "open" | "put">
324
960
  ): Promise<RequestAgentRunResult> {
325
- resolveExecutionScopeAuthorization(runtime.projectId, {
961
+ const authority = resolveExecutionScopeAuthorization(runtime.projectId, {
326
962
  execution,
327
963
  authorization: runtime.runtimeAuthorization,
328
964
  })
@@ -347,6 +983,16 @@ export async function retryAgentRun(
347
983
  )
348
984
  }
349
985
  assertSandboxExecutionAvailable(thread)
986
+ if (
987
+ authority.type === "principal" &&
988
+ thread.runsOn === "computer" &&
989
+ !principalsEqual(authority.context.principal, thread.ownerPrincipal)
990
+ ) {
991
+ throw new AgentRequestError(
992
+ "not_thread_owner",
993
+ `[Sixb] Agent thread '${thread.id}' runs on its owner's computer, as them: only its owner can retry a turn in it.`
994
+ )
995
+ }
350
996
  const runId = createAgentRunId()
351
997
  const durableExecution = await prepareDurableAgentExecution(runtime, execution, runId)
352
998
  await assertAiLimitPreflight(runtime, durableExecution)
@@ -449,7 +1095,8 @@ export async function sendAgentMessage(
449
1095
  runtime: SixbRuntimeContext,
450
1096
  execution: ExecutionContext,
451
1097
  models: AgentRequestModels,
452
- input: SendAgentMessageInput
1098
+ input: SendAgentMessageInput,
1099
+ blobStorage?: RewindBlobStorage
453
1100
  ): Promise<SendAgentMessageResult> {
454
1101
  const delivery = input.delivery ?? "auto"
455
1102
  const agents = requireAgentStorage(runtime)
@@ -520,9 +1167,9 @@ export async function sendAgentMessage(
520
1167
  })
521
1168
 
522
1169
  if (delivery === "send_now") {
523
- await stopTurnBefore(runtime, execution, active as ConversationAgentRunRecord)
1170
+ await stopTurnBefore(runtime, execution, active as ConversationAgentRunRecord, blobStorage)
524
1171
  }
525
- await startIfThreadIdle(runtime, execution, thread.id)
1172
+ await startIfThreadIdle(runtime, execution, thread.id, blobStorage)
526
1173
  return { kind: "inbox", item }
527
1174
  }
528
1175
 
@@ -551,7 +1198,8 @@ export interface PromoteAgentInboxItemInput {
551
1198
  export async function promoteAgentInboxItem(
552
1199
  runtime: SixbRuntimeContext,
553
1200
  execution: ExecutionContext,
554
- input: PromoteAgentInboxItemInput
1201
+ input: PromoteAgentInboxItemInput,
1202
+ blobStorage?: RewindBlobStorage
555
1203
  ): Promise<AgentInboxItemRecord> {
556
1204
  const agents = requireAgentStorage(runtime)
557
1205
  const projectId = runtime.projectId
@@ -622,9 +1270,9 @@ export async function promoteAgentInboxItem(
622
1270
  )
623
1271
  }
624
1272
  if (input.immediate === true && turn) {
625
- await stopTurnBefore(runtime, execution, turn)
1273
+ await stopTurnBefore(runtime, execution, turn, blobStorage)
626
1274
  }
627
- await startIfThreadIdle(runtime, execution, thread.id)
1275
+ await startIfThreadIdle(runtime, execution, thread.id, blobStorage)
628
1276
  return updated
629
1277
  }
630
1278
 
@@ -698,14 +1346,21 @@ async function askedForTurn(
698
1346
  async function stopTurnBefore(
699
1347
  runtime: SixbRuntimeContext,
700
1348
  execution: ExecutionContext,
701
- active: ConversationAgentRunRecord
1349
+ active: ConversationAgentRunRecord,
1350
+ blobStorage: RewindBlobStorage | undefined
702
1351
  ): Promise<void> {
703
1352
  if (active.status === "running") {
704
1353
  await cancelAgentRun(runtime, active)
705
1354
  return
706
1355
  }
707
1356
  await cancelAgentRun(runtime, active).catch(() => undefined)
708
- await startQueuedAgentTurnFromInbox(runtime, execution, active, { onlyImmediate: true })
1357
+ await startQueuedAgentTurnFromInbox(
1358
+ runtime,
1359
+ execution,
1360
+ active,
1361
+ { onlyImmediate: true },
1362
+ blobStorage
1363
+ )
709
1364
  }
710
1365
 
711
1366
  /**
@@ -718,7 +1373,8 @@ async function stopTurnBefore(
718
1373
  async function startIfThreadIdle(
719
1374
  runtime: SixbRuntimeContext,
720
1375
  execution: ExecutionContext,
721
- threadId: string
1376
+ threadId: string,
1377
+ blobStorage: RewindBlobStorage | undefined
722
1378
  ): Promise<void> {
723
1379
  const agents = requireAgentStorage(runtime)
724
1380
  const projectId = runtime.projectId
@@ -740,7 +1396,7 @@ async function startIfThreadIdle(
740
1396
  // it, setting its held calls aside as a message typed in the chat would.
741
1397
  const onlyImmediate =
742
1398
  isAwaitingApprovalRun(last) || !(await turnAnsweredEveryMessage(agents, last))
743
- await startQueuedAgentTurnFromInbox(runtime, execution, last, { onlyImmediate })
1399
+ await startQueuedAgentTurnFromInbox(runtime, execution, last, { onlyImmediate }, blobStorage)
744
1400
  } catch (error) {
745
1401
  console.error(
746
1402
  `[Sixb] Could not start what waits in Agent thread '${threadId}'; the repair pass retries.`,
@@ -793,7 +1449,8 @@ export async function startQueuedAgentTurnFromInbox(
793
1449
  runtime: SixbRuntimeContext,
794
1450
  execution: ExecutionContext,
795
1451
  finishedRun: ConversationAgentRunRecord,
796
- input: { readonly onlyImmediate: boolean }
1452
+ input: { readonly onlyImmediate: boolean },
1453
+ blobStorage?: RewindBlobStorage
797
1454
  ): Promise<AgentQueuedTurnStart> {
798
1455
  resolveExecutionScopeAuthorization(runtime.projectId, {
799
1456
  execution,
@@ -823,8 +1480,11 @@ export async function startQueuedAgentTurnFromInbox(
823
1480
  const runId = createAgentRunId()
824
1481
  const durableExecution = await prepareResumedExecution(runtime, execution, runId)
825
1482
  await assertAiLimitPreflight(runtime, durableExecution)
1483
+ const documents = await waitingEditDocuments(runtime, blobStorage, thread, principal)
826
1484
 
827
1485
  let started: ConversationAgentRunRecord | null
1486
+ let rewind: AgentThreadRewind | undefined
1487
+ let dropped: { readonly item: AgentInboxItemRecord; readonly reason: unknown } | undefined
828
1488
  let superseded: readonly AgentApprovalRecord[] = []
829
1489
  try {
830
1490
  started = await runtime.storage.transaction(async (tx) => {
@@ -843,6 +1503,24 @@ export async function startQueuedAgentTurnFromInbox(
843
1503
  })
844
1504
  if (!item) return null
845
1505
 
1506
+ // An edit takes the thread back to the message it replaces first. One the thread moved past
1507
+ // since it was sent (that message is gone) is dropped: the checks write nothing.
1508
+ if (item.replacesMessageId !== undefined) {
1509
+ try {
1510
+ rewind = await rewindAgentThread(tx, agents, {
1511
+ projectId,
1512
+ thread,
1513
+ messageId: item.replacesMessageId,
1514
+ editor: item.authorPrincipal,
1515
+ documents,
1516
+ })
1517
+ } catch (error) {
1518
+ if (!(error instanceof AgentRequestError)) throw error
1519
+ dropped = { item, reason: error }
1520
+ return null
1521
+ }
1522
+ }
1523
+
846
1524
  const inherited = await resolveAgentApprovalMode(agents, {
847
1525
  projectId,
848
1526
  principal,
@@ -894,14 +1572,49 @@ export async function startQueuedAgentTurnFromInbox(
894
1572
  }
895
1573
  throw error
896
1574
  }
1575
+ if (dropped) {
1576
+ console.warn(
1577
+ `[Sixb] Dropped the edit of Agent message '${dropped.item.replacesMessageId}' waiting in thread '${thread.id}': it no longer applies.`,
1578
+ dropped.reason
1579
+ )
1580
+ }
897
1581
  if (!started) return { status: "nothing" }
898
1582
 
899
- await announceAgentApprovals(runtime.broker, superseded)
1583
+ await announceAgentThreadRewind(runtime, rewind, superseded)
900
1584
  await publishRunActivity(runtime, started)
901
1585
  await dispatchAgentRun(runtime, agents, runId)
902
1586
  return { status: "started", run: started }
903
1587
  }
904
1588
 
1589
+ /**
1590
+ * The restore documents for the edit the caller's next queued message would make, read before
1591
+ * the transaction that starts it, as an edit on an idle thread reads them. Edits are always sent
1592
+ * now, so the caller's oldest message sent now is the one their turn takes first.
1593
+ */
1594
+ async function waitingEditDocuments(
1595
+ runtime: SixbRuntimeContext,
1596
+ blobStorage: RewindBlobStorage | undefined,
1597
+ thread: AgentThreadRecord,
1598
+ principal: Principal
1599
+ ): Promise<ReadonlyMap<string, Record<string, FileRef>>> {
1600
+ if (!runtime.storage.artifacts || !blobStorage) return new Map()
1601
+
1602
+ const agents = requireAgentStorage(runtime)
1603
+ const projectId = runtime.projectId
1604
+ const waiting = await agents.inbox.list({ projectId, threadId: thread.id, includeClaimed: false })
1605
+ const next = waiting
1606
+ .filter((item) => item.immediate && principalsEqual(item.authorPrincipal, principal))
1607
+ .sort((left, right) => left.seq - right.seq)[0]
1608
+ if (next?.replacesMessageId === undefined) return new Map()
1609
+
1610
+ const target = await agents.messages.getById({ projectId, id: next.replacesMessageId })
1611
+ if (!target || target.threadId !== thread.id) return new Map()
1612
+
1613
+ const tail = await listAllThreadMessagesFromSeq(agents, projectId, thread.id, target.seq)
1614
+ const rewoundRuns = await listRewoundConversationRuns(agents, projectId, thread.id, tail)
1615
+ return rewoundTurnDocuments(runtime, blobStorage, rewoundRuns, tail)
1616
+ }
1617
+
905
1618
  /** A queued message's turn: the finished turn's spec, with the message's own choices over it. */
906
1619
  function queuedConversationRunSpec(
907
1620
  thread: AgentThreadRecord,
@@ -910,7 +1623,10 @@ function queuedConversationRunSpec(
910
1623
  approvalMode: AgentApprovalMode
911
1624
  ): ConversationAgentRunSpec {
912
1625
  const model = item.spec?.model ?? kept.model
913
- const reasoning = item.spec?.reasoning ?? kept.reasoning
1626
+ // An edit's choices were made against the turn it continues: the stopped turn it rewinds passes
1627
+ // nothing on.
1628
+ const reasoning =
1629
+ item.spec?.reasoning ?? (item.replacesMessageId === undefined ? kept.reasoning : undefined)
914
1630
  const timeZone = item.timeZone ?? kept.timeZone
915
1631
  const locale = item.locale ?? kept.locale
916
1632
  return inPlace(thread, {
@@ -1079,8 +1795,8 @@ function inPlace(
1079
1795
  thread: AgentThreadRecord,
1080
1796
  spec: ConversationAgentRunSpec
1081
1797
  ): ConversationAgentRunSpec {
1082
- const { runsOn: _runsOn, ...rest } = spec
1083
- return Object.freeze(thread.runsOn === undefined ? rest : { ...rest, runsOn: thread.runsOn })
1798
+ const { runsOn: _runsOn, computer: _computer, ...rest } = spec
1799
+ return Object.freeze({ ...rest, ...turnPlace(thread.runsOn, thread.computer) })
1084
1800
  }
1085
1801
 
1086
1802
  /** The paused turn's spec, with defaults for a model that has since left the catalog. */
@@ -1153,18 +1869,22 @@ function routedTurn(
1153
1869
 
1154
1870
  /** The spec of a turn Sixb picks the model for, compared to the thread's previous turn. */
1155
1871
  async function routedConversationRunSpec(
1156
- agents: AgentStorage,
1157
1872
  input: RoutedTurn & {
1873
+ readonly agents: AgentStorage
1158
1874
  readonly projectId: string
1159
- readonly threadId: string | undefined
1875
+ /** The turn this one continues, absent for a thread's first. */
1876
+ readonly previous: ConversationAgentRunRecord | undefined
1877
+ /** Where the turn runs: the previous turn's cache holds its prompt only if it ran there. */
1878
+ readonly place: AgentTurnPlace
1160
1879
  readonly settings: RequesterSettings
1161
1880
  readonly language: LanguageModelCatalog | undefined
1162
1881
  }
1163
1882
  ): Promise<ConversationAgentRunSpec> {
1164
- const previous = input.threadId
1165
- ? await latestConversationRun(agents, input.projectId, input.threadId)
1166
- : undefined
1167
- const choice = await input.router.choose(input.text, previous)
1883
+ const previous = input.previous && {
1884
+ run: input.previous,
1885
+ text: await messageWords(input.agents, input.projectId, input.previous.triggerMessageId),
1886
+ }
1887
+ const choice = await input.router.choose({ text: input.text, previous, place: input.place })
1168
1888
 
1169
1889
  return resolveConversationRunSpec({
1170
1890
  models: input.language,
@@ -1174,6 +1894,22 @@ async function routedConversationRunSpec(
1174
1894
  })
1175
1895
  }
1176
1896
 
1897
+ /** What a person wrote in a message, without the context or files sent with it. */
1898
+ async function messageWords(
1899
+ agents: AgentStorage,
1900
+ projectId: string,
1901
+ messageId: string
1902
+ ): Promise<string | undefined> {
1903
+ const message = await agents.messages.getById({ projectId, id: messageId })
1904
+ if (!message) return undefined
1905
+
1906
+ const words = message.parts
1907
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
1908
+ .join("\n")
1909
+ .trim()
1910
+ return words || undefined
1911
+ }
1912
+
1177
1913
  async function latestConversationRun(
1178
1914
  agents: AgentStorage,
1179
1915
  projectId: string,
@@ -1226,6 +1962,18 @@ function assertAttachments(attachments: readonly FileRef[] | undefined): void {
1226
1962
  }
1227
1963
 
1228
1964
  function assertThreadAcceptsRun(thread: AgentThreadRecord, principal: Principal): void {
1965
+ assertThreadAcceptsMessages(thread, principal)
1966
+ // Fast single-flight check for a clear error. `runs.create` is the atomic authority.
1967
+ if (thread.activeRunId !== null) {
1968
+ throw new AgentRequestError(
1969
+ "active_run_exists",
1970
+ `[Sixb] Agent thread '${thread.id}' already has an active run '${thread.activeRunId}'.`
1971
+ )
1972
+ }
1973
+ }
1974
+
1975
+ /** Whether `principal` may send the thread a message: a turn may still be running. */
1976
+ function assertThreadAcceptsMessages(thread: AgentThreadRecord, principal: Principal): void {
1229
1977
  assertConversationThread(thread)
1230
1978
  assertSandboxExecutionAvailable(thread)
1231
1979
  // Its owner's computer runs its turns as its owner: nobody else may send it one.
@@ -1235,17 +1983,14 @@ function assertThreadAcceptsRun(thread: AgentThreadRecord, principal: Principal)
1235
1983
  `[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.`
1236
1984
  )
1237
1985
  }
1238
- // Fast single-flight check for a clear error. `runs.create` is the atomic authority.
1239
- if (thread.activeRunId !== null) {
1240
- throw new AgentRequestError(
1241
- "active_run_exists",
1242
- `[Sixb] Agent thread '${thread.id}' already has an active run '${thread.activeRunId}'.`
1243
- )
1244
- }
1245
1986
  }
1246
1987
 
1247
1988
  function assertSandboxExecutionAvailable(thread: AgentThreadRecord): void {
1248
- if (thread.sandboxState && !["new", "ready"].includes(thread.sandboxState.status)) {
1989
+ if (
1990
+ thread.runsOn !== "computer" &&
1991
+ thread.sandboxState &&
1992
+ !["new", "ready"].includes(thread.sandboxState.status)
1993
+ ) {
1249
1994
  throw new AgentRequestError(
1250
1995
  "sandbox_execution_unavailable",
1251
1996
  "[Sixb] Sandbox recovery is required before another run. Reload the thread, then resume its previous sandbox or recreate it to start fresh."