gemi 0.136.0 → 0.137.0

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 (220) hide show
  1. package/dist/ai/Agent.d.ts +48 -5
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentController.d.ts +42 -2
  4. package/dist/ai/AgentController.d.ts.map +1 -1
  5. package/dist/ai/index.d.ts +3 -1
  6. package/dist/ai/index.d.ts.map +1 -1
  7. package/dist/ai/index.js +85 -18
  8. package/dist/ai/index.js.map +5 -4
  9. package/dist/ai/memory/AgentMemories.d.ts +226 -0
  10. package/dist/ai/memory/AgentMemories.d.ts.map +1 -0
  11. package/dist/ai/memory/AgentMemoryStore.d.ts +182 -0
  12. package/dist/ai/memory/AgentMemoryStore.d.ts.map +1 -0
  13. package/dist/ai/memory/DatabaseAgentMemoryStore.d.ts +76 -0
  14. package/dist/ai/memory/DatabaseAgentMemoryStore.d.ts.map +1 -0
  15. package/dist/ai/memory/contextBlock.d.ts +32 -0
  16. package/dist/ai/memory/contextBlock.d.ts.map +1 -0
  17. package/dist/ai/memory/index.d.ts +6 -0
  18. package/dist/ai/memory/index.d.ts.map +1 -0
  19. package/dist/ai/memory/runMemory.d.ts +355 -0
  20. package/dist/ai/memory/runMemory.d.ts.map +1 -0
  21. package/dist/ai/memory/safety.d.ts +34 -0
  22. package/dist/ai/memory/safety.d.ts.map +1 -0
  23. package/dist/ai/memory/search.d.ts +23 -0
  24. package/dist/ai/memory/search.d.ts.map +1 -0
  25. package/dist/app/index.js +1 -1
  26. package/dist/bun/plugin.js +1 -1
  27. package/dist/bun/preload.js +1 -1
  28. package/dist/{chunk-rnp5k8m3.js → chunk-038xtqpm.js} +2 -2
  29. package/dist/{chunk-rnp5k8m3.js.map → chunk-038xtqpm.js.map} +1 -1
  30. package/dist/{chunk-5pdgh9a1.js → chunk-26yghzet.js} +2 -2
  31. package/dist/{chunk-5pdgh9a1.js.map → chunk-26yghzet.js.map} +1 -1
  32. package/dist/{chunk-ha15x5ns.js → chunk-27xv8kty.js} +2 -2
  33. package/dist/{chunk-ha15x5ns.js.map → chunk-27xv8kty.js.map} +1 -1
  34. package/dist/{chunk-k2xeskp6.js → chunk-3jkem5gq.js} +2 -2
  35. package/dist/{chunk-k2xeskp6.js.map → chunk-3jkem5gq.js.map} +1 -1
  36. package/dist/{chunk-q15f5g86.js → chunk-46bwknb5.js} +3 -3
  37. package/dist/{chunk-q15f5g86.js.map → chunk-46bwknb5.js.map} +1 -1
  38. package/dist/{chunk-8sde8337.js → chunk-4jc7wbet.js} +2 -2
  39. package/dist/{chunk-8sde8337.js.map → chunk-4jc7wbet.js.map} +1 -1
  40. package/dist/{chunk-3dpmkxp7.js → chunk-4zjtbgnr.js} +2 -2
  41. package/dist/{chunk-3dpmkxp7.js.map → chunk-4zjtbgnr.js.map} +1 -1
  42. package/dist/{chunk-feajsgns.js → chunk-5benn2ys.js} +3 -3
  43. package/dist/{chunk-feajsgns.js.map → chunk-5benn2ys.js.map} +1 -1
  44. package/dist/{chunk-rzqft8q8.js → chunk-6qzyq0g5.js} +2 -2
  45. package/dist/{chunk-rzqft8q8.js.map → chunk-6qzyq0g5.js.map} +1 -1
  46. package/dist/{chunk-6qty7at2.js → chunk-78zfqt54.js} +2 -2
  47. package/dist/{chunk-6qty7at2.js.map → chunk-78zfqt54.js.map} +1 -1
  48. package/dist/{chunk-ysc7ykss.js → chunk-7d26eqv1.js} +2 -2
  49. package/dist/{chunk-ysc7ykss.js.map → chunk-7d26eqv1.js.map} +1 -1
  50. package/dist/{chunk-6fr6j338.js → chunk-7t7jh8t2.js} +2 -2
  51. package/dist/{chunk-6fr6j338.js.map → chunk-7t7jh8t2.js.map} +1 -1
  52. package/dist/{chunk-xvvsc58s.js → chunk-7vxeqxxr.js} +2 -2
  53. package/dist/{chunk-xvvsc58s.js.map → chunk-7vxeqxxr.js.map} +1 -1
  54. package/dist/{chunk-zyhmn3hy.js → chunk-80fjsb26.js} +3 -3
  55. package/dist/{chunk-zyhmn3hy.js.map → chunk-80fjsb26.js.map} +1 -1
  56. package/dist/{chunk-xymr3asa.js → chunk-85k70cme.js} +3 -3
  57. package/dist/{chunk-xymr3asa.js.map → chunk-85k70cme.js.map} +1 -1
  58. package/dist/{chunk-ka991yx4.js → chunk-8dmhbj4m.js} +2 -2
  59. package/dist/{chunk-ka991yx4.js.map → chunk-8dmhbj4m.js.map} +1 -1
  60. package/dist/{chunk-8ryrjtn0.js → chunk-8ef5c93d.js} +2 -2
  61. package/dist/{chunk-8ryrjtn0.js.map → chunk-8ef5c93d.js.map} +1 -1
  62. package/dist/{chunk-t33yh84d.js → chunk-8p4t8x9c.js} +2 -2
  63. package/dist/{chunk-t33yh84d.js.map → chunk-8p4t8x9c.js.map} +1 -1
  64. package/dist/{chunk-7nxnyw7x.js → chunk-965gfa41.js} +2 -2
  65. package/dist/{chunk-7nxnyw7x.js.map → chunk-965gfa41.js.map} +1 -1
  66. package/dist/{chunk-swwkdm75.js → chunk-974p7em0.js} +2 -2
  67. package/dist/{chunk-swwkdm75.js.map → chunk-974p7em0.js.map} +1 -1
  68. package/dist/{chunk-krk880my.js → chunk-9s203ks3.js} +2 -2
  69. package/dist/{chunk-krk880my.js.map → chunk-9s203ks3.js.map} +1 -1
  70. package/dist/{chunk-0eamc2tr.js → chunk-9wc53ywv.js} +2 -2
  71. package/dist/{chunk-0eamc2tr.js.map → chunk-9wc53ywv.js.map} +1 -1
  72. package/dist/{chunk-hb9hm8za.js → chunk-a2fhbstt.js} +3 -3
  73. package/dist/{chunk-hb9hm8za.js.map → chunk-a2fhbstt.js.map} +1 -1
  74. package/dist/{chunk-cxsvzqd4.js → chunk-aj2sr77y.js} +2 -2
  75. package/dist/{chunk-cxsvzqd4.js.map → chunk-aj2sr77y.js.map} +1 -1
  76. package/dist/{chunk-0gg4e94v.js → chunk-an1nja68.js} +2 -2
  77. package/dist/{chunk-0gg4e94v.js.map → chunk-an1nja68.js.map} +1 -1
  78. package/dist/{chunk-jy9dkgt0.js → chunk-ant9ck0r.js} +2 -2
  79. package/dist/{chunk-jy9dkgt0.js.map → chunk-ant9ck0r.js.map} +1 -1
  80. package/dist/chunk-atmw5c0q.js +28 -0
  81. package/dist/chunk-atmw5c0q.js.map +27 -0
  82. package/dist/{chunk-sa6cxt3g.js → chunk-bg0e39dk.js} +2 -2
  83. package/dist/{chunk-sa6cxt3g.js.map → chunk-bg0e39dk.js.map} +1 -1
  84. package/dist/{chunk-1awxdnb6.js → chunk-c0m8pcbd.js} +1 -1
  85. package/dist/{chunk-65j32dtn.js → chunk-c6c7p43e.js} +2 -2
  86. package/dist/{chunk-65j32dtn.js.map → chunk-c6c7p43e.js.map} +1 -1
  87. package/dist/{chunk-x9bk5s21.js → chunk-c83e4ghx.js} +2 -2
  88. package/dist/{chunk-x9bk5s21.js.map → chunk-c83e4ghx.js.map} +1 -1
  89. package/dist/{chunk-jgx8ggbz.js → chunk-cedmppcy.js} +2 -2
  90. package/dist/{chunk-jgx8ggbz.js.map → chunk-cedmppcy.js.map} +1 -1
  91. package/dist/{chunk-wrsf2abe.js → chunk-chyt9th4.js} +2 -2
  92. package/dist/{chunk-wrsf2abe.js.map → chunk-chyt9th4.js.map} +1 -1
  93. package/dist/{chunk-qfra7gah.js → chunk-d368es1y.js} +2 -2
  94. package/dist/{chunk-qfra7gah.js.map → chunk-d368es1y.js.map} +1 -1
  95. package/dist/{chunk-dt95z6et.js → chunk-d492ae5e.js} +2 -2
  96. package/dist/{chunk-dt95z6et.js.map → chunk-d492ae5e.js.map} +1 -1
  97. package/dist/{chunk-beb265c9.js → chunk-e440f645.js} +2 -2
  98. package/dist/{chunk-beb265c9.js.map → chunk-e440f645.js.map} +1 -1
  99. package/dist/{chunk-njpnstck.js → chunk-eqzxvfvt.js} +2 -2
  100. package/dist/{chunk-njpnstck.js.map → chunk-eqzxvfvt.js.map} +1 -1
  101. package/dist/{chunk-99a4e6zf.js → chunk-f9w78tbd.js} +2 -2
  102. package/dist/{chunk-99a4e6zf.js.map → chunk-f9w78tbd.js.map} +1 -1
  103. package/dist/chunk-fjw51b91.js +10 -0
  104. package/dist/{chunk-3gx7wcrt.js.map → chunk-fjw51b91.js.map} +3 -3
  105. package/dist/chunk-fs4ntgdr.js +5 -0
  106. package/dist/{chunk-47e7fbsp.js.map → chunk-fs4ntgdr.js.map} +1 -1
  107. package/dist/{chunk-gng5e7pd.js → chunk-fwmmy0jn.js} +1 -1
  108. package/dist/{chunk-mw7ft5bs.js → chunk-g22q8j2s.js} +2 -2
  109. package/dist/{chunk-mw7ft5bs.js.map → chunk-g22q8j2s.js.map} +1 -1
  110. package/dist/{chunk-z9xxthp1.js → chunk-ghbzre7k.js} +3 -3
  111. package/dist/{chunk-z9xxthp1.js.map → chunk-ghbzre7k.js.map} +1 -1
  112. package/dist/{chunk-x5hj0mqp.js → chunk-gq4fr0zn.js} +3 -3
  113. package/dist/{chunk-x5hj0mqp.js.map → chunk-gq4fr0zn.js.map} +1 -1
  114. package/dist/{chunk-x51tegk3.js → chunk-gqcmnyc8.js} +2 -2
  115. package/dist/{chunk-x51tegk3.js.map → chunk-gqcmnyc8.js.map} +1 -1
  116. package/dist/{chunk-x16ckgq1.js → chunk-h0ydk8cc.js} +2 -2
  117. package/dist/{chunk-x16ckgq1.js.map → chunk-h0ydk8cc.js.map} +1 -1
  118. package/dist/{chunk-m9vwg9j1.js → chunk-jys3n8xv.js} +3 -3
  119. package/dist/{chunk-m9vwg9j1.js.map → chunk-jys3n8xv.js.map} +1 -1
  120. package/dist/{chunk-3h37f124.js → chunk-kpb8xvrv.js} +2 -2
  121. package/dist/{chunk-3h37f124.js.map → chunk-kpb8xvrv.js.map} +1 -1
  122. package/dist/{chunk-mpqvmge4.js → chunk-kzdkpz04.js} +1 -1
  123. package/dist/{chunk-0rhf4g12.js → chunk-md6wfc1h.js} +3 -3
  124. package/dist/{chunk-0rhf4g12.js.map → chunk-md6wfc1h.js.map} +1 -1
  125. package/dist/{chunk-s025aycr.js → chunk-n2czjpz9.js} +2 -2
  126. package/dist/{chunk-s025aycr.js.map → chunk-n2czjpz9.js.map} +1 -1
  127. package/dist/{chunk-ff60bzvf.js → chunk-n7576zsr.js} +3 -3
  128. package/dist/{chunk-ff60bzvf.js.map → chunk-n7576zsr.js.map} +1 -1
  129. package/dist/{chunk-s782bzeq.js → chunk-nbfksexg.js} +2 -2
  130. package/dist/{chunk-s782bzeq.js.map → chunk-nbfksexg.js.map} +1 -1
  131. package/dist/{chunk-p82868xx.js → chunk-p1y58p84.js} +2 -2
  132. package/dist/{chunk-p82868xx.js.map → chunk-p1y58p84.js.map} +1 -1
  133. package/dist/{chunk-zv5qyrqg.js → chunk-p2c7z2nr.js} +2 -2
  134. package/dist/{chunk-zv5qyrqg.js.map → chunk-p2c7z2nr.js.map} +1 -1
  135. package/dist/{chunk-vnw91fe1.js → chunk-pv2mtg8n.js} +2 -2
  136. package/dist/{chunk-vnw91fe1.js.map → chunk-pv2mtg8n.js.map} +1 -1
  137. package/dist/{chunk-jx5zx48j.js → chunk-qfhcec6q.js} +2 -2
  138. package/dist/{chunk-jx5zx48j.js.map → chunk-qfhcec6q.js.map} +1 -1
  139. package/dist/{chunk-6hz63ts4.js → chunk-qk6vmvr2.js} +4 -4
  140. package/dist/{chunk-6hz63ts4.js.map → chunk-qk6vmvr2.js.map} +1 -1
  141. package/dist/{chunk-w1cksc5z.js → chunk-qvx8473q.js} +3 -3
  142. package/dist/{chunk-w1cksc5z.js.map → chunk-qvx8473q.js.map} +1 -1
  143. package/dist/{chunk-4278e429.js → chunk-rqb52m93.js} +2 -2
  144. package/dist/{chunk-4278e429.js.map → chunk-rqb52m93.js.map} +1 -1
  145. package/dist/{chunk-py1twqh8.js → chunk-skmdmqv7.js} +2 -2
  146. package/dist/{chunk-py1twqh8.js.map → chunk-skmdmqv7.js.map} +1 -1
  147. package/dist/{chunk-04tkpna8.js → chunk-t0p6zb29.js} +2 -2
  148. package/dist/{chunk-04tkpna8.js.map → chunk-t0p6zb29.js.map} +1 -1
  149. package/dist/{chunk-53rr32zm.js → chunk-ted0qjps.js} +1 -1
  150. package/dist/{chunk-hj88dcss.js → chunk-v4dp93qv.js} +3 -3
  151. package/dist/{chunk-hj88dcss.js.map → chunk-v4dp93qv.js.map} +1 -1
  152. package/dist/{chunk-33hdxe7v.js → chunk-vmr4d6hc.js} +1 -1
  153. package/dist/{chunk-3g5q0cj5.js → chunk-vz5rrcnh.js} +2 -2
  154. package/dist/{chunk-3g5q0cj5.js.map → chunk-vz5rrcnh.js.map} +1 -1
  155. package/dist/{chunk-pm8wjatv.js → chunk-w17p2k8g.js} +3 -3
  156. package/dist/{chunk-pm8wjatv.js.map → chunk-w17p2k8g.js.map} +1 -1
  157. package/dist/{chunk-j5g7qc5f.js → chunk-wbvb1hcx.js} +2 -2
  158. package/dist/{chunk-j5g7qc5f.js.map → chunk-wbvb1hcx.js.map} +1 -1
  159. package/dist/{chunk-t8xs9ptb.js → chunk-x1j7e46e.js} +2 -2
  160. package/dist/{chunk-t8xs9ptb.js.map → chunk-x1j7e46e.js.map} +1 -1
  161. package/dist/{chunk-jx2mgvvt.js → chunk-xwmy6fby.js} +3 -3
  162. package/dist/{chunk-jx2mgvvt.js.map → chunk-xwmy6fby.js.map} +1 -1
  163. package/dist/{chunk-z61dj480.js → chunk-y6gr3stt.js} +3 -3
  164. package/dist/{chunk-z61dj480.js.map → chunk-y6gr3stt.js.map} +1 -1
  165. package/dist/{chunk-4t41m5f1.js → chunk-yhp70t40.js} +2 -2
  166. package/dist/{chunk-4t41m5f1.js.map → chunk-yhp70t40.js.map} +1 -1
  167. package/dist/{chunk-zypmy8yq.js → chunk-z0jazehw.js} +2 -2
  168. package/dist/{chunk-zypmy8yq.js.map → chunk-z0jazehw.js.map} +1 -1
  169. package/dist/{chunk-541s0vkt.js → chunk-z19rwc6x.js} +5 -5
  170. package/dist/{chunk-541s0vkt.js.map → chunk-z19rwc6x.js.map} +1 -1
  171. package/dist/{chunk-gqgpwb88.js → chunk-z969a4nt.js} +2 -2
  172. package/dist/{chunk-gqgpwb88.js.map → chunk-z969a4nt.js.map} +1 -1
  173. package/dist/{chunk-hf492gg2.js → chunk-zj8y4ak5.js} +1 -1
  174. package/dist/{chunk-qpwb3gnh.js → chunk-zvzvgrrn.js} +2 -2
  175. package/dist/{chunk-qpwb3gnh.js.map → chunk-zvzvgrrn.js.map} +1 -1
  176. package/dist/config/index.js +1 -1
  177. package/dist/console/run.js +2 -2
  178. package/dist/console/run.js.map +1 -1
  179. package/dist/container/index.js +2 -2
  180. package/dist/container/index.js.map +1 -1
  181. package/dist/database/index.js +2 -2
  182. package/dist/database/index.js.map +1 -1
  183. package/dist/email/index.js +2 -2
  184. package/dist/email/index.js.map +1 -1
  185. package/dist/facades/index.js +2 -2
  186. package/dist/facades/index.js.map +1 -1
  187. package/dist/foundation/index.js +2 -2
  188. package/dist/foundation/index.js.map +1 -1
  189. package/dist/http/index.js +2 -2
  190. package/dist/http/index.js.map +1 -1
  191. package/dist/i18n/dictionaryRuntime.js +2 -2
  192. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  193. package/dist/i18n/index.js +2 -2
  194. package/dist/i18n/index.js.map +1 -1
  195. package/dist/kernel/index.js +2 -2
  196. package/dist/kernel/index.js.map +1 -1
  197. package/dist/orm/index.js +2 -2
  198. package/dist/orm/index.js.map +1 -1
  199. package/dist/server/index.js +2 -2
  200. package/dist/server/index.js.map +1 -1
  201. package/dist/services/index.js +2 -2
  202. package/dist/services/index.js.map +1 -1
  203. package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
  204. package/dist/services/queue/work.js +2 -2
  205. package/dist/services/queue/work.js.map +1 -1
  206. package/dist/stats/route-table.js +1 -1
  207. package/dist/support/index.js +2 -2
  208. package/dist/support/index.js.map +1 -1
  209. package/dist/vitest/index.js +1 -1
  210. package/package.json +1 -1
  211. package/dist/chunk-2cnawkke.js +0 -22
  212. package/dist/chunk-2cnawkke.js.map +0 -21
  213. package/dist/chunk-3gx7wcrt.js +0 -10
  214. package/dist/chunk-47e7fbsp.js +0 -5
  215. /package/dist/{chunk-1awxdnb6.js.map → chunk-c0m8pcbd.js.map} +0 -0
  216. /package/dist/{chunk-gng5e7pd.js.map → chunk-fwmmy0jn.js.map} +0 -0
  217. /package/dist/{chunk-mpqvmge4.js.map → chunk-kzdkpz04.js.map} +0 -0
  218. /package/dist/{chunk-53rr32zm.js.map → chunk-ted0qjps.js.map} +0 -0
  219. /package/dist/{chunk-33hdxe7v.js.map → chunk-vmr4d6hc.js.map} +0 -0
  220. /package/dist/{chunk-hf492gg2.js.map → chunk-zj8y4ak5.js.map} +0 -0
@@ -1,21 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../ai/store/Nonces.ts", "../ai/redact.ts", "../ai/store/Attachments.ts", "../ai/jobs/AgentJobStore.ts", "../ai/runtime.ts", "../ai/signing.ts", "../ai/providers/errors.ts", "../ai/contextWindow.ts", "../ai/contextCompaction.ts", "../ai/Agent.ts", "../ai/generate.ts", "../ai/jobs/AgentJob.ts"],
4
- "sourcesContent": [
5
- "import { app } from \"../../foundation/app\";\nimport { RedisManager } from \"../../services/redis/RedisManager\";\n\n/**\n * SPENT NONCES: what makes a signed answer single-use (#445).\n *\n * A pending call's signature (and a parked sub-run's record) carries a nonce\n * and an expiry. Verifying the MAC says the server once asked this exact\n * question; spending the nonce says nobody has answered it yet. Without that a\n * stateless client rewinds its history to before the result and replays the\n * same signed approval, and the human who approved once has approved forever.\n *\n * Spending has to be shared by every process that can receive the answer, and\n * it has to be atomic: insert-if-absent, so two instances handed the same\n * answer at the same moment cannot both be told \"first\". A check followed by a\n * write is not enough, since both reads can happen before either write.\n *\n * Implementations:\n *\n * MemoryNonceStore — the default. One process, lost on restart. Correct for\n * a single instance; with several, each instance accepts\n * the same answer once.\n * RedisNonceStore — `SET key 1 PX <ttl> NX` on the app's Redis. Shared,\n * atomic, and Redis drops each key at the token's expiry.\n * your own — e.g. a table with the nonce as its primary key:\n *\n * class DbNonceStore implements NonceStore {\n * async consume(nonce, expiresAt) {\n * // INSERT ... ON CONFLICT (nonce) DO NOTHING, then look at the row count.\n * const inserted = await db.$executeRaw`\n * INSERT INTO agent_nonces (nonce, expires_at)\n * VALUES (${nonce}, ${new Date(expiresAt)})\n * ON CONFLICT (nonce) DO NOTHING`;\n * return inserted === 1;\n * }\n * }\n * // and, from a cron: DELETE FROM agent_nonces WHERE expires_at < now()\n *\n * Expired tokens fail verification on their own, so a store only has to\n * remember a nonce until `expiresAt`; anything older may be dropped.\n */\nexport interface NonceStore {\n /**\n * Records `nonce` as spent until `expiresAt` (epoch milliseconds). Resolves\n * `true` when this call is the one that spent it, `false` when it was\n * already spent. Must be atomic across every process sharing the store.\n *\n * A rejection is treated as \"could not be spent\": the answer is refused,\n * and the user is asked again. A replay guard that silently lets an answer\n * through when its backing store is down is not a guard.\n */\n consume(nonce: string, expiresAt: number): Promise<boolean>;\n}\n\n/**\n * The in-process store. Bounded by the tokens issued in one TTL window: an\n * entry is dropped once its token expires, swept amortized O(1) per insert.\n */\nexport class MemoryNonceStore implements NonceStore {\n private readonly spent = new Map<string, number>();\n /** Sweep when the map has grown past this, so sweeping costs O(1) per insert\n * amortized instead of walking every entry on every answer. */\n private sweepAt = 1024;\n\n async consume(nonce: string, expiresAt: number): Promise<boolean> {\n return this.consumeSync(nonce, expiresAt);\n }\n\n /**\n * The same decision without the promise. JavaScript runs it to completion,\n * so within one process it is atomic. `now` is injectable for tests.\n */\n consumeSync(nonce: string, expiresAt: number, now = Date.now()): boolean {\n if (this.spent.size >= this.sweepAt) this.sweep(now);\n const spentUntil = this.spent.get(nonce);\n // A record past its own expiry binds nothing: the token it refers to fails\n // verification on its own, so holding the nonce would only grow the map.\n if (spentUntil !== undefined && spentUntil > now) return false;\n this.spent.set(nonce, expiresAt);\n return true;\n }\n\n get size(): number {\n return this.spent.size;\n }\n\n private sweep(now: number) {\n for (const [nonce, expiresAt] of this.spent) {\n if (expiresAt <= now) this.spent.delete(nonce);\n }\n this.sweepAt = Math.max(1024, this.spent.size * 2);\n }\n}\n\n/** The slice of Bun's `RedisClient` this store needs: `send(command, args)`. */\nexport interface NonceRedisClient {\n send(command: string, args: string[]): Promise<any>;\n}\n\nexport interface RedisNonceStoreOptions {\n /**\n * Client to run against. Defaults to the app's shared client from\n * `RedisServiceProvider`, resolved on first use so constructing the store\n * never needs a kernel or a connection.\n */\n client?: NonceRedisClient;\n /** Key namespace. Defaults to `gemi:ai:nonce`. */\n prefix?: string;\n}\n\n/**\n * Spent nonces in Redis, shared by every instance of the app. `SET ... NX` is\n * a single command, so the insert-if-absent is atomic in Redis; `PX` hands the\n * cleanup to Redis at the token's own expiry.\n *\n * ```ts\n * const nonces = new RedisNonceStore();\n *\n * class ChatController extends AgentController<typeof chat> {\n * agent = chat;\n * nonces = nonces;\n * }\n * ```\n *\n * A Redis failure rejects, and the answer it was checking is refused (see\n * `NonceStore.consume`).\n */\nexport class RedisNonceStore implements NonceStore {\n private readonly injectedClient?: NonceRedisClient;\n private readonly prefix: string;\n\n constructor(options: RedisNonceStoreOptions = {}) {\n this.injectedClient = options.client;\n this.prefix = options.prefix ?? \"gemi:ai:nonce\";\n }\n\n async consume(nonce: string, expiresAt: number): Promise<boolean> {\n // At least 1ms: `PX 0` is an error, and an already-expired token never\n // reaches here (verification refuses it first) unless the clock moved.\n const ttl = Math.max(1, Math.ceil(expiresAt - Date.now()));\n const reply = await this.client.send(\"SET\", [\n `${this.prefix}:${nonce}`,\n \"1\",\n \"PX\",\n String(ttl),\n \"NX\",\n ]);\n // `OK` when the key was set, nil when it already existed.\n return reply === \"OK\";\n }\n\n private get client(): NonceRedisClient {\n if (this.injectedClient) return this.injectedClient;\n const container = app();\n const client = container.bound(RedisManager)\n ? container.make(RedisManager).client\n : undefined;\n if (!client) {\n throw new Error(\n \"RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).\",\n );\n }\n return client;\n }\n}\n\n/** The process-wide default, shared by every agent that is not given a store. */\nexport const defaultNonceStore = new MemoryNonceStore();\n",
6
- "import type { AgentError, AgentErrorCode } from \"./types\";\n\n/**\n * A tool failure whose message is meant to be read: by the model, which can\n * act on it, and by the client, which shows it.\n *\n * Any other exception a tool throws reaches the model and the client as a\n * generic sentence (see `redactError`), because its message is whatever the\n * code underneath happened to say: a database driver's connection string, an\n * internal hostname, a third party's error body. The full error is logged.\n * Throw this instead when the message is written for the person:\n *\n * ```ts\n * if (!order) throw new ToolError(`There is no order ${input.orderId}.`);\n * ```\n */\nexport class ToolError extends Error {\n /** Whether the model may try the call again. Default `true`. */\n readonly retryable: boolean;\n\n constructor(message: string, options: { retryable?: boolean; cause?: unknown } = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = \"ToolError\";\n this.retryable = options.retryable ?? true;\n }\n}\n\n/**\n * Where an error being redacted came from, with the unredacted detail.\n *\n * - `run`: the run's own failure, on its `error` frame. `failure` is what\n * `result().error` returns: the provider's own message, its HTTP status and\n * request id.\n * - `tool`: a tool threw. `cause` is what it threw; the result the model and\n * the client read is the redacted one.\n */\nexport type ErrorRedactionInfo =\n | {\n source: \"run\";\n failure: AgentError & { status?: number; requestId?: string };\n }\n | {\n source: \"tool\";\n toolName: string;\n cause: unknown;\n };\n\n/**\n * Decides what a client (and, for a tool, the model) is told about a failure.\n * Return the error to send. Full detail is never lost: it stays on\n * `result().error`, in the log and in the controller's `onError`.\n */\nexport type ErrorRedactor = (error: AgentError, info: ErrorRedactionInfo) => AgentError;\n\n/**\n * The run failures whose message comes from outside gemi: a provider's error\n * body or an exception's text. Those can carry resource and deployment names,\n * internal URLs, request ids and, in a provider's validation message, pieces of\n * the request itself. The rest (`timeout`, `invalid_output`, `aborted`, ...)\n * are sentences gemi wrote and are kept.\n */\nconst GENERIC_RUN_MESSAGES: Partial<Record<AgentErrorCode, string>> = {\n provider_error: \"The model provider returned an error.\",\n rate_limited: \"The model provider is rate limiting requests. Try again shortly.\",\n context_length_exceeded: \"The conversation is too long for the model.\",\n content_filtered: \"The model provider's content filter blocked this request.\",\n invalid_tool_input: \"The model provider rejected the request.\",\n tool_error: \"A tool failed.\",\n unknown: \"The run failed unexpectedly.\",\n};\n\n/**\n * The default redaction, and what an override of `AgentController.redactError`\n * falls back to.\n *\n * Keeps `code`, `retryable` and `toolCallId`, which are what a client branches\n * on, and replaces a message that did not come from gemi with a fixed sentence\n * for its code. A tool's exception keeps its message only when it is a\n * `ToolError`.\n */\nexport function redactError(error: AgentError, info: ErrorRedactionInfo): AgentError {\n if (info.source === \"tool\") {\n if (info.cause instanceof ToolError) return error;\n return {\n ...error,\n message: `The tool \"${info.toolName}\" failed with an unexpected error.`,\n };\n }\n const generic = GENERIC_RUN_MESSAGES[error.code];\n return generic === undefined ? error : { ...error, message: generic };\n}\n\n/**\n * Runs an app's redactor and keeps only the `AgentError` fields of what it\n * returns, so a redactor that spreads the failure (`{ ...info.failure }`)\n * cannot put its status or request id on the wire by accident. A redactor\n * that throws falls back to the default rather than to the unredacted error.\n */\nexport function applyRedaction(\n redactor: ErrorRedactor | undefined,\n error: AgentError,\n info: ErrorRedactionInfo,\n onFailure: (err: unknown) => void,\n): AgentError {\n let out: AgentError;\n try {\n out = (redactor ?? redactError)(error, info);\n } catch (err) {\n onFailure(err);\n out = redactError(error, info);\n }\n return {\n code: out.code,\n message: out.message,\n ...(out.toolCallId !== undefined ? { toolCallId: out.toolCallId } : {}),\n retryable: out.retryable,\n };\n}\n\n/**\n * The unredacted error behind a redacted one, for the server-side hooks.\n *\n * Keyed by the object put on the frame, which is the object the controller's\n * event hooks are handed in the same process; it never crosses a wire.\n */\nconst unredacted = new WeakMap<AgentError, AgentError>();\n\nexport function rememberUnredacted(redacted: AgentError, original: AgentError): void {\n if (redacted !== original) unredacted.set(redacted, original);\n}\n\n/** The original of `error` when it was redacted in this process, else `error`. */\nexport function unredactedError(error: AgentError): AgentError {\n return unredacted.get(error) ?? error;\n}\n",
7
- "import { ToolError } from \"../redact\";\nimport type {\n PutFileParams,\n ReadFileParams,\n ReadResult,\n} from \"../../services/file-storage/drivers/types\";\nimport type { Usage } from \"../types\";\n\n/**\n * The bytes of an upload, kept by gemi, and the scope that says whose they are.\n *\n * WHY THIS EXISTS. `AgentController.upload` used to hand the file straight to\n * the model provider and keep nothing, which is the trade `AgentProvider.upload`\n * documents — provider file ids in the history, no storage story. That is a fine\n * trade for vision and it fails the moment a *tool* needs the file: the user\n * uploads an image and asks the agent to create a product, `POST /products`\n * wants multipart bytes, and the server is holding a provider file id and\n * nothing else. The model cannot make up the difference — it *saw* the image, it\n * cannot reproduce it — and the only recovery left is downloading from the\n * vendor, which is a round trip for bytes we held minutes ago, is not declared\n * anywhere (`AgentProvider` has `upload` and no counterpart), and is subject to\n * a retention policy that is not ours.\n *\n * WHY THE SCOPE IS NOT OPTIONAL. Once a tool takes an attachment id as an\n * argument, that id arrives *from the model*, and a model's arguments are as\n * untrusted as a request body: whatever the model wrote is a function of what it\n * read, and it reads the user's text, tool output, and any document it was\n * shown. A store that resolves ids globally therefore lets a prompt-injected\n * model name another tenant's upload and have the server fetch it — the model as\n * confused deputy, spending the server's own credentials.\n *\n * So there is no `find(id)` on this interface, only `find(scope, id)`, and the\n * thing a tool is handed is a `ScopedAttachments` whose methods take no scope at\n * all because it already closed over one. The unscoped read is not discouraged,\n * it is unspellable: the tool has no object to call it on. The scope itself is\n * derived from the server's own knowledge of the request — see\n * `AgentController.attachmentScope` — and never from anything the model can\n * write.\n */\n\n/**\n * The subject an attachment belongs to, as one opaque string.\n *\n * ONE STRING, COMPARED WITH `===`, RATHER THAN A STRUCTURE OF user/thread/org\n * fields. gemi does not have an opinion about tenancy — there is no `Org` in\n * this framework — so a structured scope would have had to be a bag of optional\n * fields, and a bag of optional fields has a worst member: `{}`, which under any\n * partial-match rule matches everything. Every such rule admits `{}` — or\n * `{ userId: undefined }`, which is the same thing arrived at by a typo — so one\n * forgetful line in an app turns the scope check into a no-op that still\n * typechecks. An opaque key has no such member: an app that wants org isolation\n * writes `org:${org.id}` and gets it, and an app that decides a request has no\n * subject returns `null` from `attachmentScope()` and gets no attachment ids at\n * all, rather than a bucket everyone shares.\n *\n * It is an object rather than a bare `string` for one reason, and it is a real\n * one: `find(scope, id)` taking two bare strings is a signature whose arguments\n * can be transposed, and the transposition typechecks, runs, and is a scope\n * check comparing an id against an id. The wrapper makes that a compile error.\n *\n * The key is never shown to the model and never sent to the client. It is a\n * server-side comparison value; it is not a path component and is not parsed.\n */\nexport type AttachmentScope = { readonly key: string };\n\n/**\n * Where an upload's bytes were sent. See `AgentController.attachmentDestination`.\n *\n * `\"provider\"` DESCRIBES A RECORD `upload` NEVER WRITES. A file that goes to the\n * provider alone leaves gemi holding nothing to resolve — `read` and `file`\n * would throw for it — so the route answers `fileId` and mints no attachment id\n * at all, and there is no id for anyone to look up its name with. The value is\n * on this type because a store *can* hold such a row (a custom `AttachmentStore`\n * filing provider uploads for its own bookkeeping is a reasonable thing to\n * write, and `ScopedAttachments` handles it correctly), not because the shipped\n * route produces one.\n */\nexport type AttachmentDestination = \"both\" | \"provider\" | \"storage\";\n\n/**\n * One recorded upload.\n *\n * `fileId` and `objectName` are both optional and at least one is always\n * present, because which of them exists is exactly the destination decision:\n * `provider` has a `fileId` and no bytes of ours, `storage` has bytes and no\n * `fileId`, `both` has both.\n */\nexport type Attachment = {\n /**\n * gemi's id for the upload — the one a tool takes as an argument, and the only\n * id in this module that may be shown to a model.\n *\n * Prefixed `gemi_att_` so that the mistake everyone makes once — a gemi\n * attachment id put into `FilePart.fileId`, which is a *provider* id — is\n * caught by a sentence to read rather than by whatever the vendor says about\n * a file it has never heard of, mid-conversation. `toResponsesInput` checks\n * for the prefix; the vendor's own answer to a bogus `file_id` has not been\n * measured, and the guard does not depend on it.\n */\n id: string;\n /**\n * The scope this was filed under, carried on the record so `ScopedAttachments`\n * can check it a second time. See `ScopedAttachments.get` for why the second\n * check is not redundant.\n */\n scopeKey: string;\n /** The provider file id, when the file was sent to the provider. */\n fileId?: string;\n /** The storage object name, when the bytes were kept. Feed it to `read`. */\n objectName?: string;\n /** The client's filename, kept so a tool can forward the file under it. */\n name: string;\n mimeType: string;\n size: number;\n createdAt: string;\n destination: AttachmentDestination;\n};\n\n/**\n * Where attachment *records* live. The bytes are in `AttachmentStorage`; this\n * holds the row that says which bytes, whose, and under what id.\n *\n * The default is `MemoryAttachmentStore`, which dies with the process, exactly\n * like `MemoryAgentStore`. An app that wants an attachment to outlive a deploy\n * implements this over a table — `id` primary key, `scope_key` column — and\n * assigns it to `AgentController.attachments`.\n *\n * IF YOU IMPLEMENT THIS, THE ONE THING YOU MUST NOT DO is answer `find` from the\n * id alone. `SELECT * FROM attachments WHERE id = ?` is the leak this module\n * exists to prevent, and it passes every test an app writes about its own\n * uploads, because those uploads are always in scope. It is wrong only for an id\n * that came from somewhere else, which is to say only when it matters. The\n * clause is `WHERE id = ? AND scope_key = ?`.\n */\nexport interface AttachmentStore {\n /** Records an attachment under `scope`. The caller has already minted the id. */\n put(scope: AttachmentScope, attachment: Attachment): Promise<void>;\n /**\n * The attachment with this id *within this scope*, or `null`.\n *\n * `null` for an id that does not exist and `null` for an id that exists under\n * another scope, and the caller cannot tell which — deliberately. See\n * `AttachmentNotFoundError`.\n */\n find(scope: AttachmentScope, id: string): Promise<Attachment | null>;\n}\n\n/**\n * The bytes half: whatever the app's file storage is.\n *\n * Structurally satisfied by the `Storage` facade, which is what\n * `AgentController` defaults to. Declared as an interface of two methods rather\n * than as `typeof Storage` so a test — or an app with a second bucket for user\n * uploads — can pass something else without standing up a container.\n */\nexport interface AttachmentStorage {\n put(params: PutFileParams | Blob): Promise<string>;\n read(params: ReadFileParams | string): Promise<ReadResult>;\n}\n\n/**\n * What both a missing id and someone else's id answer.\n *\n * THE MESSAGE MUST NOT SAY WHICH. \"Exists but is not yours\" and \"does not exist\"\n * are two answers to a question the caller is not entitled to ask, and a store\n * that distinguishes them is an oracle: a prompt-injected model that can tell\n * the two apart can walk an id space and report back which ids are live, which\n * is a tenant census delivered through the very tool the injection was aimed at.\n * One error, one wording, one code, for both.\n *\n * A `ToolError` rather than a `RequestBreakerError`: this is thrown inside a\n * tool, where the agent loop turns a throw into a tool result the model reads\n * and can recover from, not inside a route where it would decide a status code.\n * A `ToolError` so the model and the client are shown its message (#446).\n */\nexport class AttachmentNotFoundError extends ToolError {\n readonly code = \"attachment_not_found\";\n constructor(public readonly id: string) {\n super(`No attachment ${id}.`);\n this.name = \"AttachmentNotFoundError\";\n }\n}\n\n/** Raised for a scope no caller could have meant. See `assertScope`. */\nexport class InvalidAttachmentScopeError extends ToolError {\n readonly code = \"invalid_attachment_scope\";\n constructor(message: string) {\n super(message);\n this.name = \"InvalidAttachmentScopeError\";\n }\n}\n\n/**\n * Rejects the empty scope.\n *\n * `{ key: \"\" }` is what an app produces by writing `` `org:${org?.id ?? \"\"}` ``\n * for a request that has no org, and it is the one value that must never reach a\n * store: it compares equal to itself, so every subject-less upload in the\n * process lands in one shared bucket that every subject-less caller can read out\n * of. That is the global store this module exists not to be, arrived at by a\n * template literal. Failing here is loud, happens on the first request, and\n * names the method to fix.\n */\nfunction assertScope(scope: AttachmentScope): AttachmentScope {\n if (!scope || typeof scope.key !== \"string\" || scope.key.length === 0) {\n throw new InvalidAttachmentScopeError(\n \"An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject — an empty key is a bucket every caller shares.\",\n );\n }\n return scope;\n}\n\n/** The prefix on every gemi attachment id. See `Attachment.id`. */\nexport const ATTACHMENT_ID_PREFIX = \"gemi_att_\";\n\nexport function newAttachmentId(): string {\n return `${ATTACHMENT_ID_PREFIX}${crypto.randomUUID()}`;\n}\n\n/**\n * The handle a tool is given, and the only attachment API a tool should ever\n * see.\n *\n * IT TAKES NO SCOPE, ON ANY METHOD. That is the whole design, and it is not a\n * convenience: an API where the scope is a parameter is an API where the scope\n * is a parameter someone passes the wrong thing to — and the wrong thing here is\n * whatever the model wrote, because inside a tool body the model's arguments are\n * the variables closest to hand. Handing the tool an object that has already\n * closed over the server's answer leaves nothing to pass. `resolve(id, scope)`\n * was the rejected shape: it is the same code with the mistake still available.\n */\nexport class ScopedAttachments {\n constructor(\n private readonly store: AttachmentStore,\n private readonly storage: AttachmentStorage,\n private readonly scope: AttachmentScope,\n ) {\n assertScope(scope);\n }\n\n /**\n * The scope's key. Read by `ctx.jobs.start` (#461), which records it on the\n * job so a background job gets the same attachments its tool had. Only the\n * key leaves: it is the server's answer, not something a tool can set.\n */\n get scopeKey(): string {\n return this.scope.key;\n }\n\n /**\n * The record for `id`, or `AttachmentNotFoundError`.\n *\n * THE SCOPE IS CHECKED TWICE HERE, and the second check is the one that\n * matters. `store.find` is an app's code — a table lookup somebody wrote, with\n * a `WHERE` clause somebody has to have remembered — and the failure mode of\n * forgetting the scope clause is a query that works perfectly for every upload\n * the app's own tests make. Comparing `record.scopeKey` again is three lines\n * that hold even when that clause is missing, so a careless store finds nothing\n * across scopes instead of leaking.\n *\n * It is not defence against a *malicious* store — an app's store is the app's\n * own code and could return anything. It is defence against the ordinary\n * version of this bug, which is the one that ships.\n */\n async get(id: string): Promise<Attachment> {\n const record = await this.store.find(this.scope, id);\n if (!record || record.scopeKey !== this.scope.key) {\n throw new AttachmentNotFoundError(id);\n }\n return record;\n }\n\n /**\n * The bytes, streaming, with the metadata `createStreamResponse` wants.\n *\n * Throws `AttachmentNotFoundError` for an attachment that exists but whose\n * bytes were never kept — a `provider`-destination upload. The same error as\n * an unknown id, for the reason on that class: \"it is at the vendor and not\n * here\" is information about someone else's upload as readily as about your\n * own.\n */\n async read(id: string): Promise<ReadResult> {\n return await this.readRecord(id, await this.get(id));\n }\n\n /**\n * The bytes for a record already resolved, so `file()` does one lookup rather\n * than two. `store.find` is a `SELECT` in any real store, and the second one\n * was not a second check of anything — same scope, same id, same row.\n *\n * It still takes the id the *caller* asked for, rather than reading\n * `record.id`, so the error stays a function of the caller's own input: an app\n * store that answers with the wrong row must not get to choose which id\n * appears in a message the model may read.\n */\n private async readRecord(id: string, record: Attachment): Promise<ReadResult> {\n if (!record.objectName) {\n throw new AttachmentNotFoundError(id);\n }\n return await this.storage.read({ name: record.objectName });\n }\n\n /**\n * The bytes as a `File`, under the name and type they were uploaded with —\n * which is the shape the motivating case actually needs, because\n * `form.append(\"image\", file)` is what a tool forwarding an upload to a\n * multipart endpoint writes.\n *\n * Buffers, and says so. `read()` is there for anything large enough that\n * buffering it is the wrong call.\n *\n * THIS IS ALSO HOW AN ATTACHMENT OUTLIVES THE RUN, and it is `file()` rather\n * than `read()` that composes for it:\n *\n * const file = await ctx.attachments.file(id);\n * await Storage.put({ name: `pages/${pageId}/hero.png`, body: file });\n *\n * `read()` answers a `ReadResult` whose `body` is `ReadableStream | Blob |\n * null`, and `PutFileParams.body` is `Blob | File | Buffer` — a stream body\n * has nowhere to go without being drained first.\n *\n * Two things that bite on the way out, both silent:\n *\n * - **Do not keep a `gemi_att_` id as an app's durable handle to a file.**\n * The default record store is `MemoryAttachmentStore`, so the id→object\n * mapping dies with the process while the bytes stay in storage. Copy the\n * file under a key of the app's own and keep that.\n * - **Put an extension on that key.** `FileSystemDriver` — the default —\n * ignores `contentType` on write and re-derives the type from the stored\n * path on read, so an extensionless object serves as\n * `application/octet-stream` and an `<img>` pointed at it renders nothing,\n * with no error anywhere. `attachmentObjectName` carries one over for this\n * module's own writes; an app's key is the app's to name.\n */\n async file(id: string): Promise<File> {\n const record = await this.get(id);\n const result = await this.readRecord(id, record);\n const body = result.body;\n const blob =\n body instanceof Blob ? body : body ? await new Response(body).blob() : new Blob([]);\n return new File([blob], record.name, { type: record.mimeType });\n }\n\n /**\n * Stores bytes a tool produced, under this caller's scope, and answers the\n * record.\n *\n * Here rather than on the store because the id, the object name and the scope\n * all have to be decided together, and because an attachment a tool created\n * has to land in the scope the tool is reading from — otherwise a tool writes\n * a file the next tool of the same run cannot see.\n *\n * Nothing is sent to the provider: bytes a tool made are bytes for the app,\n * and a tool that wants the model to look at its output says so by returning\n * something the model can read. Issue #490 builds `ctx.attachments.put(blob)`\n * on exactly this.\n */\n async put(\n blob: Blob,\n params: { name?: string; mimeType?: string; fileId?: string } = {},\n ): Promise<Attachment> {\n const id = newAttachmentId();\n const mimeType = params.mimeType ?? blob.type ?? \"\";\n const name = params.name ?? (blob instanceof File ? blob.name : id);\n const objectName = await this.storage.put({\n name: attachmentObjectName(id, name),\n body: blob,\n contentType: mimeType || undefined,\n });\n const record: Attachment = {\n id,\n scopeKey: this.scope.key,\n objectName,\n name,\n mimeType: mimeType || \"application/octet-stream\",\n size: blob.size,\n createdAt: new Date().toISOString(),\n // `both` when the caller has already sent the same bytes to the provider,\n // which is what `ctx.attachments.put(blob, { showModel: true })` does\n // before it gets here.\n //\n // The parameter exists rather than a second `markShown` call because the\n // alternative is a row that is briefly, and then permanently if the second\n // write fails, a lie: `destination` is the field that says where the bytes\n // went, and a file sitting in the vendor's file list under a record that\n // says `storage` is exactly the discrepancy the field was added to close.\n // Nothing here uploads — the provider is the run's, not this module's —\n // so the id is passed in rather than produced.\n destination: params.fileId ? \"both\" : \"storage\",\n ...(params.fileId ? { fileId: params.fileId } : {}),\n };\n await this.store.put(this.scope, record);\n return record;\n }\n}\n\n/**\n * What a tool asks for when it parks bytes.\n *\n * `showModel` is the whole of issue #490 in one flag: without it a tool's\n * output is an id in a string, which the model can quote back and cannot look\n * at, so \"edit this image\" produces a file nobody but the app ever sees. With\n * it the same bytes also go to the provider and come back into the transcript\n * as an input-role message the next step is built on — generate, look, fix.\n *\n * It is a flag rather than the default because the default costs money on every\n * call. The reasoning is `capabilitiesForModel`'s, run the other way round: a\n * file the model did not need and was shown anyway is an upload plus a set of\n * image tokens on every subsequent request of the run, on an invoice, for a\n * tool whose author never asked to be looked at. A file the model needed and\n * was not shown is a tool that returned an id, which is what tools did before\n * this existed and is visible in the transcript the moment anyone reads it. The\n * expensive mistake is the silent one here, so the expensive thing is opt in.\n */\nexport type PutAttachmentParams = {\n /** The filename to keep, so a later `file()` hands the bytes back under it. */\n name?: string;\n /** Overrides `blob.type`, which a `Blob` built from raw bytes does not have. */\n mimeType?: string;\n /**\n * Also send these bytes to the model provider and put them in front of the\n * model as an input-role message, once this tool call settles.\n *\n * Refused, loudly, by a provider whose `capabilities.fileInput` is false: the\n * request builder drops a file part such a provider cannot read, and an\n * upload paid for, stored, and then dropped on the way to the wire is the\n * silent-forever failure — the tool reports success, the model answers about\n * an image it was never shown, and nothing anywhere says why.\n */\n showModel?: boolean;\n};\n\n/**\n * The attachment API a tool is given, as `ctx.attachments`.\n *\n * Everything a `ScopedAttachments` does, plus `showModel`, plus the memo that\n * makes a re-entered tool call idempotent. It is a separate interface from\n * `ScopedAttachments` because those two additions are not properties of the\n * scope, they are properties of *one tool call*: the run has to know which call\n * a `put` belongs to in order to replay it, and the object handed to a tool is\n * therefore built per call — the same shape `ctx.runAgent` has, for the same\n * reason.\n *\n * The read half (`get`, `read`, `file`) is delegated to the `ScopedAttachments`\n * unchanged, including its two scope checks. A tool reading a file it did not\n * create is reading an id the model wrote, and #489's whole argument applies to\n * it word for word.\n */\nexport interface ToolAttachments {\n /**\n * Parks bytes under this caller's scope and answers the record.\n *\n * ON A REPLAY THIS STORES NOTHING. An escalating tool is re-entered from the\n * top on the next turn, so the body that built this blob has run before and\n * built one already; the record from that first attempt is what comes back,\n * and the bytes handed in now are dropped. That is the same bargain\n * `ctx.runAgent` makes and it is not avoidable: the id from the first attempt\n * is already in the transcript the model read, so minting a second one would\n * leave the model holding an id for bytes nobody kept — and uploading the\n * second copy would pay the vendor twice and put the same image into the\n * context twice. Work *before* a `put` still runs again; if producing the\n * bytes is what costs, branch on `ctx.resumed`.\n */\n put(blob: Blob, params?: PutAttachmentParams): Promise<Attachment>;\n /** The record for `id`, or `AttachmentNotFoundError`. Scoped. */\n get(id: string): Promise<Attachment>;\n /** The bytes, streaming. Scoped. */\n read(id: string): Promise<ReadResult>;\n /** The bytes as a `File`, under their original name and type. Scoped. */\n file(id: string): Promise<File>;\n}\n\n/**\n * One successful `ctx.attachments.put` of one tool call, written down so the\n * next turn can replay it instead of doing it again.\n *\n * Lives on `ToolCallPart.attachments`, indexed by the order the puts happened\n * in — exactly where and how `ToolCallPart.nested` records sub-runs, and for\n * exactly the same reason: the message history is the only state that survives\n * a turn boundary, in a thread and in the browser both, so a memo that is not\n * on the message is a memo a stateless app does not have.\n *\n * `shown` is absent for a plain `put`. When present it carries the provider\n * file id AND the identity of the message injected for it, because both have to\n * come back byte for byte: a replay that minted a fresh message id would put a\n * second copy of the same image in the transcript, and a client that had\n * already applied the first would show it twice.\n */\nexport type ToolAttachmentPut = {\n /** What `put` answered, replayed verbatim. */\n attachment: Attachment;\n /**\n * Set when this slot was filled by `ctx.generateImage` / `ctx.editImage`\n * rather than a plain `put`, carrying what the render reported and the\n * attachment record cannot.\n *\n * WHY THE RENDER IS MEMOIZED AT ALL, and why it is memoized *here*. An\n * escalating tool is re-entered from the top on the next turn, so a render\n * that is not written down is paid for again — and unlike a `put`, the thing\n * being repeated costs money at the vendor and about two minutes of wall\n * clock. The memo cannot hold the image: this record lives in the message\n * history, which goes over the wire and into a store on every turn, and a\n * megabyte of base64 per generated image would go with it. So what is\n * recorded is the attachment id, and the bytes live in storage where they\n * were going anyway.\n *\n * That is the whole reason `ctx.generateImage` answers an `Attachment`\n * instead of a `Blob` while `ImageModel.generate` answers the bytes: outside\n * a run there is nothing to replay and nowhere to park, and inside one there\n * has to be both.\n *\n * `size` is the pixel dimensions the model actually produced — read off the\n * response, which does not always echo the request — and is not derivable\n * from `Attachment.size`, which is a byte count.\n */\n generated?: {\n size: string;\n usage: Usage;\n };\n /** Set when `showModel` was asked for. See above. */\n shown?: {\n /** The provider's file id — what the injected `FilePart` carries. */\n fileId: string;\n /** The injected message's id, so a replay reproduces it rather than a twin. */\n messageId: string;\n /** Its `createdAt`, for the same reason. */\n createdAt: string;\n };\n};\n\n/**\n * A slot in that list, which is one `put` — or one `put` that threw.\n *\n * The failure arm exists because the index is what identifies a `put`, and an\n * index is taken the moment the call is made rather than when it succeeds: a\n * body that runs its puts concurrently must number them by the order it *asked*\n * and not by the order the network answered, or the next turn will not\n * reproduce the numbering. So a `put` that throws and is caught — a provider\n * that cannot read files, a vendor that refuses the type, a storage write that\n * fails — leaves a slot behind, and a later successful `put` in the same call\n * would otherwise leave a hole in front of it. A hole is `null` once it has\n * been through JSON, which is what a consumer walking `part.attachments`\n * crashes on; `{ failed: true }` is the same fact said out loud.\n *\n * It is written lazily, only when a later `put` needs the index above it, so a\n * tool whose puts all threw still adds no `attachments` field at all. And it is\n * not a memo: a replayed slot marked `failed` is re-attempted from scratch,\n * because there is nothing recorded to hand back and the failure may have been\n * the network's rather than the tool's.\n */\nexport type ToolAttachmentRecord = ToolAttachmentPut | { failed: true };\n\n/**\n * The object name an attachment's bytes are stored under.\n *\n * The scope is deliberately NOT in the path. A scope key is app-authored text —\n * `org:${slug}`, with whatever a slug turns out to be — and putting arbitrary\n * app text into an object name is how a `..` or a `/` ends up somewhere nobody\n * meant on the one driver that resolves names literally (`FileSystemDriver`\n * concatenates them onto a folder path). The record is what carries the scope;\n * the object name only has to be unique, and a uuid already is.\n *\n * The extension is carried over from the client's filename when it looks like\n * one, because `FileSystemDriver` reads a stored object's content type back off\n * its path and would otherwise answer `application/octet-stream` for everything.\n * `Attachment.mimeType` is the authority either way — this is for anything that\n * reads the bucket without the record.\n */\nexport function attachmentObjectName(id: string, name: string): string {\n const match = /\\.([A-Za-z0-9]{1,8})$/.exec(name);\n return `attachments/${id}${match ? `.${match[1]!.toLowerCase()}` : \"\"}`;\n}\n\n/**\n * The default: attachment records last as long as the process.\n *\n * Modelled as one flat map keyed by id, holding the scope beside the record and\n * comparing it in `find` — rather than as a map of maps, which would make the\n * scoping structural and unforgettable. That looks like the safer shape and is\n * the wrong reference implementation: an app's store is a table with an `id`\n * primary key and a `scope_key` column, and its `find` is a `WHERE` clause that\n * can be written wrong. The store gemi ships should have the same failure\n * available to it as the store an app writes, so that a test written against\n * this one is a test of the check every real store also has to make.\n */\nexport class MemoryAttachmentStore implements AttachmentStore {\n private readonly rows = new Map<string, Attachment>();\n\n async put(scope: AttachmentScope, attachment: Attachment): Promise<void> {\n assertScope(scope);\n this.rows.set(attachment.id, { ...attachment, scopeKey: scope.key });\n }\n\n async find(scope: AttachmentScope, id: string): Promise<Attachment | null> {\n assertScope(scope);\n const row = this.rows.get(id);\n // The scope clause. An id belonging to another scope answers `null`, which\n // is the answer an id that does not exist gets — see\n // `AttachmentNotFoundError` for why the two must be indistinguishable.\n if (!row || row.scopeKey !== scope.key) {\n return null;\n }\n return row;\n }\n\n /** Test and dev affordance: how many rows are held, across every scope. */\n get size(): number {\n return this.rows.size;\n }\n}\n\n/**\n * The process-wide default, so an app that configures nothing still gets\n * attachment ids that work for the length of a conversation.\n *\n * Module-level for the reason `defaultAgentStore` is: the controller is\n * constructed per request, so a store assigned as `new MemoryAttachmentStore()`\n * in a field initializer is an empty store on every request, and every\n * attachment id is a miss one turn after it was minted.\n */\nexport const defaultAttachmentStore = new MemoryAttachmentStore();\n",
8
- "import type { AgentError, Usage } from \"../types\";\n\n/**\n * Where a background job stands (#461).\n *\n * `running` until something settles it; `ok` and `error` are final. A job\n * moves out of `running` once, by compare-and-set (`AgentJobStore.transition`),\n * so a queue worker, a provider's webhook, a poller and the deadline sweep can\n * all race to settle the same job and exactly one of them wins.\n */\nexport type AgentJobState = \"running\" | \"ok\" | \"error\";\n\n/**\n * One background job, as the job store keeps it.\n *\n * The record is the job's state, and it is NOT the tool result. The tool\n * result in the thread says `running` and points here by `id`; the controller\n * renders the record's current state over it whenever it loads the thread (see\n * `overlayJobs`). The record is kept apart from the messages because a live\n * run writes whole messages to the store, and a job settling during that run\n * would race those writes and lose.\n */\nexport type AgentJobRecord = {\n /** `ajob_…`. Handed to the app (`JobHandle.id`) to settle a tracked job. */\n id: string;\n threadId: string;\n /** The run whose tool started the job. */\n runId: string;\n /** The tool call whose result this job settles. */\n toolCallId: string;\n toolName: string;\n /** The `runOwner` of the run that started it, or `null` for an anonymous run. */\n owner: string | null;\n /** The `AgentJob` class's queue name, or `null` for a job made with `track`. */\n job: string | null;\n /**\n * What the tool said about the job when it started it: what the model and\n * the UI see while it runs. Server-owned, and kept small by the tool.\n */\n summary?: unknown;\n state: AgentJobState;\n /** The settled output, on `ok`. */\n output?: unknown;\n /** Why it failed, on `error`. Already redacted: this is what the model reads. */\n error?: AgentError;\n /** What the job spent on model and image calls. Counted on the turn that started it. */\n usage?: Usage;\n /**\n * Set when the job's tool result never reached the thread: the run died\n * after the job started and before the result was stored. The job still\n * runs and settles; nothing in the thread shows it.\n */\n orphaned?: true;\n /**\n * The attachment scope key of the run that started the job, so the job's\n * `attachments` are the ones the tool would have had. `null` when the run\n * had none.\n */\n attachmentScope: string | null;\n /** Epoch milliseconds, on the store's clock. */\n createdAt: number;\n updatedAt: number;\n /** When the deadline sweep fails the job if it is still running. */\n deadlineAt: number;\n settledAt?: number;\n};\n\n/** What `create` is given: the record minus what the store stamps. */\nexport type NewAgentJobRecord = Omit<\n AgentJobRecord,\n \"state\" | \"createdAt\" | \"updatedAt\" | \"deadlineAt\" | \"settledAt\"\n> & {\n /** How long from now the job may run, in milliseconds. */\n deadlineMs: number;\n};\n\n/** The fields a transition may write. `id`, the thread and the call never change. */\nexport type AgentJobUpdate = Partial<\n Pick<AgentJobRecord, \"state\" | \"output\" | \"error\" | \"usage\" | \"orphaned\" | \"settledAt\">\n>;\n\n/**\n * Where background jobs live.\n *\n * `MemoryAgentJobStore` is the default and is not durable. `DatabaseAgentJobStore`\n * keeps them in a table. An app that already has a jobs table can implement\n * this over it.\n */\nexport interface AgentJobStore {\n /** Writes a new `running` record and returns it as stored. */\n create(job: NewAgentJobRecord): Promise<AgentJobRecord>;\n get(id: string): Promise<AgentJobRecord | null>;\n /**\n * A thread's jobs, newest first. `states` filters, `limit` bounds. Each\n * record is a copy the caller may keep.\n */\n listForThread(\n threadId: string,\n options?: { states?: AgentJobState[]; limit?: number },\n ): Promise<AgentJobRecord[]>;\n /**\n * Compare-and-set: applies `to` only when the job's state is one of `from`,\n * and answers whether it did. Bumps `updatedAt`, and stamps `settledAt` when\n * `to.state` moves the job out of `running`.\n */\n transition(id: string, from: AgentJobState[], to: AgentJobUpdate): Promise<boolean>;\n /** Running jobs whose `deadlineAt` is at or before `now`, oldest deadline first. */\n overdue(now: number, limit: number): Promise<AgentJobRecord[]>;\n /**\n * The store's clock, in epoch milliseconds. The deadline sweep compares\n * `deadlineAt` against this rather than the process's clock. Optional: a\n * store without one is compared against `Date.now()`.\n */\n now?(): Promise<number>;\n /**\n * Runs `fn` in a transaction, so `ctx.jobs.start` writes the record and\n * queues the job together: both or neither. Optional: without it the record\n * is written first, and a dispatch that fails then fails the record.\n */\n transaction?<T>(fn: () => Promise<T>): Promise<T>;\n}\n\n/** How many settled jobs the memory store keeps per thread before dropping the oldest. */\nconst MEMORY_SETTLED_PER_THREAD = 200;\n\n/**\n * Jobs in a map, for as long as the process lives.\n *\n * NOT DURABLE, like `MemoryAgentStore`: a restart loses every record, and a\n * job that was running is then lost too. The tool result that pointed at it\n * reads as a lost job on the next turn. It is the default so that jobs work in\n * development and tests without a table; use `DatabaseAgentJobStore` in\n * production.\n *\n * It only works when the queue runs the jobs in this same process (the memory\n * queue driver, or a database driver claiming here), since a worker in another\n * process has a map of its own.\n */\nexport class MemoryAgentJobStore implements AgentJobStore {\n private jobs = new Map<string, AgentJobRecord>();\n\n async create(job: NewAgentJobRecord): Promise<AgentJobRecord> {\n if (this.jobs.has(job.id)) {\n throw new Error(`A background job with the id ${job.id} already exists.`);\n }\n const now = Date.now();\n const { deadlineMs, ...fields } = job;\n const record: AgentJobRecord = {\n ...structuredClone(fields),\n state: \"running\",\n createdAt: now,\n updatedAt: now,\n deadlineAt: now + deadlineMs,\n };\n this.jobs.set(record.id, record);\n this.trim(record.threadId);\n return structuredClone(record);\n }\n\n async get(id: string): Promise<AgentJobRecord | null> {\n const record = this.jobs.get(id);\n return record ? structuredClone(record) : null;\n }\n\n async listForThread(\n threadId: string,\n options: { states?: AgentJobState[]; limit?: number } = {},\n ): Promise<AgentJobRecord[]> {\n const out: AgentJobRecord[] = [];\n for (const record of this.jobs.values()) {\n if (record.threadId !== threadId) continue;\n if (options.states && !options.states.includes(record.state)) continue;\n out.push(record);\n }\n out.sort(newestFirst);\n return (options.limit === undefined ? out : out.slice(0, options.limit)).map((record) =>\n structuredClone(record),\n );\n }\n\n async transition(id: string, from: AgentJobState[], to: AgentJobUpdate): Promise<boolean> {\n const record = this.jobs.get(id);\n if (!record || !from.includes(record.state)) return false;\n // Cloned in before anything is assigned, so an output that is not plain\n // data fails the transition rather than half-applying it.\n const update = structuredClone(to);\n const now = Date.now();\n Object.assign(record, update, { updatedAt: now });\n if (update.state && update.state !== \"running\" && record.settledAt === undefined) {\n record.settledAt = update.settledAt ?? now;\n }\n return true;\n }\n\n async overdue(now: number, limit: number): Promise<AgentJobRecord[]> {\n const out: AgentJobRecord[] = [];\n for (const record of this.jobs.values()) {\n if (record.state === \"running\" && record.deadlineAt <= now) out.push(record);\n }\n out.sort((a, b) => a.deadlineAt - b.deadlineAt);\n return out.slice(0, Math.max(0, limit)).map((record) => structuredClone(record));\n }\n\n async now(): Promise<number> {\n return Date.now();\n }\n\n /** Bounds a long-lived thread: running jobs are never dropped, settled ones oldest first. */\n private trim(threadId: string): void {\n const settled = [...this.jobs.values()]\n .filter((record) => record.threadId === threadId && record.state !== \"running\")\n .sort(newestFirst);\n for (const record of settled.slice(MEMORY_SETTLED_PER_THREAD)) this.jobs.delete(record.id);\n }\n}\n\n/** Newest first, with the id as a tie-break so the order is stable. */\nexport function newestFirst(a: AgentJobRecord, b: AgentJobRecord): number {\n return b.createdAt - a.createdAt || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);\n}\n",
9
- "import type { ProviderStreamParams } from \"./AgentProvider\";\nimport { supportsStrict, type Schema } from \"./Schema\";\nimport type { AgentError, AgentMessage, Usage } from \"./types\";\n\n/**\n * What one model call needs, whether the agent loop makes it or `generate` does.\n *\n * Moved out of `Agent.ts` rather than copied when `generate` arrived (#594).\n * `generate` is the agent's step without the loop around it — assemble one\n * call, read the stream, parse the answer — so each of these would otherwise\n * exist twice, and the two copies of \"how is a structured answer parsed\" or\n * \"how is usage summed\" are exactly the kind that drift apart unnoticed.\n *\n * Internal. Nothing here is exported from `gemi/ai`.\n */\n\n// --- aborting --------------------------------------------------------------\n\nexport class RunAborted extends Error {\n constructor() {\n super(\"The run was stopped\");\n this.name = \"RunAborted\";\n }\n}\n\nexport function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(new RunAborted());\n }\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(new RunAborted());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n}\n\n// --- usage -----------------------------------------------------------------\n\nexport function emptyUsage(): Usage {\n return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n}\n\nexport function addUsage(total: Usage, next: Usage | undefined): Usage {\n if (!next) return total;\n const merged: Usage = {\n inputTokens: total.inputTokens + (next.inputTokens ?? 0),\n outputTokens: total.outputTokens + (next.outputTokens ?? 0),\n totalTokens: total.totalTokens + (next.totalTokens ?? 0),\n };\n // A breakdown stays absent until either side reports it, so a text run's\n // usage does not grow fields it never measured.\n for (const key of USAGE_BREAKDOWNS) {\n if (next[key] !== undefined || total[key] !== undefined) {\n merged[key] = (total[key] ?? 0) + (next[key] ?? 0);\n }\n }\n return merged;\n}\n\nconst USAGE_BREAKDOWNS = [\n \"reasoningTokens\",\n \"cachedInputTokens\",\n \"imageInputTokens\",\n \"imageOutputTokens\",\n \"audioInputTokens\",\n \"cachedAudioInputTokens\",\n \"audioOutputTokens\",\n] as const satisfies readonly (keyof Usage)[];\n\n// --- structured output -----------------------------------------------------\n\n/**\n * The best parse of a JSON document that is still arriving.\n *\n * Exists so a UI can bind fields before the object closes. It closes whatever\n * brackets are open and drops a trailing key with no value; when even that does\n * not parse it gives up and returns an empty object rather than throwing,\n * because a snapshot is a convenience and a run must not die for one.\n */\nexport function bestEffortParse(text: string): any {\n if (!text.trim()) return {};\n try {\n return JSON.parse(text);\n } catch {\n // fall through to repair\n }\n const closers: string[] = [];\n let inString = false;\n let escaped = false;\n for (const char of text) {\n if (inString) {\n if (escaped) escaped = false;\n else if (char === \"\\\\\") escaped = true;\n else if (char === '\"') inString = false;\n continue;\n }\n if (char === '\"') inString = true;\n else if (char === \"{\") closers.push(\"}\");\n else if (char === \"[\") closers.push(\"]\");\n else if (char === \"}\" || char === \"]\") closers.pop();\n }\n let repaired = text;\n if (inString) repaired += '\"';\n repaired = repaired.replace(/[,:]\\s*$/, \"\");\n const suffix = closers.reverse().join(\"\");\n try {\n return JSON.parse(repaired + suffix);\n } catch {\n // A trailing `\"key\":` leaves a property with no value; drop the key too.\n try {\n return JSON.parse(repaired.replace(/,?\\s*\"[^\"]*\"\\s*$/, \"\") + suffix);\n } catch {\n return {};\n }\n }\n}\n/**\n * The `output` parameter a provider is sent for a schema.\n *\n * `strict` is read off the schema, never chosen: an `s.json()` node anywhere in\n * it has no spelling in strict mode, so a schema containing one is sent\n * non-strict and the provider does not answer 400.\n */\nexport function outputFormat(schema: Schema<any>): NonNullable<ProviderStreamParams[\"output\"]> {\n return { name: \"output\", schema: schema.toJSONSchema(), strict: supportsStrict(schema) };\n}\n\n/**\n * A finished structured answer, checked against its schema.\n *\n * The failure is an `AgentError` with `code: \"invalid_output\"` rather than the\n * schema's own `errors: string[]`, so a caller branches on a code the way it\n * does for `invalid_tool_input`, and the list is joined into the message for a\n * person — or a retry prompt — to read.\n *\n * `bestEffortParse`, not `JSON.parse`, for the reason the agent loop has always\n * used it: the text is the whole answer by now, so the repair has nothing to\n * close, and a document that still does not parse comes back `{}` and fails the\n * schema with a message naming what is missing, instead of a `SyntaxError`\n * position nobody can act on. A cut-off answer never reaches here — see the\n * `length` checks in both callers — because a repaired prefix can pass a loose\n * schema and look finished.\n */\nexport function parseOutput<T>(\n schema: Schema<T>,\n text: string,\n): { ok: true; value: T } | { ok: false; error: AgentError } {\n const parsed = schema.safeParse(bestEffortParse(text));\n if (parsed.ok === true) return { ok: true, value: parsed.value };\n return {\n ok: false,\n error: {\n code: \"invalid_output\",\n message: `The model's structured answer did not match the output schema: ${parsed.errors.join(\", \")}`,\n retryable: true,\n },\n };\n}\n\n// --- building the assistant message ----------------------------------------\n\n/**\n * Resolves a string built by repeated concatenation, in place.\n *\n * `text = text + delta`, run once per streamed token, does not build a string —\n * it builds a rope: a tree of pointers to every fragment, which the engine\n * flattens only when something needs the characters contiguously. A message\n * that nothing reads before it is persisted therefore keeps all of its\n * fragments alive, and the tree costs several times the text.\n *\n * Measured on Bun 1.x, 600 deltas of six characters (a ~450-token answer, 3.5 KB\n * of ASCII): held as a rope, 18.7 KB. Resolved, 3.5 KB — half the UTF-16 size,\n * because a flat ASCII string is stored one byte per character and a rope\n * cannot be. That is 5.3x, and it is paid by every message a store keeps and\n * every run the live registry holds.\n *\n * Indexing is what forces the resolution: `text[0]` cannot be answered without\n * the characters, so the engine collapses the tree and drops the fragments.\n * Nothing is allocated and nothing is copied, which is why this is not\n * `split(\"\").join(\"\")` — that measures the same but allocates one string per\n * character to get there.\n *\n * DO NOT DELETE THIS AS A NO-OP. It reads like one and it is not; the value is\n * the side effect on the receiver. If a future engine does not resolve on\n * index, this silently becomes a real no-op and memory returns to what it is\n * today — a safe failure, which is why it is written as a hint rather than as a\n * round trip through an encoder that would also mangle a lone surrogate.\n */\nexport function resolveRope(text: string): string {\n if (text.length > 0) void text[0];\n return text;\n}\n\nexport function appendText(message: AgentMessage, type: \"text\" | \"reasoning\", delta: string) {\n const last = message.content[message.content.length - 1];\n if (last && last.type === type) {\n (last as { text?: string }).text = ((last as { text?: string }).text ?? \"\") + delta;\n return;\n }\n message.content.push(\n type === \"text\" ? { type: \"text\", text: delta } : { type: \"reasoning\", text: delta },\n );\n}\n\n/**\n * Reasoning is accumulated per ITEM, not per message, and the item's id is kept.\n *\n * This used to go through `appendText`, which merges on the part *type* alone\n * and has nowhere to put an id. Both halves of that were wrong and neither was\n * visible in the transcript:\n *\n * - `request.ts` drops a reasoning item with no id, deliberately — the id is\n * the API's handle on the stored reasoning and a fabricated one would look\n * like continuity that is not there. So an id dropped here meant reasoning\n * was never sent back at all: on a two-step run the model re-derived its\n * own argument from nothing, and the prompt cache (which keys on the\n * literal item) missed every time. Measured against the live Responses API\n * in `live/live.test.ts`: the second call's input carried zero reasoning\n * items.\n * - a step that produces two reasoning items was flattening them into one\n * part, so even with an id there would have been one id for two items'\n * text.\n *\n * A part with no id is still appended rather than dropped: the text is what a\n * UI renders, and a provider that reports no item id (Azure does not always)\n * should still show its thinking. It just cannot be echoed back, which is the\n * bargain `reasoningItem` already documents.\n */\nexport function appendReasoning(message: AgentMessage, id: string | undefined, delta: string) {\n const last = message.content[message.content.length - 1];\n if (last && last.type === \"reasoning\" && last.id === id) {\n last.text = (last.text ?? \"\") + delta;\n return;\n }\n message.content.push(\n id ? { type: \"reasoning\", id, text: delta } : { type: \"reasoning\", text: delta },\n );\n}\n",
10
- "import { createHmac, hkdfSync, randomBytes, timingSafeEqual } from \"crypto\";\nimport { defaultNonceStore, type NonceStore } from \"./store/Nonces\";\n\n/**\n * Signing for pending tool calls.\n *\n * A pending call travels through the browser and comes back — in stateless mode\n * the whole history does — so the server cannot trust that what it gets back is\n * what it sent. Without a signature the client asserts not just *that* a call\n * was approved but *what* was approved, and nothing would stop it from\n * returning `approve: true` against an input it rewrote on the way. Signing is\n * what makes the round trip safe, and it is why approvals need no server-side\n * storage at all.\n *\n * What is signed, and what deliberately is not:\n *\n * signed — `runId`, `toolCallId`, the tool `name`, the `kind` of pending call\n * and a canonical serialization of the input, plus a nonce, an\n * expiry, and — for a call a sub-agent asked — the `path` of\n * tool-call ids it is nested under.\n * not — the client's answer. `approve: true` / `approve: false` and a\n * question's output are the *point* of asking; a client that flips\n * its own answer has refused, not forged. What the signature buys is\n * that the answer is bound to the call the server actually made,\n * with the input the server actually saw.\n *\n * A verified token is not yet an answer the server may act on: it says the\n * question was asked, not that it is still open. `consumePendingCall` at the\n * bottom of this file spends the nonce, which is what makes an approval\n * single-use — see the note there for what that guarantee is worth.\n *\n * `kind` is in there for a specific attack: an `approval`-kind call is one the\n * *server* runs, so a client that reused its signature on the \"here is the\n * output\" arm of `ClientToolResult` would be fabricating a server tool's result\n * rather than approving it. Binding the kind makes that a forgery instead of a\n * shape the caller has to remember to check.\n *\n * Keys and principals (#447). Neither token kind is MACed with `SECRET`\n * itself: each is keyed with its own HKDF-derived key (`purposeKey` below), so\n * a MAC minted for one purpose — a pending call, a parked-run record, or\n * anything else in the app keyed off `SECRET` (CSRF, sessions) — is never a\n * MAC for another. And each binds the `subject`, the principal the run was\n * started for (`AgentController.runOwner`), so a token minted while user A was\n * asked cannot be answered by user B, even with A's history in hand.\n */\n\n/** Everything the signature commits to. */\nexport type PendingCallClaims = {\n runId: string;\n toolCallId: string;\n name: string;\n kind: \"approval\" | \"question\" | \"client\";\n input: unknown;\n /**\n * The chain of tool-call ids the call is nested under, outermost first.\n * Absent — or empty, which means the same thing — for a top-level call.\n *\n * A sub-agent's question reaches the user through its parent's pending list,\n * so `toolCallId` stops being an address on its own: two sub-runs under two\n * different tools can each hold a call the outer run never made. Binding the\n * path is what stops a token minted for a call nested under tool call X from\n * being replayed as a top-level call, or as one nested under Y.\n */\n path?: string[];\n /**\n * Who the question was asked of: the run's owner (`AgentController.runOwner`,\n * `user:<id>` by default). `null` or absent is nobody in particular — an\n * anonymous run — and the two are the same claim. A token minted for one\n * subject fails verification for any other, `null` included, so an approval\n * cannot be carried from one user's session to another's.\n */\n subject?: string | null;\n};\n\nexport type SignOptions = {\n /** Overrides `process.env.SECRET`. Exists for tests; apps use the app key. */\n secret?: string;\n /**\n * Default 24 hours. An approval waits on a human, and humans go to lunch —\n * a short expiry turns \"I approved it after standup\" into an unexplained\n * failure. Long enough to survive a working day, short enough that a token\n * lifted from a log is not useful next month.\n */\n ttlMs?: number;\n /** Injected clock, so the expiry path is testable without waiting. */\n now?: number;\n};\n\nexport type VerifyOptions = {\n secret?: string;\n now?: number;\n};\n\n/**\n * A discriminated result rather than a boolean, because the two failures are\n * different events: `expired` is a sentence to show the user, `forged` is worth\n * logging and possibly alerting on. Collapsing them loses the only signal that\n * says someone is probing.\n */\nexport type VerifyResult =\n | { ok: true; runId: string; nonce: string; expiresAt: number }\n | { ok: false; reason: \"malformed\" | \"expired\" | \"forged\" };\n\n/**\n * `agt2` is minted; `agt1` is still verified. A v1 token was MACed with the raw\n * `SECRET` and binds no subject — it is accepted so that a question asked\n * before the upgrade can still be answered after it, and it stops mattering on\n * its own when the last one expires (`DEFAULT_TTL_MS` after the deploy). Drop\n * `LEGACY_VERSION` from the accepted set once that window is long past.\n */\nconst VERSION = \"agt2\";\nconst LEGACY_VERSION = \"agt1\";\nconst PENDING_VERSIONS = [VERSION, LEGACY_VERSION];\nconst DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;\n\n/**\n * The latest expiry a legacy token may claim. Every v1 token this process can\n * legitimately see was minted by an earlier deploy with the default TTL, so it\n * expires no later than one TTL after this module loaded. Bounding it here\n * means a v1 token — MACed with the raw `SECRET`, the key this change exists to\n * stop relying on — cannot be forged with a far-future expiry, and that after\n * one TTL of uptime no v1 token verifies at all.\n */\nconst LEGACY_ACCEPTED_UNTIL = Date.now() + DEFAULT_TTL_MS;\n\nfunction legacyExpiryOk(expiresAt: number): boolean {\n return expiresAt <= LEGACY_ACCEPTED_UNTIL;\n}\n\n/**\n * HKDF `info` labels, one per thing a key signs. Changing a label is a key\n * rotation for that purpose alone.\n */\nconst PENDING_CALL_PURPOSE = \"gemi.ai.pending-call.v1\";\nconst NESTED_RUN_PURPOSE = \"gemi.ai.nested-run.v1\";\nconst EXECUTION_RECEIPT_PURPOSE = \"gemi.ai.execution-receipt.v1\";\nconst HKDF_SALT = \"gemi.ai.signing\";\n\nconst derivedKeys = new Map<string, Buffer>();\n\n/**\n * A key for one purpose, derived from the app secret with HKDF-SHA256.\n *\n * `SECRET` is also what CSRF tokens and sessions are keyed with. Using it as\n * the HMAC key here would make every one of those a potential oracle for the\n * others; HKDF with a purpose label gives each its own independent key, so a\n * weakness or leak in one use cannot be turned against another — including\n * the two token kinds in this file against each other.\n *\n * Memoized per (purpose, secret): verification is on the request path and the\n * derivation is pure. The map is bounded by the number of purposes times the\n * secrets a process ever sees, which is one outside of tests.\n */\nexport function purposeKey(purpose: string, override?: string): Buffer {\n const secret = secretKey(override);\n const cacheKey = `${purpose}\\u0000${secret}`;\n let key = derivedKeys.get(cacheKey);\n if (!key) {\n key = Buffer.from(hkdfSync(\"sha256\", secret, HKDF_SALT, purpose, 32));\n if (derivedKeys.size > 64) derivedKeys.clear();\n derivedKeys.set(cacheKey, key);\n }\n return key;\n}\n\nfunction secretKey(override?: string): string {\n const secret = override ?? process.env.SECRET;\n if (!secret) {\n // Refusing is the only safe answer. A fallback constant would make every\n // approval in every deployment forgeable by anyone who read this file, and\n // it would do it silently — the feature would appear to work.\n throw new Error(\n \"Signing a pending tool call needs an app secret. Set SECRET in the environment.\",\n );\n }\n return secret;\n}\n\n/**\n * Serializes a value so that the same value always produces the same string.\n *\n * `JSON.stringify` is not enough: it preserves insertion order, so an input\n * that made a round trip through a client — parsed and re-serialized, with the\n * keys in whatever order the parser produced — would hash differently and a\n * legitimate approval would come back looking forged. Keys are sorted,\n * `undefined` members are dropped (they do not survive JSON anyway), and arrays\n * keep their order because in an array order *is* the value.\n */\nexport function canonicalize(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value) ?? \"null\";\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalize).join(\",\")}]`;\n }\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record)\n .filter((key) => record[key] !== undefined)\n .sort();\n return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalize(record[key])}`).join(\",\")}}`;\n}\n\n/**\n * Length-prefixed rather than delimiter-joined. A separator is a place for two\n * different claim sets to hash the same — `runId: \"a\", toolCallId: \"b|c\"` and\n * `runId: \"a|b\", toolCallId: \"c\"` — and while neither field contains the\n * separator today, that is a property of the id generator, not of this code.\n */\nfunction payload(fields: string[]): string {\n return fields.map((field) => `${field.length}:${field}`).join(\"\");\n}\n\nfunction mac(key: string | Buffer, fields: string[]): Buffer {\n return createHmac(\"sha256\", key).update(payload(fields)).digest();\n}\n\nfunction macMatches(signature: string, expected: Buffer): boolean {\n const presented = Buffer.from(signature.split(\".\")[4], \"base64url\");\n // `timingSafeEqual` throws on a length mismatch, and a wrong length is\n // already a public fact about the token — nothing is leaked by checking it\n // first, and everything is leaked by comparing the bytes with `===`.\n return presented.length === expected.length && timingSafeEqual(presented, expected);\n}\n\n/** The principal as a field: absent and `null` are the same claim. */\nfunction subjectField(subject: string | null | undefined): string {\n return canonicalize(subject ?? null);\n}\n\n/**\n * The v2 claim set. Fixed-length: the path is always present (`[]` at the top\n * level) and so is the subject, so there is no optional field to reason about.\n */\nfunction claimFields(claims: PendingCallClaims, nonce: string, expiresAt: number): string[] {\n return [\n VERSION,\n claims.runId,\n claims.toolCallId,\n claims.name,\n claims.kind,\n nonce,\n String(expiresAt),\n canonicalize(claims.input),\n canonicalize(claims.path ?? []),\n subjectField(claims.subject),\n ];\n}\n\n/**\n * The v1 claim set, kept only to verify tokens minted before #447.\n *\n * The path is appended, and only when there is one.\n *\n * Byte-identical output for a call with no path is the whole requirement here:\n * every approval already in flight was minted from the eight fields below, and\n * a ninth field carrying `\"[]\"` or `\"undefined\"` would invalidate all of them\n * on deploy — the user who clicked Approve before the release would be told\n * their answer was forged. So an absent path adds nothing at all, and an empty\n * array is treated as absent because it says the same thing.\n *\n * `payload` is length-prefixed, so appending a field cannot collide with a\n * longer value in the one before it; that is why this can be an append rather\n * than a new version tag.\n */\nfunction legacyClaimFields(claims: PendingCallClaims, nonce: string, expiresAt: number): string[] {\n const fields = [\n LEGACY_VERSION,\n claims.runId,\n claims.toolCallId,\n claims.name,\n claims.kind,\n nonce,\n String(expiresAt),\n canonicalize(claims.input),\n ];\n if (claims.path && claims.path.length > 0) {\n fields.push(canonicalize(claims.path));\n }\n return fields;\n}\n\nconst encode = (value: string) => Buffer.from(value, \"utf8\").toString(\"base64url\");\nconst decode = (value: string) => Buffer.from(value, \"base64url\").toString(\"utf8\");\n\n/** `agt2.<runId>.<nonce>.<expiry>.<mac>`, all base64url or base36. */\nexport function signPendingCall(claims: PendingCallClaims, options: SignOptions = {}): string {\n const key = purposeKey(PENDING_CALL_PURPOSE, options.secret);\n const now = options.now ?? Date.now();\n const expiresAt = now + (options.ttlMs ?? DEFAULT_TTL_MS);\n const nonce = randomBytes(12).toString(\"base64url\");\n const signature = mac(key, claimFields(claims, nonce, expiresAt)).toString(\"base64url\");\n return [VERSION, encode(claims.runId), nonce, expiresAt.toString(36), signature].join(\".\");\n}\n\n/**\n * The metadata a signature carries in the clear.\n *\n * `Agent` needs the issuing `runId` before it can verify anything: the call was\n * signed under the run that made it, and the turn answering it is a *new* run\n * with a new id. Reading it out of the token is safe because the token's own\n * MAC covers it — a client that edits the runId here fails verification, so\n * this is \"which run does this claim to belong to\", not \"which run does the\n * client say it belongs to\".\n */\nexport function readSignature(\n signature: string,\n): { runId: string; nonce: string; expiresAt: number } | null {\n return readToken(signature, PENDING_VERSIONS);\n}\n\n/**\n * The version tag is checked here and nowhere else, which is what keeps the\n * two token kinds apart: a parked-run record presented where a pending call's\n * signature is expected fails as malformed before its MAC is even looked at,\n * and the other way round. Their claim sets are different lengths and would\n * not collide anyway, but a tag makes that a rule rather than an accident of\n * the field count.\n */\nfunction readToken(\n signature: string,\n versions: readonly string[],\n): { runId: string; nonce: string; expiresAt: number; version: string } | null {\n const parts = signature.split(\".\");\n if (parts.length !== 5 || !versions.includes(parts[0])) {\n return null;\n }\n const expiresAt = Number.parseInt(parts[3], 36);\n if (!Number.isFinite(expiresAt)) {\n return null;\n }\n try {\n return { runId: decode(parts[1]), nonce: parts[2], expiresAt, version: parts[0] };\n } catch {\n return null;\n }\n}\n\nexport function verifyPendingCall(\n signature: string,\n claims: PendingCallClaims,\n options: VerifyOptions = {},\n): VerifyResult {\n const parsed = readToken(signature, PENDING_VERSIONS);\n if (!parsed) {\n return { ok: false, reason: \"malformed\" };\n }\n\n if (parsed.version === LEGACY_VERSION && !legacyExpiryOk(parsed.expiresAt)) {\n return { ok: false, reason: \"forged\" };\n }\n const expected =\n parsed.version === LEGACY_VERSION\n ? // Raw secret, no subject: see `LEGACY_VERSION`.\n mac(secretKey(options.secret), legacyClaimFields(claims, parsed.nonce, parsed.expiresAt))\n : mac(\n purposeKey(PENDING_CALL_PURPOSE, options.secret),\n claimFields(claims, parsed.nonce, parsed.expiresAt),\n );\n if (!macMatches(signature, expected)) {\n return { ok: false, reason: \"forged\" };\n }\n\n // Expiry is checked *after* the MAC on purpose: only a genuine token can be\n // \"expired\". Reporting a forgery as expired would tell the UI to say \"your\n // approval timed out\" to someone who was tampering.\n if ((options.now ?? Date.now()) > parsed.expiresAt) {\n return { ok: false, reason: \"expired\" };\n }\n\n return { ok: true, runId: parsed.runId, nonce: parsed.nonce, expiresAt: parsed.expiresAt };\n}\n\n// --- parked sub-runs -----------------------------------------------------\n\n/**\n * What a parked sub-run's record is signed over.\n *\n * `ToolCallPart.nested` is the parent's own record of where a sub-run stopped,\n * and in stateless mode it makes the same trip through the browser a pending\n * call does. The next turn *runs a tool* on the strength of that record — the\n * tool is re-entered because the record says a sub-run under it is waiting on\n * the question being answered — so an unsigned record lets the client choose\n * which tools run, with what input, before any answer is verified. A MAC over\n * what the server actually recorded is what makes the record safe to carry.\n *\n * Only a parked record is signed, because only a parked record executes\n * anything: a finished sub-run is replayed out of its transcript and spends\n * nothing, and a client that forges one has fed its own tool a made-up answer,\n * which a client-carried history already allows everywhere.\n *\n * Deliberately not signed: the transcript. The sub-run resumes from messages\n * the client carried, exactly as the parent does in stateless mode, and the\n * same argument applies — what the signature pins is that the server parked\n * *here*, on *these* calls, with *this* input, and not what was said on the\n * way.\n */\nexport type NestedRunClaims = {\n /** The root run's id, the one every pending call of the tree is minted under. */\n runId: string;\n /**\n * Tool-call ids from the root down to and including the call the record\n * hangs off. A sub-run's id is not an address on its own for the same reason\n * a nested call's is not: two sub-runs under two different tools can carry\n * the same one.\n */\n path: string[];\n /** The sub-run's own id, so a record cannot be moved between sub-runs. */\n nestedRunId: string;\n /** The tool calls the sub-run is waiting on: every call left open in its transcript. */\n open: string[];\n /**\n * The input the tool that parked was running on, as the transcript carries\n * it. Re-entry runs the tool body with the input the history holds, and the\n * history is the client's — so a record that pinned where the sub-run parked\n * but not what its tool was given would let the client keep the run and\n * rewrite the arguments to anything the schema accepts. The same bargain a\n * pending call makes: the input executed is the input signed.\n */\n input: unknown;\n /** The run's owner, as on `PendingCallClaims.subject`: a record parked for\n * one principal does not re-enter a tool for another. */\n subject?: string | null;\n};\n\n/** `agn2` is minted; `agn1` (raw secret, no subject) is still verified. See\n * `LEGACY_VERSION`. */\nconst NESTED_VERSION = \"agn2\";\nconst LEGACY_NESTED_VERSION = \"agn1\";\nconst NESTED_VERSIONS = [NESTED_VERSION, LEGACY_NESTED_VERSION];\n\nfunction nestedFields(claims: NestedRunClaims, nonce: string, expiresAt: number): string[] {\n return [\n ...legacyNestedFields(claims, nonce, expiresAt, NESTED_VERSION),\n subjectField(claims.subject),\n ];\n}\n\nfunction legacyNestedFields(\n claims: NestedRunClaims,\n nonce: string,\n expiresAt: number,\n version = LEGACY_NESTED_VERSION,\n): string[] {\n return [\n version,\n claims.runId,\n canonicalize(claims.path),\n claims.nestedRunId,\n nonce,\n String(expiresAt),\n // A set, so it is sorted: the ids are read back out of a transcript the\n // client re-serialized, and message order is not part of the claim.\n canonicalize([...claims.open].sort()),\n canonicalize(claims.input),\n ];\n}\n\n/**\n * Same shape as a pending call's token, so the same reader serves both — nonce\n * included, and the nonce is spent, by `consumeNestedRun` below. A verified\n * record is permission to run the tool it hangs off, and the tool body runs\n * before the sub-run gets to look at the answer's own nonce; a record that\n * could be presented twice would run the body twice before anything refused\n * the replay. Every park mints a fresh record, so spending one costs a\n * legitimate re-park nothing.\n */\nexport function signNestedRun(claims: NestedRunClaims, options: SignOptions = {}): string {\n const key = purposeKey(NESTED_RUN_PURPOSE, options.secret);\n const now = options.now ?? Date.now();\n const expiresAt = now + (options.ttlMs ?? DEFAULT_TTL_MS);\n const nonce = randomBytes(12).toString(\"base64url\");\n const signature = mac(key, nestedFields(claims, nonce, expiresAt)).toString(\"base64url\");\n return [NESTED_VERSION, encode(claims.runId), nonce, expiresAt.toString(36), signature].join(\".\");\n}\n\n/**\n * The run that verifies a record is never the run that minted it — the turn\n * answering a question is a new run with a new id — so the minting run's id is\n * read out of the token rather than asked of the caller, which has no other\n * source for it. The MAC covers it, so a client that edits the id in the clear\n * fails here rather than being believed.\n */\nexport function verifyNestedRun(\n signature: string,\n claims: Omit<NestedRunClaims, \"runId\">,\n options: VerifyOptions = {},\n): VerifyResult {\n const parsed = readToken(signature, NESTED_VERSIONS);\n if (!parsed) {\n return { ok: false, reason: \"malformed\" };\n }\n\n if (parsed.version === LEGACY_NESTED_VERSION && !legacyExpiryOk(parsed.expiresAt)) {\n return { ok: false, reason: \"forged\" };\n }\n const full = { ...claims, runId: parsed.runId };\n const expected =\n parsed.version === LEGACY_NESTED_VERSION\n ? mac(secretKey(options.secret), legacyNestedFields(full, parsed.nonce, parsed.expiresAt))\n : mac(\n purposeKey(NESTED_RUN_PURPOSE, options.secret),\n nestedFields(full, parsed.nonce, parsed.expiresAt),\n );\n if (!macMatches(signature, expected)) {\n return { ok: false, reason: \"forged\" };\n }\n\n // A parked record outlives its usefulness with the answers it exists to\n // deliver: those expire on the pending call's TTL, and a record older than\n // that can route nothing that would still verify.\n if ((options.now ?? Date.now()) > parsed.expiresAt) {\n return { ok: false, reason: \"expired\" };\n }\n\n return { ok: true, runId: parsed.runId, nonce: parsed.nonce, expiresAt: parsed.expiresAt };\n}\n\n// --- single use ----------------------------------------------------------\n\n/**\n * Spending a nonce.\n *\n * The MAC makes a token unforgeable; it does not make it single-use. Without\n * this a captured signature approves the same call again every time it is\n * presented, because a token that carries its own `runId` is a token that\n * asserts its own binding — which is no binding at all. Verifying tells you the\n * server once asked this exact question; spending the nonce is what says nobody\n * has answered it yet.\n *\n * Where spent nonces live is a `NonceStore` (`store/Nonces.ts`, #445). The\n * default is the process-wide `MemoryNonceStore`, which is exact for one\n * instance; an app with several instances gives the agent a shared store\n * (`RedisNonceStore`, or a table) so a rewound history cannot be replayed once\n * against each of them. The store's `consume` is insert-if-absent, so two\n * instances answering at once cannot both win.\n *\n * The other guard is the app's own message store: once a call has a result\n * next to it, the call is no longer open and the answer has nothing to attach\n * to. This is what stands in for that in stateless mode, where the history the\n * client returns can be rewound to before the result existed.\n */\n\n/**\n * The id an approved call's execution receipt is kept under (#458).\n *\n * Deterministic in the call the signature covers — the issuing run, the tool\n * call id, the tool, its canonical input, the nesting path and the subject —\n * and in nothing else, so every presentation of one approval, on any instance,\n * names the same receipt. Not in the nonce or expiry: those identify one\n * *token*, and a receipt identifies the *execution* it authorizes.\n *\n * An HMAC under its own HKDF-derived key rather than a plain hash, so an id in\n * a shared store is neither a MAC for anything else nor something a client can\n * compute to probe the store for another user's calls.\n */\nexport function executionReceiptId(\n agent: string,\n claims: PendingCallClaims,\n options: { secret?: string } = {},\n): string {\n const key = purposeKey(EXECUTION_RECEIPT_PURPOSE, options.secret);\n return mac(key, [\n agent,\n claims.runId,\n claims.toolCallId,\n claims.name,\n claims.kind,\n canonicalize(claims.input),\n canonicalize(claims.path ?? []),\n subjectField(claims.subject),\n ]).toString(\"base64url\");\n}\n\n/**\n * Spends a signature's nonce in `store`. `false` means it was already spent —\n * the answer is a replay and must not be acted on — or the token is malformed.\n * A store that throws rejects; the caller refuses the answer.\n *\n * Separate from `verifyPendingCall` rather than folded into it, because verify\n * is a pure question a caller may want to ask twice (logging a forgery, say)\n * and this one is a state change that must happen exactly once per answer.\n */\nexport function spendPendingCall(signature: string, store: NonceStore): Promise<boolean> {\n return spendIn(store, readSignature(signature));\n}\n\n/**\n * Spends a parked-run record's nonce, on the same store and the same terms.\n * `false` means the record has already re-entered its tool once — the turn is\n * a replay of a history from before the answer was delivered, and the body\n * must not run again on it.\n */\nexport function spendNestedRun(signature: string, store: NonceStore): Promise<boolean> {\n return spendIn(store, readToken(signature, NESTED_VERSIONS));\n}\n\nasync function spendIn(\n store: NonceStore,\n parsed: { nonce: string; expiresAt: number } | null,\n): Promise<boolean> {\n if (!parsed) return false;\n return store.consume(parsed.nonce, parsed.expiresAt);\n}\n\n/** `spendPendingCall` on the process-wide default store, synchronously.\n * `now` is injectable for tests. */\nexport function consumePendingCall(signature: string, options: VerifyOptions = {}): boolean {\n const parsed = readSignature(signature);\n return parsed\n ? defaultNonceStore.consumeSync(parsed.nonce, parsed.expiresAt, options.now)\n : false;\n}\n\n/** `spendNestedRun` on the process-wide default store, synchronously. */\nexport function consumeNestedRun(signature: string, options: VerifyOptions = {}): boolean {\n const parsed = readToken(signature, NESTED_VERSIONS);\n return parsed\n ? defaultNonceStore.consumeSync(parsed.nonce, parsed.expiresAt, options.now)\n : false;\n}\n",
11
- "import type { AgentError } from \"../types\";\n\n/**\n * A non-2xx response, carried as an exception so the retry loop and\n * `normalizeError` can both read it.\n *\n * The body is kept parsed-if-possible and raw-if-not: OpenAI and Azure both\n * answer `{ error: { message, type, code } }` on a good day, and an HTML error\n * page from a proxy on a bad one, and the bad day is exactly when the text\n * matters.\n */\nexport class ProviderHttpError extends Error {\n readonly status: number;\n readonly body: unknown;\n readonly requestId?: string;\n\n constructor(status: number, body: unknown, requestId?: string) {\n super(`Provider request failed with status ${status}: ${describeBody(body)}`);\n this.name = \"ProviderHttpError\";\n this.status = status;\n this.body = body;\n this.requestId = requestId;\n }\n}\n\n/**\n * The request ran out of time. Its own class because it must not read as a\n * user abort: `stop()` means the person is done, and a timeout means the\n * network was, and only one of those is worth trying again.\n */\nexport class ProviderTimeoutError extends Error {\n readonly timeoutMs: number;\n\n constructor(timeoutMs: number) {\n super(`Provider request timed out after ${timeoutMs}ms`);\n this.name = \"ProviderTimeoutError\";\n this.timeoutMs = timeoutMs;\n }\n}\n\nfunction describeBody(body: unknown): string {\n const detail = errorBody(body);\n if (detail?.message) return detail.message;\n if (typeof body === \"string\") return body.slice(0, 500);\n return \"no error body\";\n}\n\ntype OpenAIErrorBody = { message?: string; type?: string; code?: string; param?: string };\n\nfunction errorBody(body: unknown): OpenAIErrorBody | null {\n if (!body || typeof body !== \"object\") return null;\n const wrapper = body as { error?: unknown };\n const inner = wrapper.error && typeof wrapper.error === \"object\" ? wrapper.error : body;\n const e = inner as OpenAIErrorBody & { innererror?: { code?: string } };\n if (typeof e.message !== \"string\" && typeof e.code !== \"string\" && typeof e.type !== \"string\") {\n return null;\n }\n // Azure hides the interesting code one level down when its content filter\n // fires, and the outer code is the useless `content_filter`.\n const code = e.innererror?.code ?? e.code;\n return { message: e.message, type: e.type, code, param: e.param };\n}\n\n/**\n * The HTTP status and request id of a provider failure, read off what was\n * thrown — server-side detail for `AgentRunResult.error`, never for a frame.\n *\n * By shape rather than by `instanceof ProviderHttpError`, so a custom provider\n * whose SDK throws its own error class with a `status` gets the same detail.\n * A `status` outside 100–599 is not an HTTP status and is ignored.\n */\nexport function httpErrorDetail(error: unknown): { status?: number; requestId?: string } {\n if (!error || typeof error !== \"object\") return {};\n const { status, requestId } = error as { status?: unknown; requestId?: unknown };\n return {\n ...(typeof status === \"number\" && status >= 100 && status <= 599 ? { status } : {}),\n ...(typeof requestId === \"string\" && requestId ? { requestId } : {}),\n };\n}\n\n/**\n * Provider failures onto `AgentErrorCode`.\n *\n * The contract an app is buying here is that it can branch on `rate_limited`\n * without knowing whose rate limit it was, and on `retryable` without knowing\n * which of the two APIs answered. So `retryable` is set from what is actually\n * true of the failure — a 429 from a spent quota is not retryable no matter\n * what its status code says, and neither is a request that will be too long\n * again next time.\n */\nexport function normalizeProviderError(error: unknown): AgentError {\n if (error instanceof ProviderTimeoutError) {\n return { code: \"provider_error\", message: error.message, retryable: true };\n }\n\n if (isAbort(error)) {\n return { code: \"aborted\", message: \"The request was aborted.\", retryable: false };\n }\n\n if (error instanceof ProviderHttpError) {\n return fromStatus(error.status, errorBody(error.body), error.message);\n }\n\n // `fetch` rejects with a TypeError for DNS failures, refused connections and\n // dropped sockets. Every one of those is worth another attempt.\n if (error instanceof TypeError) {\n return {\n code: \"provider_error\",\n message: `Could not reach the provider: ${error.message}`,\n retryable: true,\n };\n }\n\n if (error instanceof Error) {\n return { code: \"provider_error\", message: error.message, retryable: false };\n }\n\n return { code: \"unknown\", message: String(error), retryable: false };\n}\n\nfunction fromStatus(\n status: number,\n body: OpenAIErrorBody | null,\n fallbackMessage: string,\n): AgentError {\n const message = body?.message ?? fallbackMessage;\n const code = (body?.code ?? \"\").toLowerCase();\n const type = (body?.type ?? \"\").toLowerCase();\n const haystack = `${code} ${type} ${message}`.toLowerCase();\n\n if (status === 429) {\n // A spent quota answers 429 and will answer 429 for the rest of the month.\n // Retrying it is how a run turns one billing problem into `maxRetries`\n // billing problems and a much later error message.\n const outOfCredit = code === \"insufficient_quota\" || haystack.includes(\"quota\");\n return { code: \"rate_limited\", message, retryable: !outOfCredit };\n }\n\n if (status >= 500 || status === 408 || status === 409) {\n return { code: \"provider_error\", message, retryable: true };\n }\n\n if (isContextLength(haystack)) {\n return { code: \"context_length_exceeded\", message, retryable: false };\n }\n\n if (isContentFilter(haystack)) {\n return { code: \"content_filtered\", message, retryable: false };\n }\n\n // A schema the API refused. It is our request that is wrong, so the run\n // should surface it as a tool problem rather than a generic outage.\n if (body?.param?.startsWith(\"tools\") || haystack.includes(\"invalid schema for function\")) {\n return { code: \"invalid_tool_input\", message, retryable: false };\n }\n\n return { code: \"provider_error\", message, retryable: false };\n}\n\nfunction isContextLength(haystack: string): boolean {\n return (\n haystack.includes(\"context_length_exceeded\") ||\n haystack.includes(\"maximum context length\") ||\n haystack.includes(\"context window\") ||\n haystack.includes(\"reduce the length\")\n );\n}\n\nfunction isContentFilter(haystack: string): boolean {\n return (\n haystack.includes(\"content_filter\") ||\n haystack.includes(\"content_policy_violation\") ||\n haystack.includes(\"responsibleaipolicyviolation\") ||\n haystack.includes(\"content management policy\")\n );\n}\n\nfunction isAbort(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const e = error as { name?: string; code?: string };\n return e.name === \"AbortError\" || e.code === \"ABORT_ERR\";\n}\n",
12
- "/**\n * Bounding what a long thread sends to the model (#473).\n *\n * A threaded conversation grows without end, and before this nothing in gemi\n * bounded what a turn sent: the whole `loadThread` went to the provider until\n * it answered `context_length_exceeded`. These are the pieces an app needs to\n * bound it where the model call is, rather than in its store:\n *\n * - `turnStarts` / `splitTurns`: where the user's turns begin. A cut made at\n * one never separates a tool call from its result, since a result is stored\n * in the message that made the call, and never strands a tool-injected file\n * message (user role, but not a turn) from the call that showed it.\n * - `windowMessages`: a built-in policy over those turns (at most N turns, at\n * most N bytes or approximate tokens), with cut points that move in steps so\n * the provider's prompt cache keeps hitting.\n *\n * `Agent.create({ contextWindow })` applies the policy on every model call, and\n * `prepareStep` is the hook for anything else. Neither changes what is stored:\n * they shape the request, and the run's history, `onMessage` and the store\n * see every message as before.\n */\n\nimport type { ContextCompactOptions } from \"./contextCompaction\";\nimport type { AgentMessage, ToolCallPart, ToolSearchRecord } from \"./types\";\n\n/**\n * The ids of the messages a tool injected to show a file, read from the\n * `ToolCallPart.attachments` records in `messages`.\n *\n * The record is the test, not `attachmentId` on the part: a user's own upload\n * carries an `attachmentId` too. Such a message has the user's role but is not\n * the user's turn, which is why `turnStarts` steps over it.\n */\nexport function injectedMessageIds(messages: readonly AgentMessage[]): Set<string> {\n const injected = new Set<string>();\n for (const message of messages) {\n for (const part of message.content ?? []) {\n if (part.type !== \"tool-call\") continue;\n for (const record of part.attachments ?? []) {\n if (record && \"shown\" in record && record.shown) injected.add(record.shown.messageId);\n }\n }\n }\n return injected;\n}\n\n/**\n * The index of the first message of every turn in `messages`.\n *\n * A turn starts at a user message that no tool injected, and runs until the\n * next one: the assistant's steps, their tool calls with their results (which\n * are stored on the same message as the call), and any file a tool showed.\n * Index 0 always starts a turn, so messages before the first user message (a\n * greeting, a run cut short before its turn was stored) belong to the first\n * turn rather than to none. Empty for an empty list.\n */\nexport function turnStarts(messages: readonly AgentMessage[]): number[] {\n if (messages.length === 0) return [];\n const injected = injectedMessageIds(messages);\n const starts = [0];\n for (let index = 1; index < messages.length; index++) {\n const message = messages[index]!;\n if (message.role === \"user\" && !injected.has(message.id)) starts.push(index);\n }\n return starts;\n}\n\n/** `messages` grouped into turns. See `turnStarts`. */\nexport function splitTurns(messages: readonly AgentMessage[]): AgentMessage[][] {\n const starts = turnStarts(messages);\n return starts.map((start, index) => messages.slice(start, starts[index + 1] ?? messages.length));\n}\n\n/**\n * Roughly how much a message costs to send: the length of its JSON. A file\n * part counts as its reference, not its bytes, which is what the request\n * carries. Good enough to budget with, and the same number for the same\n * message every time, which is what keeps a cut point stable.\n */\nexport function messageSize(message: AgentMessage): number {\n try {\n return JSON.stringify(message).length;\n } catch {\n return 0;\n }\n}\n\n/** Characters per token when a budget is given in `maxTokens`. */\nconst CHARS_PER_TOKEN = 4;\n\n/** `ContextWindowOptions.step`'s default. */\nexport const DEFAULT_CONTEXT_WINDOW_STEP = 10;\n\n/** `ContextWindowOptions.note`'s default. */\nexport const DEFAULT_CONTEXT_WINDOW_NOTE = \"[Earlier turns of this conversation are not shown.]\";\n\nexport type ContextWindowOptions = {\n /** The most turns sent. The latest turn is always sent, whatever the limits. */\n maxTurns?: number;\n /**\n * The most characters of message JSON sent (see `messageSize`). The system\n * prompt and the tools' schemas are not counted.\n */\n maxBytes?: number;\n /**\n * The same budget in approximate tokens (four characters each). When both\n * are given, the smaller one applies.\n */\n maxTokens?: number;\n /**\n * How many turns the start of the window moves at a time. Default 10.\n *\n * A window that slid one turn per turn would send a different first message\n * on every turn, and the provider's prompt cache (a prefix cache) would miss\n * on every turn. With a step, the first kept turn is the 0th, the 10th, the\n * 20th, … of the thread, so consecutive turns send the same prefix until the\n * window has to move again. The cost is that the window holds up to `step`\n * fewer turns than the limits would allow. `1` slides one turn at a time.\n */\n step?: number;\n /**\n * Put at the start of the first kept turn when turns were left out, so the\n * model knows the conversation goes back further. Default\n * `DEFAULT_CONTEXT_WINDOW_NOTE`; `false` for none. A function gets how much\n * was left out and answers the text, or `false`.\n */\n note?: string | false | ((omitted: { turns: number; messages: number }) => string | false);\n /**\n * Summarise the turns left out instead of dropping them (#782). Off unless\n * set; `true` uses the defaults. Applies to a run with a `threadId` (a\n * stored thread), at the top level; anything else, stateless threads\n * included, gets the plain window. `windowMessages` itself ignores it. See\n * `ContextCompactOptions`.\n *\n * Turns are summarised when the window leaves them out and, with\n * `compact.triggerTokens`, once the turns sent would be over that many\n * tokens. The summary is made with one or more provider calls when the\n * window's start moves (every `step` turns), usually in the background\n * after the turn before; kept per thread in a `SummaryStore`; and sent as a\n * user message in front of the kept turns, in place of `note`. Its usage is\n * billed once, to a run that waits on it or uses it. If it fails, the run\n * sends the plain window with `note`.\n */\n compact?: boolean | ContextCompactOptions;\n};\n\nexport type ContextWindowResult = {\n /** What to send. New objects only where something changed (the note, a\n * carried search); every other message is the one passed in. */\n messages: AgentMessage[];\n /** The index in the input of the first kept turn's first message. */\n start: number;\n /** How many turns and messages were left out. Both 0 when nothing was. */\n omittedTurns: number;\n omittedMessages: number;\n};\n\n/**\n * The latest turns of `messages` that fit `options`.\n *\n * - Cuts only at a turn start (`turnStarts`), so a tool call keeps its result\n * and a tool-injected file stays below the call that showed it.\n * - Always keeps the latest turn, even when it alone is over the budget: an\n * empty request is worse than an oversized one, and the provider is the\n * judge of whether it fits.\n * - Moves the cut `step` turns at a time, counted from the thread's first\n * turn, so the prefix sent stays the same from turn to turn (see `step`).\n * When no step-aligned cut fits (one huge turn), it falls back to the\n * earliest turn that does.\n * - Keeps `system` messages from before the cut, at the front: they are\n * instructions, not conversation.\n * - Carries tool searches over the cut (#777). A namespaced or deferred tool\n * is only loaded for the model by a search in its history, so a kept call to\n * one whose search was left out gets that search put back on it (on a copy).\n *\n * Pure: the input is never changed, and the same input gives the same output.\n */\nexport function windowMessages(\n messages: readonly AgentMessage[],\n options: ContextWindowOptions = {},\n): ContextWindowResult {\n const all = [...messages];\n const starts = turnStarts(all);\n const budget = byteBudget(options);\n const maxTurns = positive(options.maxTurns) ?? Infinity;\n const step = Math.max(1, Math.floor(positive(options.step) ?? DEFAULT_CONTEXT_WINDOW_STEP));\n\n if (starts.length <= 1 || (maxTurns >= starts.length && budget === Infinity)) {\n return { messages: all, start: 0, omittedTurns: 0, omittedMessages: 0 };\n }\n\n // Characters from each message to the end: what a cut there would send.\n // System messages kept from before the cut are not counted.\n const sizeFrom: number[] = Array.from({ length: all.length + 1 }, () => 0);\n if (budget !== Infinity) {\n for (let index = all.length - 1; index >= 0; index--) {\n sizeFrom[index] = sizeFrom[index + 1]! + messageSize(all[index]!);\n }\n }\n const fits = (turn: number) =>\n starts.length - turn <= maxTurns && sizeFrom[starts[turn]!]! <= budget;\n\n let first = -1;\n for (let turn = 0; turn < starts.length; turn += step) {\n if (fits(turn)) {\n first = turn;\n break;\n }\n }\n if (first < 0) {\n for (let turn = 0; turn < starts.length; turn++) {\n if (fits(turn)) {\n first = turn;\n break;\n }\n }\n }\n if (first < 0) first = starts.length - 1;\n if (first === 0) return { messages: all, start: 0, omittedTurns: 0, omittedMessages: 0 };\n\n const start = starts[first]!;\n const dropped = all.slice(0, start);\n const pinned = dropped.filter((message) => message.role === \"system\");\n const kept = carrySearches(dropped, all.slice(start));\n\n const omitted = { turns: first, messages: dropped.length - pinned.length };\n const note =\n typeof options.note === \"function\"\n ? options.note(omitted)\n : options.note === undefined\n ? DEFAULT_CONTEXT_WINDOW_NOTE\n : options.note;\n if (note) {\n const head = kept[0]!;\n kept[0] = { ...head, content: [{ type: \"text\", text: note }, ...head.content] };\n }\n\n return {\n messages: [...pinned, ...kept],\n start,\n omittedTurns: omitted.turns,\n omittedMessages: omitted.messages,\n };\n}\n\nfunction positive(value: number | undefined): number | undefined {\n return typeof value === \"number\" && value > 0 ? value : undefined;\n}\n\nfunction byteBudget(options: ContextWindowOptions): number {\n const bytes = positive(options.maxBytes) ?? Infinity;\n const tokens = positive(options.maxTokens);\n return Math.min(bytes, tokens === undefined ? Infinity : tokens * CHARS_PER_TOKEN);\n}\n\n/**\n * What a search has to have loaded for a call to make sense: the call's\n * namespace, or, for a deferred tool outside any namespace, its name.\n */\nfunction covers(search: ToolSearchRecord, call: ToolCallPart): boolean {\n const namespaces = Array.isArray(search?.namespaces) ? search.namespaces : [];\n const loaded = Array.isArray(search?.loaded) ? search.loaded : [];\n return call.namespace ? namespaces.includes(call.namespace) : loaded.includes(String(call.name));\n}\n\nfunction searchesOf(part: ToolCallPart): ToolSearchRecord[] {\n return Array.isArray(part.toolSearches) ? part.toolSearches : [];\n}\n\n/**\n * `kept`, with the searches from `dropped` that a kept call still depends on\n * put back on the first call that needs one.\n *\n * A call needs a dropped search when no search before it in `kept` (its own\n * included) covers it and one in `dropped` does. All such searches go on the\n * first call that needs any, in their original order, so every later call is\n * covered by them too. Deterministic in the cut, which keeps the prefix the\n * same from turn to turn while the cut stays put.\n */\nfunction carrySearches(dropped: AgentMessage[], kept: AgentMessage[]): AgentMessage[] {\n const droppedSearches: ToolSearchRecord[] = [];\n for (const message of dropped) {\n for (const part of message.content ?? []) {\n if (part.type === \"tool-call\") droppedSearches.push(...searchesOf(part));\n }\n }\n if (droppedSearches.length === 0) return kept;\n\n const seen: ToolSearchRecord[] = [];\n const needed = new Set<ToolSearchRecord>();\n let host: { message: number; part: number } | undefined;\n kept.forEach((message, m) => {\n (message.content ?? []).forEach((part, p) => {\n if (part.type !== \"tool-call\" || part.partial) return;\n seen.push(...searchesOf(part));\n if (seen.some((search) => covers(search, part))) return;\n const missing = droppedSearches.filter((search) => covers(search, part));\n if (missing.length === 0) return;\n for (const search of missing) needed.add(search);\n host ??= { message: m, part: p };\n });\n });\n if (!host) return kept;\n\n const carried = droppedSearches.filter((search) => needed.has(search));\n const out = [...kept];\n const message = out[host.message]!;\n out[host.message] = {\n ...message,\n content: message.content.map((part, p) =>\n p === host!.part && part.type === \"tool-call\"\n ? { ...part, toolSearches: [...carried, ...searchesOf(part)] }\n : part,\n ),\n };\n return out;\n}\n",
13
- "/**\n * Compaction for the context window (#782).\n *\n * `contextWindow` (#473) bounds a long thread's request by leaving its older\n * turns out. With `compact` set, the turns left out are summarised instead,\n * and the request becomes `[system messages, summary, ...kept turns]`.\n *\n * - **Incremental.** The part left out of a long thread can itself be bigger\n * than a context, so a summary is never built from the whole of it at once.\n * The summary for a cut is the summary for an earlier cut of the same thread\n * plus the turns between the two, folded in chunks of at most `chunkTokens`.\n * - **Persistent.** Summaries live in a `SummaryStore`, per thread and keyed\n * by the cut (the id of the first kept message). `AgentController` uses its\n * own `AgentStore` when that implements the summary methods, which\n * `MemoryAgentStore` does; otherwise a process-wide memory store.\n * - **Two triggers.** The window's own limits (`maxTurns`, `maxTokens`,\n * `maxBytes`) and `triggerTokens`, a token budget for the turns sent: a\n * thread whose turns are few but long (big tool results) is compacted\n * before `maxTurns` would cut it. `triggerTokens` only moves the cut when a\n * summary can take the turns' place; without one the plain window is sent.\n * - **Computed once per cut.** The cut moves `step` turns at a time, so a\n * summary is made when the window moves and reused, from the store, by every\n * later turn until it moves again. The request's prefix stays the same from\n * turn to turn in between, so the provider's prompt cache keeps hitting.\n * - **In the background.** When a run on a thread ends, the summary the next\n * turn will need is started right away (`precompactWindow`), so the next\n * turn usually finds it stored. If it isn't ready, the next turn waits for\n * the same call, or makes it before its first model call.\n * - **Never twice at once.** In one process, every run and background start\n * on a thread share one summary job per cut. Across processes, a store may\n * implement `lockSummary`; a run that finds the cut locked waits for the\n * summary to appear, and sends the plain window if it doesn't in time.\n * - **Detached from the run.** A summary job is not cancelled by the run that\n * started it: stopping that run stops its wait, not the job, which finishes,\n * is saved, and reaches every run waiting on it.\n * - **Billed once.** Each summary call's usage is added to the usage of a run\n * waiting on the job (the one that started it, while it runs). A call no run\n * was waiting on (a background start, or a job whose run was stopped) is\n * billed to the next run in this process that uses the summary.\n * - **Never fatal.** A failed summary call sends the plain window with its\n * note, as `contextWindow` without `compact` would, and the run goes on.\n *\n * The summary is checked against what it summarised: each record carries a\n * fingerprint of the messages before its cut, so a thread whose earlier\n * messages changed (a regenerate, an edit, an amended tool result) gets a new\n * summary rather than a stale one.\n */\n\nimport type { AgentProvider } from \"./AgentProvider\";\nimport { turnStarts, windowMessages } from \"./contextWindow\";\nimport type { ContextWindowOptions } from \"./contextWindow\";\nimport { generate } from \"./generate\";\nimport { addUsage, emptyUsage } from \"./runtime\";\nimport { s } from \"./Schema\";\nimport type { AgentMessage, AgentContentPart, Usage } from \"./types\";\n\n/** `ContextCompactOptions.maxSummaryTokens`'s default. */\nexport const DEFAULT_MAX_SUMMARY_TOKENS = 1_000;\n/** `ContextCompactOptions.chunkTokens`'s default. */\nexport const DEFAULT_COMPACT_CHUNK_TOKENS = 24_000;\n/** `ContextCompactOptions.lockWaitMs`'s default. */\nexport const DEFAULT_COMPACT_LOCK_WAIT_MS = 20_000;\n/**\n * `ContextCompactOptions.triggerTokens`'s default, for a window with no\n * `maxTokens`/`maxBytes` of its own.\n */\nexport const DEFAULT_COMPACT_TRIGGER_TOKENS = 100_000;\n/**\n * How long one summary call may take. A job is detached from the runs\n * waiting on it, so nothing else would stop a provider that never answers.\n */\nconst SUMMARY_CALL_TIMEOUT_MS = 120_000;\n\n/** `ContextCompactOptions.instructions`'s default. */\nexport const DEFAULT_COMPACT_INSTRUCTIONS = [\n \"You keep a running summary of a conversation between a user and an AI assistant.\",\n \"The assistant will continue the conversation with only your summary and the latest turns, so the summary has to carry everything from the earlier turns it may still need.\",\n \"You are given the summary so far (possibly empty) and the turns that came after it. Answer the updated summary, which replaces the old one.\",\n \"Keep: the user's goals, preferences and constraints; decisions made and why; facts, names, ids, numbers, dates, file names and URLs that may matter later; what tools were used and their important results; open questions and unfinished work.\",\n \"Drop greetings, repetition and anything later turns superseded. Do not invent anything, and do not answer the user.\",\n \"Write terse prose or bullet points, in the language of the conversation.\",\n].join(\" \");\n\n/** The text the summary is sent under. */\nexport const COMPACT_SUMMARY_HEADER =\n \"[Summary of the earlier turns of this conversation, which are not shown:]\";\n\n/**\n * `contextWindow.compact`: summarise the turns the window leaves out instead\n * of dropping them. See `contextCompaction.ts`.\n */\nexport type ContextCompactOptions = {\n /** The model that writes the summaries. Default: the run's provider. */\n provider?: AgentProvider;\n /**\n * Compact once the turns sent would be over this many approximate tokens\n * (four characters each, as `maxTokens` counts them), even when `maxTurns`\n * would keep them all: older turns are summarised until the rest, with the\n * summary, fit. So a few long turns (big tool results) are compacted early.\n *\n * Unlike the window's `maxTokens`, it never drops a turn without a summary:\n * when no summary can be had, the plain window is sent as if it weren't set.\n *\n * Default `DEFAULT_COMPACT_TRIGGER_TOKENS` (100000) when the window has no\n * `maxTokens`/`maxBytes`; when it has one, that budget is the trigger and\n * this is unset. `false` turns it off.\n */\n triggerTokens?: number | false;\n /**\n * Start the summary the next turn will need as soon as a run on the thread\n * ends, rather than when that turn asks for it. Default `true`. The next\n * turn makes it inline (before its first model call) when it isn't ready.\n */\n background?: boolean;\n /** The summariser's system prompt. Default `DEFAULT_COMPACT_INSTRUCTIONS`. */\n instructions?: string;\n /**\n * How long a summary may be, in approximate tokens. Default 1000. The model\n * is asked for at most this, a longer answer is cut to it, and it is\n * reserved from the window's `maxTokens`/`maxBytes`, so the summary and the\n * kept turns together stay within the budget.\n */\n maxSummaryTokens?: number;\n /**\n * The most transcript one summary call is sent, in approximate tokens.\n * Default 24000. More turns than this to fold in (the first summary of a\n * long thread) take several calls, each building on the last.\n */\n chunkTokens?: number;\n /** Passed to the summary call. Default `\"low\"`; dropped by a model that\n * cannot reason. */\n reasoning?: \"minimal\" | \"low\" | \"medium\" | \"high\";\n /**\n * Where the summaries live. Default: the controller's `AgentStore` when it\n * implements `loadSummaries` and `saveSummary` (as `MemoryAgentStore` does),\n * else `defaultSummaryStore`, which lasts as long as the process.\n */\n store?: SummaryStore;\n /**\n * How long a run waits for a summary another process is writing (see\n * `SummaryStore.lockSummary`) before it sends the plain window instead.\n * Default 20000.\n */\n lockWaitMs?: number;\n};\n\n/** One summary of a thread's turns before a cut. */\nexport type ThreadSummary = {\n /** The id of the first message after the summarised part: the cut. */\n cutMessageId: string;\n /** The summary, without `COMPACT_SUMMARY_HEADER`. */\n text: string;\n /** How many turns and messages before the cut it covers. */\n turns: number;\n messages: number;\n /**\n * A hash of the messages it covers, as stored. A record whose fingerprint\n * no longer matches the thread is ignored.\n */\n fingerprint: string;\n createdAt: string;\n /** What the calls that wrote it cost. */\n usage?: Usage;\n};\n\n/**\n * Where `compact` keeps its summaries. `AgentStore` has the same optional\n * methods, so a store that holds threads can hold their summaries too, and\n * drop them with the thread.\n */\nexport interface SummaryStore {\n /**\n * The thread's summaries, in any order. Keeping a few per thread is enough:\n * the latest is what the next cut builds on, and an older one only helps\n * when the window moves back (a regenerate, a larger budget).\n */\n loadSummaries(threadId: string): Promise<ThreadSummary[]>;\n /** Upsert by `cutMessageId`. */\n saveSummary(threadId: string, summary: ThreadSummary): Promise<void>;\n /**\n * Optional, for a store shared by several processes: take the lock for one\n * cut of a thread for at most `ttlMs`, answering its release, or `null` when\n * another process holds it. (Redis: `SET key NX PX ttlMs`.) Without it, two\n * processes may both summarise the same cut once; one process never does.\n */\n lockSummary?(\n threadId: string,\n cutMessageId: string,\n ttlMs: number,\n ): Promise<(() => Promise<void>) | null>;\n}\n\n/** How many summaries `MemorySummaryStore` keeps per thread. */\nconst SUMMARIES_PER_THREAD = 8;\n\n/**\n * Summaries kept per thread in memory, most recent first. Lost on restart and\n * not shared between processes, like `MemoryAgentStore`. Threads are\n * forgotten after `ttlMs` without a read or a write.\n */\nexport class MemorySummaryStore implements SummaryStore {\n private threads = new Map<\n string,\n { summaries: ThreadSummary[]; touchedAt: number }\n >();\n private lastSweep = 0;\n\n constructor(readonly ttlMs = 24 * 60 * 60 * 1000) {}\n\n async loadSummaries(threadId: string): Promise<ThreadSummary[]> {\n this.sweep();\n const entry = this.threads.get(threadId);\n if (!entry) return [];\n entry.touchedAt = Date.now();\n return entry.summaries.slice();\n }\n\n async saveSummary(threadId: string, summary: ThreadSummary): Promise<void> {\n this.sweep();\n const entry = this.threads.get(threadId) ?? {\n summaries: [],\n touchedAt: Date.now(),\n };\n entry.summaries = keepSummary(entry.summaries, summary);\n entry.touchedAt = Date.now();\n this.threads.set(threadId, entry);\n }\n\n /** Forget a thread's summaries. */\n delete(threadId: string): void {\n this.threads.delete(threadId);\n }\n\n private sweep(now = Date.now()): void {\n if (now - this.lastSweep < 60_000) return;\n this.lastSweep = now;\n for (const [threadId, entry] of this.threads) {\n if (now - entry.touchedAt > this.ttlMs) this.threads.delete(threadId);\n }\n }\n}\n\n/**\n * `summaries` with `summary` put first, any older record for the same cut\n * replaced, and at most `SUMMARIES_PER_THREAD` kept. For stores that hold a\n * thread's summaries as a list.\n */\nexport function keepSummary(\n summaries: readonly ThreadSummary[],\n summary: ThreadSummary,\n) {\n return [\n summary,\n ...summaries.filter((held) => held.cutMessageId !== summary.cutMessageId),\n ].slice(0, SUMMARIES_PER_THREAD);\n}\n\n/** The process-wide summary store a run uses when nothing else is given. */\nexport const defaultSummaryStore = new MemorySummaryStore();\n\n/** Whether `store` holds summaries (an `AgentStore` may or may not). */\nexport function isSummaryStore(store: unknown): store is SummaryStore {\n const candidate = store as Partial<SummaryStore> | null | undefined;\n return (\n typeof candidate?.loadSummaries === \"function\" &&\n typeof candidate?.saveSummary === \"function\"\n );\n}\n\n// --- the request -----------------------------------------------------------\n\n/** What a summary job needs, whoever started it. Nothing here is a run's. */\nexport type CompactJobParams = {\n /** What the request would send before windowing (`historyForProvider`). */\n history: AgentMessage[];\n /** The same messages as stored, index for index, for the fingerprint. */\n stored: readonly AgentMessage[];\n window: ContextWindowOptions;\n compact: ContextCompactOptions;\n threadId: string;\n /** The run's provider, used when `compact.provider` is not set. */\n provider: AgentProvider;\n store: SummaryStore;\n};\n\nexport type CompactParams = CompactJobParams & {\n /** The run's signal: stops this run's wait, never the summary job. */\n signal: AbortSignal;\n /**\n * Told the usage of the summary calls this run is billed for, failed ones\n * included. See \"Billed once\" above.\n */\n onUsage: (usage: Usage) => void;\n /**\n * The run's own memo, by cut: the messages before the cut don't change\n * between a run's steps, so later steps skip the fingerprint and the store,\n * and a summary that failed is not tried again on every step.\n */\n memo?: Map<string, ThreadSummary | null>;\n};\n\n/** The two windows over one history: the one compaction cuts at, and the\n * plain one sent when there is no summary. */\nfunction plan(\n history: readonly AgentMessage[],\n window: ContextWindowOptions,\n compact: ContextCompactOptions,\n) {\n const maxSummaryTokens =\n positiveInt(compact.maxSummaryTokens) ?? DEFAULT_MAX_SUMMARY_TOKENS;\n // The summary is sent too, so it comes out of the budget. Never down to 0,\n // which `windowMessages` would read as \"no limit\".\n const reserve = (tokens: number) => Math.max(1, tokens - maxSummaryTokens);\n const plain: ContextWindowOptions = {\n ...window,\n ...(positiveInt(window.maxTokens)\n ? { maxTokens: reserve(window.maxTokens!) }\n : {}),\n ...(positiveInt(window.maxBytes)\n ? {\n maxBytes: Math.max(\n 1,\n window.maxBytes! - maxSummaryTokens * CHARS_PER_TOKEN,\n ),\n }\n : {}),\n };\n const trigger = triggerTokens(window, compact);\n const compacting: ContextWindowOptions = {\n ...plain,\n note: false,\n ...(trigger\n ? { maxTokens: Math.min(plain.maxTokens ?? Infinity, reserve(trigger)) }\n : {}),\n };\n return { plain, cut: windowMessages(history, compacting), maxSummaryTokens };\n}\n\n/** `ContextCompactOptions.triggerTokens` as it applies to `window`. */\nfunction triggerTokens(\n window: ContextWindowOptions,\n compact: ContextCompactOptions,\n): number | undefined {\n if (compact.triggerTokens === false) return undefined;\n const set = positiveInt(compact.triggerTokens || undefined);\n if (set) return set;\n if (positiveInt(window.maxTokens) || positiveInt(window.maxBytes))\n return undefined;\n return DEFAULT_COMPACT_TRIGGER_TOKENS;\n}\n\n/**\n * The messages a compacted window sends: the window with the summary of what\n * it left out in front, or the plain window (with its note) when there is\n * nothing to summarise or the summary could not be made.\n */\nexport async function compactWindow(\n params: CompactParams,\n): Promise<AgentMessage[]> {\n const { history, window, compact } = params;\n const { plain, cut, maxSummaryTokens } = plan(history, window, compact);\n if (cut.omittedTurns === 0) return cut.messages;\n\n const memoKey = `${history[cut.start]!.id}:${cut.start}`;\n let summary: ThreadSummary | null | undefined = params.memo?.get(memoKey);\n if (summary === undefined) {\n try {\n summary = await summaryFor(params, cut.start, maxSummaryTokens);\n } catch (error) {\n if (params.signal.aborted) throw error;\n summary = null;\n }\n // Not when the run was stopped: that is no verdict on the summary.\n if (!params.signal.aborted) params.memo?.set(memoKey, summary);\n }\n if (!summary) return windowMessages(history, plain).messages;\n\n const keptCount = history.length - cut.start;\n const pinned = cut.messages.slice(0, cut.messages.length - keptCount);\n const kept = cut.messages.slice(cut.messages.length - keptCount);\n const head = history[cut.start]!;\n return [\n ...pinned,\n {\n // Derived from the cut, so the same cut sends the same message: the\n // prompt cache keys on the bytes.\n id: `summary_${head.id}`,\n role: \"user\",\n content: [\n { type: \"text\", text: `${COMPACT_SUMMARY_HEADER}\\n${summary.text}` },\n ],\n createdAt: head.createdAt,\n },\n ...kept,\n ];\n}\n\n/** The id of the stand-in for the next turn's user message. */\nconst NEXT_TURN_ID = \"\\u0000next-turn\";\n\n/**\n * Starts, in the background, the summary the thread's next turn will need,\n * when it isn't stored yet: the cut is worked out with an empty user message\n * standing in for that turn. A next turn whose message moves the cut further\n * (a long one, against a token budget) makes its own summary, as without this.\n *\n * Never rejects and nobody has to wait on it; the promise is for tests and\n * shutdown, as `settleSummaries` is.\n */\nexport function precompactWindow(params: CompactJobParams): Promise<void> {\n const started = precompact(params).finally(() => starting.delete(started));\n starting.add(started);\n return started;\n}\n\n/** `precompactWindow`s still deciding whether to start a job. */\nconst starting = new Set<Promise<void>>();\n\nasync function precompact(params: CompactJobParams): Promise<void> {\n try {\n const next: AgentMessage = {\n id: NEXT_TURN_ID,\n role: \"user\",\n content: [{ type: \"text\", text: \"\" }],\n createdAt: new Date().toISOString(),\n };\n const history = [...params.history, next];\n const stored = [...params.stored, next];\n const { cut, maxSummaryTokens } = plan(\n history,\n params.window,\n params.compact,\n );\n if (cut.omittedTurns === 0 || history[cut.start]!.id === NEXT_TURN_ID)\n return;\n const target = cutTarget({ ...params, history, stored }, cut.start);\n if ((await load(params.store, params.threadId)).some(target.matches))\n return;\n await job(\n target,\n { ...params, history, stored },\n cut.start,\n maxSummaryTokens,\n ).promise;\n } catch {\n // Best effort: the next turn makes it inline.\n }\n}\n\n/** Resolves once every summary job in flight in this process has ended. */\nexport async function settleSummaries(): Promise<void> {\n while (jobs.size > 0 || starting.size > 0) {\n await Promise.allSettled([\n ...starting,\n ...[...jobs.values()].map((running) => running.promise),\n ]);\n }\n}\n\n/** One summary being made, shared by every run that needs it. */\ntype Job = {\n promise: Promise<ThreadSummary | null>;\n /** The runs waiting on it, in the order they came. The first is billed. */\n payers: Array<(usage: Usage) => void>;\n /** Usage of calls made while no run was waiting. */\n owed: Usage | undefined;\n};\n\n/** Summary jobs in flight in this process, by thread, cut and fingerprint. */\nconst jobs = new Map<string, Job>();\n\n/**\n * Usage of finished jobs no run was billed for, by job key, for the next run\n * that uses the summary. Bounded: a thread nobody comes back to leaves its\n * entry until it is pushed out.\n */\nconst owed = new Map<string, Usage>();\nconst MAX_OWED = 1_000;\n\nfunction owe(key: string, usage: Usage): void {\n owed.set(key, addUsage(owed.get(key) ?? emptyUsage(), usage));\n while (owed.size > MAX_OWED) owed.delete(owed.keys().next().value!);\n}\n\nfunction claimOwed(key: string, onUsage: (usage: Usage) => void): void {\n const usage = owed.get(key);\n if (!usage) return;\n owed.delete(key);\n onUsage(usage);\n}\n\n/** What identifies the summary for the cut at `start`. */\nfunction cutTarget(params: CompactJobParams, start: number) {\n const cutMessageId = params.history[start]!.id;\n const fingerprints = prefixFingerprints(params.stored, start);\n const fingerprint = fingerprints[start]!;\n return {\n key: `${params.threadId}\\u0000${cutMessageId}\\u0000${fingerprint}`,\n fingerprints,\n matches: (summary: ThreadSummary | undefined) =>\n summary?.cutMessageId === cutMessageId &&\n summary.fingerprint === fingerprint,\n };\n}\n\nasync function summaryFor(\n params: CompactParams,\n start: number,\n maxSummaryTokens: number,\n): Promise<ThreadSummary | null> {\n const target = cutTarget(params, start);\n const found = (await load(params.store, params.threadId)).find(\n target.matches,\n );\n if (found) {\n claimOwed(target.key, params.onUsage);\n return found;\n }\n\n const running = job(target, params, start, maxSummaryTokens);\n // Billed from here on, and for whatever ran while nobody waited.\n if (running.owed) {\n params.onUsage(running.owed);\n running.owed = undefined;\n }\n running.payers.push(params.onUsage);\n try {\n return await untilAborted(running.promise, params.signal);\n } finally {\n running.payers.splice(running.payers.indexOf(params.onUsage), 1);\n claimOwed(target.key, params.onUsage);\n }\n}\n\n/** The job for `target`, started if none is running. */\nfunction job(\n target: ReturnType<typeof cutTarget>,\n params: CompactJobParams,\n start: number,\n maxSummaryTokens: number,\n): Job {\n const running = jobs.get(target.key);\n if (running) return running;\n\n const created: Job = { promise: undefined!, payers: [], owed: undefined };\n const bill = (usage: Usage) => {\n const payer = created.payers[0];\n if (payer) payer(usage);\n else created.owed = addUsage(created.owed ?? emptyUsage(), usage);\n };\n created.promise = (async () => {\n const { store, threadId } = params;\n const lockWaitMs =\n positiveInt(params.compact.lockWaitMs) ?? DEFAULT_COMPACT_LOCK_WAIT_MS;\n let release: (() => Promise<void>) | null = null;\n if (store.lockSummary) {\n try {\n release = await store.lockSummary(\n threadId,\n params.history[start]!.id,\n lockWaitMs + 60_000,\n );\n } catch {\n release = null;\n }\n if (!release) return waitFor(params, target.matches, lockWaitMs);\n }\n try {\n // Again under the lock: whoever held it may have just written it.\n const summaries = await load(store, threadId);\n const again = summaries.find(target.matches);\n if (again) return again;\n return await build(\n params,\n summaries,\n target.fingerprints,\n start,\n maxSummaryTokens,\n bill,\n );\n } finally {\n if (release) await release().catch(() => {});\n }\n })()\n .catch(() => null)\n .finally(() => {\n jobs.delete(target.key);\n if (created.owed) owe(target.key, created.owed);\n created.owed = undefined;\n });\n jobs.set(target.key, created);\n return created;\n}\n\n/** `promise`, or a rejection as soon as `signal` fires. The promise goes on. */\nfunction untilAborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) return Promise.reject(signal.reason);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n },\n );\n });\n}\n\nasync function load(\n store: SummaryStore,\n threadId: string,\n): Promise<ThreadSummary[]> {\n try {\n const summaries = await store.loadSummaries(threadId);\n return Array.isArray(summaries) ? summaries.filter(isRecord) : [];\n } catch {\n return [];\n }\n}\n\nfunction isRecord(value: unknown): value is ThreadSummary {\n const record = value as ThreadSummary | null;\n return (\n !!record &&\n typeof record.cutMessageId === \"string\" &&\n typeof record.text === \"string\" &&\n typeof record.fingerprint === \"string\"\n );\n}\n\n/** Another process holds the cut's lock: wait for its summary to land. */\nasync function waitFor(\n params: CompactJobParams,\n matches: (summary: ThreadSummary | undefined) => boolean,\n waitMs: number,\n): Promise<ThreadSummary | null> {\n const until = Date.now() + waitMs;\n while (Date.now() < until) {\n await new Promise((resolve) => setTimeout(resolve, 250));\n const found = (await load(params.store, params.threadId)).find(matches);\n if (found) return found;\n }\n return null;\n}\n\n/**\n * Folds the turns before `start` into a summary, from the latest still-valid\n * summary at an earlier cut (or from nothing), and saves it.\n */\nasync function build(\n params: CompactJobParams,\n summaries: ThreadSummary[],\n fingerprints: string[],\n start: number,\n maxSummaryTokens: number,\n bill: (usage: Usage) => void,\n): Promise<ThreadSummary | null> {\n const { history, compact } = params;\n const starts = turnStarts(history);\n const startTurn = starts.indexOf(start);\n\n // The base: the latest summary whose cut is a turn start before this one\n // and whose fingerprint still matches the thread up to it.\n const indexOf = new Map(starts.map((index) => [history[index]!.id, index]));\n let base: ThreadSummary | undefined;\n let from = 0;\n for (const summary of summaries) {\n const at = indexOf.get(summary.cutMessageId);\n if (at === undefined || at >= start || at <= from) continue;\n if (summary.fingerprint !== fingerprints[at]) continue;\n base = summary;\n from = at;\n }\n\n const chunkChars =\n (positiveInt(compact.chunkTokens) ?? DEFAULT_COMPACT_CHUNK_TOKENS) *\n CHARS_PER_TOKEN;\n const chunks = chunkTurns(history, starts, from, start, chunkChars);\n const maxChars = maxSummaryTokens * CHARS_PER_TOKEN;\n const instructions = `${compact.instructions ?? DEFAULT_COMPACT_INSTRUCTIONS} Keep the summary under about ${Math.round(maxSummaryTokens * 0.75)} words.`;\n\n let text = base?.text ?? \"\";\n let usage = emptyUsage();\n for (const chunk of chunks) {\n const result = await generate({\n provider: compact.provider ?? params.provider,\n instructions,\n prompt: `Summary so far:\\n${text || \"(none yet: these are the first turns of the conversation)\"}\\n\\nThe turns that came after it:\\n${chunk}`,\n output: s.object({ summary: s.string() }),\n reasoning: compact.reasoning ?? \"low\",\n signal: AbortSignal.timeout(SUMMARY_CALL_TIMEOUT_MS),\n });\n usage = addUsage(usage, result.usage);\n bill(result.usage);\n if (!result.ok) return null;\n text = truncate(result.output.summary.trim(), maxChars);\n }\n if (!text) return null;\n\n const summary: ThreadSummary = {\n cutMessageId: history[start]!.id,\n text,\n turns: startTurn < 0 ? 0 : startTurn,\n messages: start,\n fingerprint: fingerprints[start]!,\n createdAt: new Date().toISOString(),\n usage,\n };\n try {\n await params.store.saveSummary(params.threadId, summary);\n } catch {\n // Sent this time anyway; the next turn writes it again.\n }\n return summary;\n}\n\n// --- the transcript ----------------------------------------------------------\n\nconst CHARS_PER_TOKEN = 4;\n\n/**\n * The turns from `from` to `to` (message indexes, both turn starts) rendered\n * as text, in chunks of whole turns of at most `chunkChars` each. A turn on\n * its own over the limit is its own chunk, its parts cut short.\n */\nexport function chunkTurns(\n history: readonly AgentMessage[],\n starts: readonly number[],\n from: number,\n to: number,\n chunkChars: number,\n): string[] {\n const injected = new Set<string>();\n const startSet = new Set(starts);\n for (let i = 0; i < history.length; i++) {\n if (history[i]!.role === \"user\" && !startSet.has(i) && i !== 0)\n injected.add(history[i]!.id);\n }\n const partLimit = Math.max(500, Math.min(20_000, Math.floor(chunkChars / 2)));\n\n const chunks: string[] = [];\n let current = \"\";\n const bounds = starts.filter((index) => index >= from && index < to);\n bounds.forEach((turnStart, t) => {\n const turnEnd = bounds[t + 1] ?? to;\n const lines: string[] = [];\n for (let i = turnStart; i < turnEnd; i++) {\n const line = renderMessage(\n history[i]!,\n injected.has(history[i]!.id),\n partLimit,\n );\n if (line) lines.push(line);\n }\n const turn = lines.join(\"\\n\");\n if (!turn) return;\n if (current && current.length + turn.length + 2 > chunkChars) {\n chunks.push(current);\n current = \"\";\n }\n current = current ? `${current}\\n\\n${turn}` : turn;\n });\n if (current) chunks.push(current);\n return chunks;\n}\n\nfunction renderMessage(\n message: AgentMessage,\n injected: boolean,\n limit: number,\n): string {\n // System messages before the cut are still sent, at the front.\n if (message.role === \"system\") return \"\";\n const who = injected\n ? \"Tool (file shown)\"\n : message.role === \"user\"\n ? \"User\"\n : \"Assistant\";\n const parts = (message.content ?? [])\n .map((part) => renderPart(part, limit))\n .filter(Boolean);\n return parts.length > 0 ? `${who}: ${parts.join(\"\\n\")}` : \"\";\n}\n\nfunction renderPart(part: AgentContentPart, limit: number): string {\n switch (part.type) {\n case \"text\":\n return truncate(part.text ?? \"\", limit);\n case \"file\":\n return `[file: ${part.name ?? part.mimeType ?? part.fileId ?? \"attachment\"}]`;\n case \"tool-call\": {\n const name = part.namespace\n ? `${part.namespace}.${String(part.name)}`\n : String(part.name);\n return `[called ${name}(${truncate(json(part.input), Math.min(limit, 1_000))})]`;\n }\n case \"tool-result\": {\n const body =\n part.status === \"ok\"\n ? json(part.output)\n : part.status === \"error\"\n ? `error: ${part.error?.message ?? \"\"}`\n : part.status === \"running\"\n ? `a background job (${part.job?.id ?? \"unknown\"}) that was still running`\n : `${part.status}${part.reason ? `: ${part.reason}` : \"\"}`;\n return `[${String(part.name)} returned: ${truncate(body, Math.min(limit, 2_000))}]`;\n }\n case \"output\":\n return `[structured answer: ${truncate(json(part.value), Math.min(limit, 2_000))}]`;\n default:\n return \"\";\n }\n}\n\nfunction json(value: unknown): string {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value) ?? \"\";\n } catch {\n return String(value);\n }\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length <= max ? text : `${text.slice(0, max)}…[cut]`;\n}\n\nfunction positiveInt(value: number | undefined): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0\n ? Math.floor(value)\n : undefined;\n}\n\n// --- fingerprints --------------------------------------------------------------\n\n/**\n * `out[i]` is a fingerprint of `messages[0..i)`, for every `i` up to `end`.\n * A chain over each message's JSON, so one pass gives every prefix.\n */\nexport function prefixFingerprints(\n messages: readonly AgentMessage[],\n end: number,\n): string[] {\n const out = [\"0\"];\n let chain = \"\";\n for (let i = 0; i < end; i++) {\n let body: string;\n try {\n body = JSON.stringify(messages[i]) ?? \"\";\n } catch {\n body = String(messages[i]?.id);\n }\n chain = hash(`${chain}|${hash(body)}`);\n out.push(chain);\n }\n return out;\n}\n\n/** cyrb53: a fast 53-bit string hash. Not cryptographic, and needn't be: it\n * tells a changed history from an unchanged one, on the server's own data. */\nfunction hash(text: string): string {\n let h1 = 0xdeadbeef;\n let h2 = 0x41c6ce57;\n for (let i = 0; i < text.length; i++) {\n const ch = text.charCodeAt(i);\n h1 = Math.imul(h1 ^ ch, 2654435761);\n h2 = Math.imul(h2 ^ ch, 1597334677);\n }\n h1 =\n Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^\n Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n h2 =\n Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^\n Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);\n}\n",
14
- "import { Log } from \"../facades/Log\";\nimport { RequestContext } from \"../http/requestContext\";\nimport type { AgentProvider, ProviderToolNamespace, ProviderToolSpec } from \"./AgentProvider\";\nimport type { GeneratedImage, GenerateImageParams, ImageInput, ImageModel } from \"./ImageModel\";\nimport {\n generateWithin,\n type GenerateParams,\n type GenerateResult,\n type GenerateSuccess,\n} from \"./generate\";\nimport {\n addUsage,\n appendReasoning,\n appendText,\n bestEffortParse,\n emptyUsage,\n outputFormat,\n parseOutput,\n raceAbort,\n resolveRope,\n RunAborted,\n} from \"./runtime\";\nimport { supportsStrict } from \"./Schema\";\nimport { applyRedaction, rememberUnredacted, ToolError } from \"./redact\";\nimport type { ErrorRedactor } from \"./redact\";\nimport type { Infer, JSONSchema, Schema } from \"./Schema\";\nimport { isJobHandle, type JobHandle, type RunJobs, type ToolJobs, toolJobs } from \"./jobs/AgentJob\";\nimport type { AgentJobsOptions } from \"./jobs/contextBlock\";\nimport {\n executionReceiptId,\n spendNestedRun,\n spendPendingCall,\n readSignature,\n signNestedRun,\n signPendingCall,\n verifyNestedRun,\n verifyPendingCall,\n} from \"./signing\";\nimport type {\n Attachment,\n PutAttachmentParams,\n ScopedAttachments,\n ToolAttachmentPut,\n ToolAttachmentRecord,\n ToolAttachments,\n} from \"./store/Attachments\";\nimport { ATTACHMENT_ID_PREFIX, InvalidAttachmentScopeError } from \"./store/Attachments\";\nimport { httpErrorDetail } from \"./providers/errors\";\nimport { defaultNonceStore, type NonceStore } from \"./store/Nonces\";\nimport type { ReceiptClaim, ReceiptStore } from \"./store/Receipts\";\nimport { sseKeepalive } from \"./store/sse\";\nimport {\n injectedMessageIds,\n windowMessages,\n type ContextWindowOptions,\n} from \"./contextWindow\";\nimport {\n compactWindow,\n defaultSummaryStore,\n precompactWindow,\n type CompactJobParams,\n type SummaryStore,\n type ThreadSummary,\n} from \"./contextCompaction\";\nimport type {\n AgentError,\n AgentMessage,\n AgentStreamEvent,\n AgentStreamFrame,\n ClientToolResult,\n ClientTurn,\n FilePart,\n FinishReason,\n NestedRun,\n PendingToolCall,\n ToolCallPart,\n ToolSearchRecord,\n ToolResultPart,\n ToolShapes,\n Usage,\n} from \"./types\";\n\n// --- tools ---------------------------------------------------------------\n\n/**\n * What the app hands a run for its tools to use: who it is for, the ids it is\n * about, and functions the tools call back into — a notifier, a scoped\n * repository, a progress sink.\n *\n * Empty here, and filled in by the app, once, with declaration merging:\n *\n * ```ts\n * declare module \"gemi/ai\" {\n * interface AgentContext {\n * userId: string;\n * notify?: (message: string) => Promise<void>;\n * }\n * }\n * ```\n *\n * WHY IT REPLACED `req`. A run used to be handed the HTTP request that started\n * it, and tools read the user off it. That tied every run to a request, and a\n * run started anywhere else — a queued job, a cron, a script — had nothing to\n * pass: `new HttpRequest()` outside a request throws before a model is called.\n * A run needs to know who it is acting for, not how the ask arrived, so the\n * caller now says that directly. `AgentController` builds it from its request\n * in `context()`; a job builds it from its payload.\n *\n * ONE SHAPE FOR THE APP, NOT ONE PER AGENT. Tools are module-scope singletons\n * that any agent may mount, so there is no agent whose type a tool could be\n * checked against. A field only some runs have is optional, and the tool that\n * needs it checks.\n *\n * TRUSTED. Unlike `ctx.body`, nothing here came from the client unless the\n * caller put it there: it is what the server decided the run is for.\n */\n// oxlint-disable-next-line no-empty-interface\nexport interface AgentContext {}\n\n/**\n * Required from a caller when the app's `AgentContext` has a required field,\n * optional when it has none — so an app that never declares one is not made to\n * pass `{}`, and an app that does cannot start a run that forgets it.\n */\ntype ContextParam = {} extends AgentContext\n ? { context?: AgentContext }\n : { context: AgentContext };\n\n/**\n * Everything a tool needs from the run it is part of.\n *\n * Tools are created once at module scope and shared by every run, so they\n * cannot close over a user or an abort signal — and anything mutable stored on\n * the tool itself would leak across runs. That is why the run's state arrives\n * as an argument instead: the tool stays a singleton and the context is per\n * call.\n */\nexport interface ToolContext {\n /**\n * What the caller of `Agent.stream` handed the run. See `AgentContext`.\n *\n * The same object for every tool of the run and every sub-run started with\n * `ctx.runAgent` — a sub-agent acts for the same caller, so it is given the\n * same one. `{}` for a run started without one.\n */\n context: AgentContext;\n /**\n * The app's own fields from the turn's request body — what `useChat`'s\n * `body` option sent, minus the keys the turn envelope owns.\n *\n * Carried on the run because `AgentController` has already consumed the\n * body, and a run outlives the request anyway, so by the time a tool\n * executes there is nothing left to read. The values are copied onto the run\n * when it starts.\n *\n * `{}` for a run started with none. Untyped on purpose — a tool is a\n * module-scope singleton that any controller may mount, so there is no one\n * `Body` for it to be. The controller that declares one gets it typed in\n * `instructions()`; a tool validates, the way it would any other input it\n * did not define.\n *\n * CLIENT-CONTROLLED. Same trust as a request body: fine to read, not a\n * finding about who the user is. An id from here says which record the\n * client wants, never that it may have it.\n */\n body: Record<string, unknown>;\n runId: string;\n threadId?: string;\n toolCallId: string;\n /**\n * Aborted when the user calls `stop()`, when the run reaches its\n * `maxRunDurationMs`, and when this call reaches the tool's own `timeoutMs`\n * (with a `TimeoutError` `DOMException` as its `reason`, the same as\n * `AbortSignal.timeout`). Not when the connection drops — a run outlives the\n * request that started it so a refresh can reattach, which means a\n * disconnect is no longer a signal to stop working.\n *\n * Pass it to whatever the tool waits on (`fetch(url, { signal })`). A tool\n * that ignores it does not hold the run open, since the run stops waiting\n * for it either way, but whatever it started keeps running in the\n * background.\n */\n signal: AbortSignal;\n /** Which step of the tool loop this is, starting at 1. */\n step: number;\n /**\n * How deep this tool is inside nested runs: 0 at the top, 1 inside a tool of\n * an agent started by `runAgent`, and so on. Compared against `maxDepth` on\n * `Agent.create` so a cycle — agent A with a tool that runs agent A — fails\n * with a sentence to read instead of exhausting the stack.\n */\n readonly depth: number;\n /**\n * True when this tool is being re-entered after a sub-agent it started asked\n * the user something and the user answered.\n *\n * READ THE `runAgent` NOTE BEFORE USING IT. This is the flag that lets a tool\n * tell a first attempt from a replay, and it exists because there is nothing\n * to tell it otherwise: the tool body ran once already.\n */\n readonly resumed: boolean;\n /**\n * Files, both directions.\n *\n * WHAT THIS FIXES. Before it, files travelled one way: a user's upload became\n * a provider file id the model could look at, and a tool that *produced*\n * something — an edited image, a rendered chart — had a string to return and\n * nowhere to put the bytes. `put(blob)` parks them and answers a record whose\n * `id` is the handle everything else uses; `put(blob, { showModel: true })`\n * also sends them to the provider and puts them in front of the model as an\n * input-role message once this tool call settles, which is what makes\n * generate → look → fix a loop rather than a one-way report.\n *\n * SCOPED, AND THAT IS THE WHOLE SECURITY STORY. The object is built from the\n * `ScopedAttachments` the controller resolved for *this request* (see\n * `AgentController.attachmentScope`), and none of its methods takes a scope,\n * so there is nothing for a tool to pass the model's arguments into. An id\n * that came from another user resolves to `AttachmentNotFoundError`, with the\n * same wording an unknown id gets.\n *\n * PER TOOL CALL, LIKE `runAgent`, AND FOR THE SAME REASON. `put` is memoized\n * by call index within the tool call, so a tool that escalates and is\n * re-entered does not store, upload or inject a second time. Read the note on\n * `ToolAttachments.put` before writing a body whose `put` calls sit in a\n * branch.\n *\n * ALWAYS PRESENT, NEVER NULL. A request with no attachment scope — an\n * unauthenticated, thread-less chat — gets an object whose every method\n * throws with a sentence naming `attachmentScope()`. A nullable `ctx`\n * member would be a guard every tool has to remember and most would not,\n * and the failure of forgetting is a `TypeError` in a tool body rather than\n * an explanation.\n */\n attachments: ToolAttachments;\n /**\n * What the user sent with the turn this tool call answers. See `ToolTurn`.\n */\n readonly turn: ToolTurn;\n /**\n * Runs another agent from inside this tool, wired into the parent run.\n *\n * A tool can already drive a sub-agent by hand — make one, iterate it, yield\n * its events as progress. What this does that hand-rolling cannot is join the\n * two runs: the sub-run inherits `ctx.signal` so the parent's `stop()` reaches\n * it; every sub-run event is re-emitted on the parent stream as\n * `nested-event`, numbered in the parent's `seq`, so `/attach` replay stays\n * correct through the nesting; the sub-run's usage rolls into the parent's;\n * its transcript is recorded on the parent's `ToolCallPart.nested`; and the\n * depth and agent-name chain travel with it, so a cycle fails fast.\n *\n * ESCALATION. If the sub-run ends `awaiting-input` — it has an approval tool,\n * or it asked a question — `onPending: \"escalate\"` (the default) throws a\n * `PendingEscalation` carrying the inner pending calls, which the parent run\n * collects exactly like pending calls of its own: the parent ends\n * `awaiting-input` with the sub-agent's questions in its list, and the client\n * answers them with the same `approve()` / `answer()` it uses for any other.\n * `onPending: \"deny\"` refuses them instead and lets the sub-run finish.\n *\n * THE COST, WHICH IS REAL AND WHICH YOU MUST DESIGN AROUND. A JS async\n * generator cannot be suspended across a turn boundary: `awaiting-input` is\n * terminal for the stream, the next turn re-enters the loop at the top and\n * rebuilds its state from the message history, and a paused generator is not\n * in that history and cannot be put there. So an escalating tool is\n * RE-ENTERED FROM THE TOP on the next turn, with `ctx.resumed === true`, and\n * `runAgent` is memoized by call index within the tool call: the Nth\n * `runAgent` of a tool call that already completed on an earlier turn returns\n * its persisted result immediately, calling no provider and running no\n * sub-tool, and only the sub-run that escalated actually continues.\n *\n * The index is the only key there is, so a body whose `runAgent` calls sit in\n * a branch or a loop can produce a different sequence on the replay and make\n * index N mean two different things. That is checked, not trusted: a mismatch\n * fails the tool call with a sentence naming both sub-runs, because pairing a\n * user's answer with a sub-run they never saw would be invisible.\n *\n * Which means: CODE BEFORE AN ESCALATING `runAgent` RUNS AGAIN ON RESUME.\n * Side effects there are repeated. Put your side effects after the\n * `runAgent`, or make them idempotent, or branch on `ctx.resumed`. This is\n * inherent to replay and it is the same bargain the outer tool loop already\n * makes; it is written here in plain words rather than solved with a\n * checkpoint API, because that is a much larger feature than this one.\n */\n runAgent<A extends AnyAgent>(agent: A, params?: RunAgentParams): Promise<NestedRunResult>;\n\n /**\n * One model call with an output schema, from inside this tool: `generate`,\n * bound to the turn. For a typed answer that needs no tools — where a\n * sub-agent would bring a tool loop nobody wants and stream a transcript to\n * the browser for a value it never renders.\n *\n * const result = await ctx.generate({ provider, instructions, prompt, output });\n * if (!result.ok) return { error: result.error.message };\n *\n * WHAT THE BINDING ADDS, and why it is not left to the caller: the call\n * aborts with the turn (`ctx.signal`), and its usage counts toward the turn,\n * the way a nested run's does. Passing the signal by hand is easy to forget\n * and the failure is invisible — a `stop()` that does not stop, and a bill\n * the run under-reports. A `signal` of the tool's own (a timeout) is\n * combined with the turn's, never swapped for it.\n *\n * SERVER ONLY. No frame reaches the client and nothing is written to the\n * transcript; the tool returns whatever it makes of the answer.\n *\n * A BAD ANSWER IS A RESULT, NOT A THROW — `{ ok: false, error, messages,\n * usage }`, so a retry continues `messages` — unless `throwOnError` is set.\n * It is logged unless `logErrors: false`, with the agent, run and tool call\n * it came from. See `generate`. A tool's own `timeoutMs` reaches it through\n * `ctx.signal` and comes back as `code: \"timeout\"`. The exception is the\n * turn itself being stopped, or reaching its deadline: then this throws, as\n * `runAgent` does, so the body does not carry on with half an answer while\n * the run around it is already closing — its result would be discarded\n * anyway.\n *\n * NOT MEMOIZED. A tool re-entered after an escalation calls the model again,\n * unlike `runAgent` and `generateImage`, which replay from what they recorded\n * on the tool call. This records nothing, by design.\n */\n generate<O extends Schema<any>>(\n params: GenerateParams<O> & { throwOnError: true },\n ): Promise<GenerateSuccess<Infer<O>>>;\n generate<O extends Schema<any>>(params: GenerateParams<O>): Promise<GenerateResult<Infer<O>>>;\n\n /**\n * Renders an image and parks it, in one step, wired into this tool call.\n *\n * THE SPELLING DIFFERS FROM `ImageModel.generate` ON PURPOSE, and the reason\n * is the same one behind `ctx.runAgent`: an escalating tool is re-entered\n * from the top on the next turn, so a render reached by a bare\n * `model.generate()` inside a tool body is paid for again on every replay —\n * two minutes and an invoice line, for an image whose id the model has\n * already read. This memoizes the render against the tool call, exactly as\n * `ctx.attachments.put` memoizes a store.\n *\n * IT ANSWERS AN `Attachment`, NOT BYTES, and that is forced rather than\n * chosen: the memo lives in the message history, so it cannot hold an image.\n * The bytes are in the app's Storage, which is where a generated image was\n * going anyway; `ctx.attachments.file(id)` hands them back, and copying them\n * under a key of the app's own is what makes the image outlive the run.\n *\n * `showModel: true` puts the result in front of the model as an input-role\n * message once this call settles, so an agent can look at what it made and\n * try again.\n */\n generateImage(model: ImageModel, params: ToolGenerateImageParams): Promise<GeneratedAttachment>;\n\n /**\n * Edits images and parks the result. Everything above applies.\n *\n * `images` takes attachment ids as well as bytes, and the ids are the point:\n * the image to change is usually the one the model just named (\"make that one\n * warmer\"), so it arrives with exactly the trust of a request body. Ids are\n * resolved through this call's `ctx.attachments`, which applies #489's scope\n * checks; there is no spelling here that reaches an id outside them.\n */\n editImage(model: ImageModel, params: ToolEditImageParams): Promise<GeneratedAttachment>;\n\n /**\n * Hands this call's work to a background job (#461).\n *\n * async execute({ images }, ctx) {\n * return ctx.jobs.start(RenderImagesJob, { images }, { summary: { count: images.length } });\n * }\n *\n * Return the handle and the call's result is `running`: the model is told\n * the job started, the turn goes on and ends, and when the job settles its\n * output becomes the call's result. The tool has to declare `async`, and\n * the run has to be a threaded turn through `AgentController`. Anywhere\n * else `start` and `track` throw a `JobsRequireThreadError`, which the\n * model reads as the tool's error. See `ToolJobs`.\n */\n jobs: ToolJobs;\n}\n\n/** What an image parked by a tool answers. See `ToolContext.generateImage`. */\nexport type GeneratedAttachment = {\n attachment: Attachment;\n /** The pixel dimensions the model produced, read off the response. */\n size: string;\n mimeType: string;\n usage: Usage;\n};\n\ntype ToolImageSettings = Omit<GenerateImageParams, \"prompt\" | \"signal\">;\n\nexport type ToolGenerateImageParams = ToolImageSettings & {\n prompt: string;\n /** The filename to store it under. Defaults to `<model name>.<extension>`. */\n name?: string;\n /** Also show the model its own output, once this tool call settles. */\n showModel?: boolean;\n};\n\nexport type ToolEditImageParams = ToolGenerateImageParams & {\n /** Attachment ids, or raw bytes. At least one. */\n images: [ImageInput | string, ...(ImageInput | string)[]];\n mask?: ImageInput | string;\n};\n\n/**\n * The files of the turn a tool call belongs to, as data the model cannot write.\n *\n * WHAT THIS FIXES. Every method on `ctx.attachments` takes an id, and before\n * this the only ids a tool could get were the ones the model put in its\n * arguments. So a tool meant to use \"the image the user attached\" had to trust\n * the model to name it, and a prompt-injected document could name a different\n * upload of the same user's — yesterday's contract instead of today's photo —\n * which the scope check passes, because it is the user's file. Reading the ids\n * from here instead leaves the model nothing to steer.\n *\n * WHICH TURN: THE USER MESSAGE BEFORE THIS CALL, NOT THE LATEST ONE. Found by\n * walking back from the assistant message that made the call, never by taking\n * the last user message in the history when the tool runs, and the difference\n * is re-entry. An escalating tool runs again from the top on a later turn (see\n * `runAgent`), and \"latest\" is recomputed each time: a turn that answers the\n * sub-agent can carry text or files of its own, and when the re-entered tool\n * asks again, that turn's user message is appended *after* the still-open call\n * — so on the next re-entry \"latest\" is the answer turn, and a tool that read\n * \"the image\" would pick a different file, or none, on its second attempt. The\n * replay checks do not reliably catch that: `putMismatch` compares the media\n * type and showModel, never the bytes, and a sub-run seeded with the file as\n * a message part fingerprints as `<file>` whichever file it was. The message\n * that preceded the call is in the history on every attempt and does not\n * move, so every attempt sees the same list.\n *\n * ONE TURN, NOT THE THREAD. The whole thread is what \"the image I sent earlier\"\n * needs, and it is the wider thing to bind to: a tool that picks \"the first\n * image\" out of forty turns picks whichever one the history happens to put\n * first, and the user who uploaded a new one sees the old one used. A tool that\n * wants earlier turns can take an id from the model and let the scope check it;\n * one that binds should bind to the turn the user is looking at. A turn with\n * text and no files gives an empty list, which is also the answer to \"the user\n * attached nothing this time\".\n *\n * NOT THE FILES A TOOL MADE. A file a tool showed with `put(…, { showModel:\n * true })` is injected as a user-role message and carries an `attachmentId`\n * too, and taking it would make it \"the user's upload\" to the next tool — so\n * the walk steps over every message a tool call's record names as injected,\n * the same test `historyForProvider` uses. A tool that wants what an earlier\n * tool produced has that tool's result to read the id from.\n *\n * IDS ONLY, AND NOT TRUSTED. The name and type beside them on the `FilePart`\n * are what the client said, so they are left off rather than offered as a\n * second, weaker copy of what `ctx.attachments.get(id)` answers from the\n * store. And the ids themselves are only as trustworthy as the history they\n * came from — which, for a stateless client, is whatever it posted. That is\n * fine for the reason everything else about attachments is fine: resolution\n * goes through `ctx.attachments`, whose scope was fixed by the request, so an\n * id from somebody else's upload answers `AttachmentNotFoundError` here\n * exactly as it would from the model's arguments. This list narrows which of\n * the caller's own files a tool reaches for; it grants nothing.\n *\n * Inside a sub-run the turn is the sub-run's own: the message its parent's\n * tool started it with, which has files only if that tool put them there. The\n * parent's upload is not inherited — the tool that called `runAgent` read its\n * own `ctx.turn` and decided what the sub-agent is given.\n */\nexport interface ToolTurn {\n /**\n * The `attachmentId`s on that user message's file parts, in order, without\n * duplicates, and only ids of gemi's own shape. Frozen, and computed once\n * before the body runs.\n */\n readonly attachments: readonly string[];\n}\n\n/** What `ctx.runAgent` is given. `messages` and `prompt` are alternatives. */\nexport interface RunAgentParams {\n /** Prior turns for the sub-agent. Starts empty when omitted. */\n messages?: AgentMessage[];\n /** Sugar for a single user turn — the common case, and the whole message\n * list when there is no sub-conversation to continue. */\n prompt?: string;\n /** Appended to the sub-agent's own `instructions`, for this run only. */\n instructions?: string;\n /** Shown on the nested transcript, e.g. \"researching pricing\". */\n label?: string;\n /**\n * What to do when the sub-run ends `awaiting-input`. `\"escalate\"` (the\n * default) throws `PendingEscalation` so the question reaches the user;\n * `\"deny\"` refuses every pending call and lets the sub-run finish, which is\n * what a tool wants when the sub-agent is meant to be autonomous.\n *\n * `\"deny\"` is refused *in place*, inside the sub-run's own loop, so the\n * sub-agent is told it cannot ask and takes another step rather than ending\n * parked — and it is inherited by everything below, so a grandchild asking to\n * escalate is overruled too. A promise that nothing from this subtree reaches\n * the user is only worth making if the whole subtree keeps it.\n */\n onPending?: \"escalate\" | \"deny\";\n /**\n * Override the sub-agent's own ceiling for this run.\n *\n * Not inherited from the parent. A sub-agent is a different job with a\n * different output size — a generator writing a document against a router\n * answering one word — and silently handing down the caller's ceiling would\n * either strangle the one or fail to bound the other.\n */\n maxOutputTokens?: number;\n temperature?: number;\n}\n\n/**\n * What a completed sub-run gives back.\n *\n * `nested` is the transcript as it is recorded on the parent's tool-call part,\n * so a tool that wants to summarize what its sub-agent did reads the same\n * object the UI renders rather than a second representation of it.\n */\nexport interface NestedRunResult<O = unknown> {\n runId: string;\n /** The sub-agent's name — carried so a caller that fans out over several\n * agents can tell the results apart without tracking the order. */\n agent: string;\n messages: AgentMessage[];\n finishReason: FinishReason;\n usage: Usage;\n /** Set when the sub-agent declares an `output` schema and the run finished. */\n output?: O;\n /** Why the sub-run failed: set exactly when `finishReason` is `\"error\"`. See\n * `AgentRunResult.error`. */\n error?: AgentRunFailure;\n /** The record written to the parent's `ToolCallPart.nested`. */\n nested: NestedRun;\n}\n\n/**\n * Thrown by `ctx.runAgent` when a sub-run ends `awaiting-input`.\n *\n * An exception rather than a return value because it must not be mistaken for\n * an answer: a tool that ignored an `{ escalated: true }` field would return a\n * result to the model as if the sub-agent had finished, and the model would act\n * on an answer nobody gave. `executeTool` lets this one propagate instead of\n * turning it into a `tool_error`, and the step loop collects `pending` exactly\n * like the pending calls it produced itself.\n *\n * `path` is the chain of tool-call ids down to the escalating call; each entry\n * of `pending` already carries its own full path, and this is the prefix they\n * share.\n */\nexport class PendingEscalation extends Error {\n readonly pending: PendingToolCall[];\n readonly path: string[];\n /** The sub-run that parked, so the parent can record its transcript before\n * ending the turn — an escalation is a pause, not a lost run. */\n readonly nested: NestedRun;\n\n constructor(params: { pending: PendingToolCall[]; path: string[]; nested: NestedRun }) {\n super(`A nested agent run is waiting on the user for ${params.pending.length} tool call(s).`);\n this.name = \"PendingEscalation\";\n this.pending = params.pending;\n this.path = params.path;\n this.nested = params.nested;\n }\n}\n\n/**\n * What a per-run `inputSchema` is resolved from: the run's caller and the\n * app's request body, the same `context` and `body` its tools are given.\n */\nexport interface ToolSchemaContext {\n context: AgentContext;\n /** CLIENT-CONTROLLED, exactly as `ToolContext.body` is. */\n body: Record<string, unknown>;\n runId: string;\n threadId?: string;\n /** Aborted with the run. */\n signal: AbortSignal;\n}\n\n/**\n * A tool's input schema: fixed, or resolved once per run.\n *\n * The function form is for a tool whose arguments depend on data — the fields\n * of the collection a page edits, the options a tenant configured. It is\n * called once when a run starts, before the model is shown the tools, and the\n * schema it returns is both what the model sees and what the run validates\n * the tool's arguments against, for every call in that run (a turn that\n * answers a pending call is a new run and resolves it again). Build the\n * schema with `s`, `s.fromJSONSchema` included; it has to be an object at the\n * root, like any tool's.\n *\n * A resolver that throws, or returns a non-object schema, fails the run with\n * `tool_error` before anything is sent to the provider.\n */\nexport type ToolInputSchema<Input> =\n | Schema<Input>\n | ((ctx: ToolSchemaContext) => Schema<Input> | Promise<Schema<Input>>);\n\n/**\n * A tool either resolves once, or yields progress and then returns.\n *\n * The generator form exists because a tool that takes twenty seconds is the\n * normal case, not the exotic one, and a chat UI that shows nothing for twenty\n * seconds looks broken. Yields become `tool-progress` events; the return value\n * is the result the model sees.\n */\nexport type ToolExecute<Input, Output, Progress = unknown> = (\n input: Input,\n ctx: ToolContext,\n) =>\n | Promise<Output | JobHandle<Output>>\n | AsyncGenerator<Progress, Output | JobHandle<Output>, void>;\n\ntype ToolDefinitionBase<Name extends string, Input, Output> = {\n name: Name;\n /** The model's only description of when to reach for this. */\n description: string;\n /** A schema, or a function resolving one per run. See `ToolInputSchema`. */\n inputSchema: ToolInputSchema<Input>;\n /**\n * Optional for a server tool, required for a client one — there it is what\n * the answer is validated against before the model sees it, and what types\n * the value the browser has to produce.\n */\n outputSchema?: Schema<Output>;\n /**\n * Withholds this tool's parameter schema from the request: the model is shown\n * only the name and description, and pulls the rest in with the provider's\n * `tool_search` when it decides it wants the tool (`defer_loading` on the\n * wire).\n *\n * It says nothing about who runs the tool or when — it is a statement about\n * the prompt, not about execution. What it buys is context: an agent with\n * forty tools spends most of its prompt on schemas for tools it will not\n * call, and deferred ones load at the end of the window, so adding one\n * mid-conversation does not invalidate the cache.\n *\n * Purely an optimization, and gemi treats it as one: a provider that cannot\n * do tool search is sent the schemas inline, and the agent behaves the same.\n * So it is safe to set on a model that does not support it, and worth setting\n * only for tools that are large, numerous, or rarely reached.\n */\n deferred?: boolean;\n /**\n * How long one call of this tool may take, in milliseconds. No limit by\n * default; the run's own `maxRunDurationMs` still bounds it.\n *\n * When it is reached, `ctx.signal` is aborted with a `TimeoutError`, the\n * model gets an `error` result for the call with code `\"timeout\"`, and the\n * run carries on: the model can retry, try something else, or answer\n * without it. The run stops waiting for the call at that moment, so a tool\n * that ignores `ctx.signal` cannot hold the run open past it, and anything\n * it yields or returns afterwards is dropped.\n *\n * Set it on any tool that waits on something it does not control (a third\n * party API, a `fetch` with no timeout of its own). Not used by client tools,\n * which the server never runs.\n */\n timeoutMs?: number;\n /**\n * Declares that the tool may hand its work to a background job with\n * `ctx.jobs.start` or `ctx.jobs.track` (#461). `deadlineMs` is how long such\n * a job may run before it is failed with code `\"timeout\"`; an hour when\n * absent. A tool without it cannot start a job.\n */\n async?: { deadlineMs?: number };\n};\n\n/**\n * Two ways a tool's result comes to exist, and neither changes the shape of the\n * conversation.\n *\n * `execute` — the server runs it.\n * `answeredBy: \"client\"` — the browser produces the result: a question for the\n * user, or something only the page can do. The stream ends `awaiting-input`\n * and the answer arrives as an ordinary turn.\n *\n * `requiresApproval` applies to the first: the server can run the tool, but\n * asks first. That, too, ends the stream `awaiting-input`, which is the whole\n * reason there is no second endpoint — an approval is a question whose answer\n * happens to be yes or no.\n */\nexport type ToolDefinition<Name extends string, Input, Output, Progress = never> =\n | (ToolDefinitionBase<Name, Input, Output> & {\n answeredBy?: \"server\";\n execute: ToolExecute<Input, Output, Progress>;\n requiresApproval?: boolean;\n })\n | (ToolDefinitionBase<Name, Input, Output> & {\n answeredBy: \"client\";\n outputSchema: Schema<Output>;\n execute?: never;\n /** Meaningless here: the client answering *is* the approval. */\n requiresApproval?: never;\n });\n\n/**\n * `Progress` is inferred, never written down.\n *\n * It comes from the yield type of an `execute` that is an async generator, and\n * from nothing else — a tool that returns a promise gets `never`, which is the\n * honest statement that it cannot yield and is what makes\n * `ToolShapesOf`'s `progress` member safe to emit unconditionally. It is\n * carried as a fourth parameter rather than derived on demand because it has to\n * survive the trip through `ToolNamespace`, `FlattenTools` and `ToolShapesOf`\n * into the browser, and only a type argument does that.\n *\n * Structurally it lives on `execute`, which is optional, and which is also why\n * `AnyAgentTool` must pass `any` here: `Progress` sits covariantly inside\n * `AsyncGenerator<Progress, …>`, so a bound of `never` would make every\n * yielding tool fail the `Extract` in `ToolShapesOf` and silently vanish from\n * the shapes.\n */\nexport class AgentTool<\n Name extends string = string,\n Input = unknown,\n Output = unknown,\n Progress = never,\n> {\n readonly name: Name;\n readonly description: string;\n readonly inputSchema: ToolInputSchema<Input>;\n readonly outputSchema?: Schema<Output>;\n readonly requiresApproval: boolean;\n readonly deferred: boolean;\n readonly answeredBy: \"server\" | \"client\";\n /** See `ToolDefinition.timeoutMs`. `undefined` is no limit of its own. */\n readonly timeoutMs?: number;\n /** See `ToolDefinition.async`. `undefined` for a tool that cannot start a job. */\n readonly async?: { deadlineMs?: number };\n /**\n * There is deliberately no `namespace` here. A tool is a module-scope\n * singleton, so a field naming its group would hold whichever agent\n * constructed its namespace last and report that to every other one — the\n * same global-effect-from-a-local-declaration that `ToolNamespace.deferred`\n * avoids. Where a tool sits is a property of the agent, and it lives on the\n * agent's `ResolvedTool`.\n */\n readonly execute?: ToolExecute<Input, Output, Progress>;\n\n private constructor(params: ToolDefinition<Name, Input, Output, Progress>) {\n this.name = params.name;\n this.description = params.description;\n this.inputSchema = params.inputSchema;\n this.outputSchema = params.outputSchema;\n this.requiresApproval = params.requiresApproval === true;\n this.deferred = params.deferred === true;\n this.answeredBy = params.answeredBy === \"client\" ? \"client\" : \"server\";\n this.execute = params.execute ?? undefined;\n this.timeoutMs = params.timeoutMs;\n this.async = params.async;\n }\n\n /**\n * `const` on the params is what preserves `name` as a literal, which is what\n * lets the browser discriminate a tool part by name.\n */\n static create<const Name extends string, Input, Output, Progress = never>(\n params: ToolDefinition<Name, Input, Output, Progress>,\n ): AgentTool<Name, Input, Output, Progress> {\n // Only the input: it is the one schema the provider is shown. The\n // `outputSchema` validates what `execute` or the browser hands back and is\n // never sent, so any shape is fine there.\n // A per-run schema is checked when a run resolves it.\n if (typeof params.inputSchema !== \"function\") {\n assertObjectRoot(params.inputSchema, `The tool \"${params.name}\"`, \"inputSchema\");\n }\n if (params.timeoutMs !== undefined) {\n assertDuration(params.timeoutMs, `The tool \"${params.name}\"`, \"timeoutMs\");\n }\n if (params.async?.deadlineMs !== undefined) {\n assertDuration(params.async.deadlineMs, `The tool \"${params.name}\"`, \"async.deadlineMs\");\n }\n if (params.async && params.answeredBy === \"client\") {\n throw new Error(\n `The tool \"${params.name}\" is answered by the client and cannot be \\`async\\`: background jobs are for tools the server runs.`,\n );\n }\n return new AgentTool(params);\n }\n\n /**\n * Sugar for the common client tool: the agent asks the user something and\n * waits. Equivalent to `answeredBy: \"client\"` with an input schema of one\n * prompt field.\n */\n static ask<const Name extends string, Output>(params: {\n name: Name;\n description: string;\n outputSchema: Schema<Output>;\n }): AgentTool<Name, { question: string }, Output> {\n return AgentTool.create({\n name: params.name,\n description: params.description,\n inputSchema: questionSchema,\n outputSchema: params.outputSchema,\n answeredBy: \"client\",\n });\n }\n}\n\n/**\n * The one schema this module owns, rather than one built with `s`.\n *\n * `Schema<T>` carries a phantom property keyed by a symbol `Schema.ts` does not\n * export, so nothing outside that file can produce one without a cast — and\n * reaching for `s` here would make the agent runtime depend on the schema\n * builder for a single hard-coded object. One field, no `describe`, no\n * optionality: the cast is cheaper than the coupling.\n */\nconst questionSchema = {\n toJSONSchema: () => ({\n type: \"object\",\n properties: { question: { type: \"string\", description: \"What to ask the user\" } },\n required: [\"question\"],\n additionalProperties: false as const,\n }),\n parse(value: unknown) {\n const result = questionSchema.safeParse(value);\n if (result.ok === false) throw new Error(result.errors.join(\", \"));\n return result.value;\n },\n safeParse(value: unknown) {\n if (\n typeof value !== \"object\" ||\n value === null ||\n typeof (value as any).question !== \"string\"\n ) {\n return { ok: false as const, errors: [\"question: expected a string\"] };\n }\n return { ok: true as const, value: { question: (value as any).question } };\n },\n} as unknown as Schema<{ question: string }>;\n\nexport type AnyAgentTool = AgentTool<string, any, any, any>;\n\n/**\n * A group of tools the model can search as a unit.\n *\n * The provider's tool search works over namespaces, and the guidance is fewer\n * than ten functions in each — the model looks at a namespace's description to\n * decide whether anything inside is worth loading, so the grouping is part of\n * the prompt, not bookkeeping. A namespace is also the only place a\n * *collection* of tools can be described; on a flat list that sentence has\n * nowhere to go.\n *\n * Tool names stay globally unique within an agent, so the browser still\n * discriminates on `name` alone and the namespace never leaks into the client's\n * types.\n */\nexport class ToolNamespace<\n Name extends string = string,\n T extends readonly AnyAgentTool[] = readonly AnyAgentTool[],\n> {\n readonly name: Name;\n readonly description: string;\n readonly tools: T;\n /**\n * Kept here rather than pushed onto each tool. A tool is a module-scope\n * singleton and may be listed bare as well as inside a group; writing the\n * group's `deferred` onto it would defer it everywhere, which is a global\n * effect from a local declaration.\n */\n readonly deferred: boolean;\n\n private constructor(params: { name: Name; description: string; tools: T; deferred?: boolean }) {\n this.name = params.name;\n this.description = params.description;\n this.tools = params.tools;\n this.deferred = params.deferred === true;\n }\n\n static create<const Name extends string, const T extends readonly AnyAgentTool[]>(params: {\n name: Name;\n /** What the model reads when deciding whether to search inside. */\n description: string;\n tools: T;\n /** Defers every tool in the group, so the whole namespace costs its own\n * description plus one line per tool until something is loaded. */\n deferred?: boolean;\n }): ToolNamespace<Name, T> {\n return new ToolNamespace(params);\n }\n}\n\n/** What an agent's `tools` may hold: tools, or namespaces of them. */\nexport type ToolEntry = AnyAgentTool | ToolNamespace<string, readonly AnyAgentTool[]>;\n\ntype FlattenTools<T extends readonly ToolEntry[]> = T[number] extends infer E\n ? E extends ToolNamespace<any, infer NT>\n ? NT[number]\n : E\n : never;\n\n/**\n * The tool tuple, erased to the payload types the client is allowed to see.\n *\n * `progress` is emitted for every tool, `never` included, rather than only for\n * the ones that can yield. A conditional that dropped the member would make\n * `T[K][\"progress\"]` in `types.ts` resolve differently per tool, and this\n * package compiles with `strict: false` — where `undefined extends T` is true\n * of everything and an optional member is indistinguishable from a required\n * one. Two inference bugs in this module already came from testing a shape\n * under those options and believing the answer (see `OptionalSchema` in\n * `Schema.ts`); an unconditional member has nothing to get wrong.\n */\nexport type ToolShapesOf<T extends readonly ToolEntry[]> =\n ShapesOf<NamedTools<Extract<FlattenTools<T>, AnyAgentTool>>> extends infer Named\n ? [keyof Named] extends [never]\n ? ShapesOf<Extract<FlattenTools<T>, AnyAgentTool>>\n : Named\n : never;\n\n/**\n * The tools whose name is a literal (#771). A tool named only `string` — an\n * untyped `toAgentTools`, or one built from a name read at runtime — would\n * give the shapes a string index signature, and `ToolCallPart`, which indexes\n * the shapes by `keyof`, would then answer the index's untyped member for\n * every tool, the literal ones included. So it is left out, and degrades only\n * itself: its parts are not in the client's union. An agent with no literal\n * name at all keeps the index, as before.\n */\ntype NamedTools<K> = K extends AnyAgentTool ? (string extends K[\"name\"] ? never : K) : never;\n\ntype ShapesOf<U extends AnyAgentTool> = {\n [K in U as K[\"name\"]]: K extends AgentTool<any, infer I, infer O, infer P>\n ? { input: I; output: O; progress: P }\n : never;\n};\n\n// --- skills --------------------------------------------------------------\n\n/**\n * A skill is instructions the model can go and fetch.\n *\n * Inlining every skill into the system prompt costs its tokens on every request\n * and gets worse with each skill added. So a skill is lowered to a tool: one\n * zero-parameter function per skill, in a reserved `skills` namespace, whose\n * description is the skill's and whose result is `instructions` plus any\n * `files`. Only those descriptions are prompted, and a skill the model never\n * reaches for costs a line of text.\n *\n * Lowering to a tool rather than to a synthetic `load_skill(name)` dispatcher\n * is the whole trick: discovery is then the same mechanism as everything else\n * the model chooses between, which means it runs on the provider's own\n * tool-selection machinery instead of on a string argument gemi would have to\n * validate, and a skill that is never loaded is a namespace entry rather than a\n * branch in our code. It is also why `deferred` applies here unchanged — with\n * tool search the namespace is searched, and without it the same tools are\n * listed inline, which for zero-parameter functions costs almost nothing.\n */\nexport interface SkillDefinition<Name extends string = string> {\n name: Name;\n /** Read on every request — this is what the model decides to load from. */\n description: string;\n /** A thunk so a large body stays off the startup path and out of memory. */\n instructions: string | (() => string | Promise<string>);\n /** Paths resolved relative to the app root, appended after `instructions`. */\n files?: string[];\n}\n\nexport class Skill<Name extends string = string> {\n readonly name: Name;\n readonly description: string;\n readonly instructions: string | (() => string | Promise<string>);\n readonly files?: string[];\n\n private constructor(params: SkillDefinition<Name>) {\n this.name = params.name;\n this.description = params.description;\n this.instructions = params.instructions;\n this.files = params.files;\n }\n\n static create<const Name extends string>(params: SkillDefinition<Name>): Skill<Name> {\n return new Skill(params);\n }\n}\n\n/** Reserved: a skill is lowered into a namespace of exactly this name. */\nexport const SKILLS_NAMESPACE = \"skills\";\n\nconst SKILLS_NAMESPACE_DESCRIPTION =\n \"Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.\";\n\n/**\n * Throws unless `schema` emits an object at its root.\n *\n * Both places a schema reaches the provider — a tool's parameters and an\n * agent's structured `output` — require one there: OpenAI's strict function\n * parameters and strict `json_schema` reject `anyOf` at the root (it is legal\n * only under a property), and a primitive or array root is not a parameter\n * list at all. Left to the provider, that is a 400 on the first request that\n * carries the schema, which an app then has to decode; checked here, it is an\n * error at startup naming the tool or agent that declared it.\n *\n * Read off the emitted JSON Schema rather than the builder's tree, so that a\n * hand-built schema (`questionSchema`, the skills' empty one, MCP's merged\n * input) is held to the same rule as one built with `s`.\n */\nfunction assertObjectRoot(schema: Schema<any>, owner: string, field: string): void {\n const json: JSONSchema | undefined = schema?.toJSONSchema?.();\n if (json?.type === \"object\") return;\n const found = !json\n ? \"no JSON Schema\"\n : json.anyOf\n ? \"a union (`anyOf`) — `s.union(...)`\"\n : json.type !== undefined\n ? `a schema of type ${JSON.stringify(json.type)}`\n : \"an unconstrained schema (`s.json()`)\";\n throw new Error(\n `${owner} declares an \\`${field}\\` whose root is ${found}, but the provider only accepts an object there (OpenAI rejects \\`anyOf\\` or a non-object at the root of tool parameters and structured output). Wrap it in an object, e.g. \\`s.object({ value: s.union([...]) })\\`, and read \\`.value\\` off the result.`,\n );\n}\n\n/**\n * A time limit has to be a positive number of milliseconds. `0` and a negative\n * number are refused rather than read as \"no limit\" or \"already expired\": both\n * readings are plausible, and a run that times out on its first tick, or a\n * limit that silently does nothing, is the kind of surprise worth an error at\n * startup instead.\n */\nfunction assertDuration(value: unknown, owner: string, field: string): void {\n if (typeof value === \"number\" && value > 0) return;\n throw new Error(\n `${owner} sets \\`${field}\\` to ${String(value)}, but it has to be a positive number of milliseconds. Use \\`null\\` for no limit.`,\n );\n}\n\n/** `Infinity` and `null` both mean \"no limit\"; `undefined` means \"not said\". */\nfunction normalizeDuration(value: number | null | undefined): number | null | undefined {\n if (value === undefined) return undefined;\n if (value === null || !Number.isFinite(value)) return null;\n return value;\n}\n\n/**\n * The longest delay `setTimeout` keeps: past it the runtime fires in about a\n * millisecond, which for a deadline would mean \"expire now\". A limit longer\n * than this (about 24.8 days) is no limit in practice and is treated as one.\n */\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n\n/**\n * Calls `onExpire` after `ms`, unless `ms` is no limit. Returns the cancel.\n */\nfunction startTimer(ms: number | null, onExpire: () => void): () => void {\n if (ms === null || ms > MAX_TIMER_MS) return () => {};\n const timer = setTimeout(onExpire, ms);\n return () => clearTimeout(timer);\n}\n\n/** `1500` as \"1.5s\", `600000` as \"10m\": for messages a model and a log read. */\nfunction formatDuration(ms: number): string {\n if (ms < 1000) return `${ms}ms`;\n if (ms < 60_000) return `${+(ms / 1000).toFixed(1)}s`;\n return `${+(ms / 60_000).toFixed(1)}m`;\n}\n\nconst EMPTY_PARAMETERS = {\n type: \"object\",\n properties: {},\n required: [] as string[],\n additionalProperties: false as const,\n};\n\n// --- agent ---------------------------------------------------------------\n\n/**\n * How hard the model should think before it answers, sent as the provider's own\n * effort setting (`reasoning.effort` on the Responses API).\n *\n * WHICH VALUES A MODEL TAKES IS THE MODEL'S BUSINESS, not gemi's. gpt-5 takes\n * `\"minimal\"` and not `\"none\"`; gpt-5.1 and later take `\"none\"`; Azure's\n * gpt-6-sol answers 400 to `\"minimal\"` and lists `none | low | medium | high |\n * xhigh | max` (#658). A closed union meant an app could not say the one value\n * its model wanted, and every new value waited on a gemi release. So the known\n * values are listed for autocomplete and any other string is passed through\n * unchanged — the same bet `capabilitiesForModel` makes on unknown model ids: a\n * value the model rejects fails loudly, once, with the API naming the values it\n * does accept (on `result().error`), and the fix is one line.\n *\n * `\"none\"` turns reasoning off on models that support it, which is what a short,\n * latency-bound call wants: with any effort at all, `maxOutputTokens` caps the\n * reasoning tokens too, and a small cap can be spent entirely on thinking. It is\n * not the same as leaving `reasoning` unset, which gets the model's default\n * (usually `\"medium\"`). On a model with no reasoning parameter at all\n * (`capabilities.reasoning` is false) every value, `\"none\"` included, is\n * dropped, since there is nothing to turn off.\n */\nexport type ReasoningEffort =\n | \"none\"\n | \"minimal\"\n | \"low\"\n | \"medium\"\n | \"high\"\n | \"xhigh\"\n | \"max\"\n // `string & {}` keeps the literals above in autocomplete; a bare `string`\n // would swallow them.\n | (string & {});\n\nexport interface CreateAgentParams<\n T extends readonly ToolEntry[],\n S extends readonly Skill[],\n O extends Schema<any> | undefined,\n> {\n name: string;\n /** The system prompt. Per-request additions belong on the controller, which\n * has the request; this is the part that is the same for everyone. */\n instructions?: string;\n provider: AgentProvider;\n tools?: T;\n /** Lowered into the reserved `skills` namespace — see `Skill`. The name is\n * reserved, so a namespace of your own cannot be called `skills`. */\n skills?: S;\n /**\n * Makes the final assistant turn strict JSON instead of prose. Tool turns are\n * unaffected — only the answer is constrained, which is the only place a\n * schema can apply once there is a tool loop.\n */\n output?: O;\n /** Ends the run with `finishReason: \"max-steps\"` rather than throwing: an\n * agent that loops is a bug to show, not an exception to swallow. */\n maxSteps?: number;\n /**\n * How far `ctx.runAgent` may nest below this agent. Default 3.\n *\n * It is a limit on the *tree*, taken from the run at the root, so raising it\n * on a sub-agent cannot deepen a run it did not start. A cycle is caught by\n * the agent-name chain before this is reached — this is for the mutually\n * recursive shape a name check cannot see, and for the merely runaway one.\n */\n maxDepth?: number;\n /** The model's reasoning effort, e.g. `\"none\"` for a quick one-liner or\n * `\"high\"` for a hard problem. Unset gets the model's default. Any string\n * the model accepts works — see `ReasoningEffort`. */\n reasoning?: ReasoningEffort;\n /**\n * A ceiling on the tokens one model call may produce, passed to the provider\n * as its own `max_output_tokens`.\n *\n * It bounds a degenerate generation. A model asked for non-strict JSON can\n * fall into emitting the same character until something stops it, and with\n * no cap the only thing that does is the client giving up — a turn that\n * never ends rather than one that fails. The cap turns that into a run\n * ending with `finishReason: \"length\"`, which an app can retry.\n *\n * Per model call, not per run: a run of four steps may produce four times\n * this. `maxSteps` is the bound on the run.\n */\n maxOutputTokens?: number;\n /**\n * Passed to the provider unchanged. Lower is steadier, which is worth having\n * for a generation whose shape matters more than its phrasing.\n *\n * SENT WHENEVER SET, and not capability-gated the way `reasoning` is.\n * `ProviderCapabilities` carries no flag for it, so `buildResponsesRequest`\n * writes it whenever it is a number and never drops it. That matters because\n * the newer reasoning models reject the parameter outright: setting this for\n * one is a 400 rather than a quietly degraded request. It is the same bargain\n * `output` takes in `request.ts` — an explicit choice is sent and the API gets\n * to say no, because silently dropping one leaves an app believing something\n * about its request that is not true.\n */\n temperature?: number;\n /**\n * Whether a run of this agent that ends with `finishReason: \"error\"` is\n * written to the app's log (`Log.error`, so `storage/logs` and the log\n * config's `onLogCreated`). Default `true`.\n *\n * On by default because the failure otherwise exists only as an `error` frame\n * on a stream a server-side caller may never read, and `result()` resolves\n * rather than rejects. A provider that cannot be reached, or a 400 for a\n * parameter the model refuses, then looks like an agent that said nothing.\n * Turn it off when the app already reports `result().error` (or the\n * controller's `onError`) itself and a second line would be noise.\n *\n * Also covers a tool that throws anything but a `ToolError`: the model and\n * the client only read that it failed (see `redactError`), so the log is\n * where its message and stack are.\n */\n logErrors?: boolean;\n /**\n * The longest one run of this agent may take, in milliseconds. Default\n * `DEFAULT_MAX_RUN_DURATION_MS`, ten minutes. `null` (or `Infinity`) turns\n * the limit off.\n *\n * When it is reached the run is stopped the way `stop()` stops it (every\n * tool call still in flight gets a `denied` result, `ctx.signal` aborts, the\n * provider request is cancelled) and it ends with `finishReason: \"error\"`\n * and `result().error.code` `\"timeout\"`, so it is logged and\n * `result({ throwOnError: true })` rejects. The transcript is finalized and\n * stored like any other.\n *\n * ON BY DEFAULT because the failure it bounds is silent and permanent. A tool\n * that never settles (a `fetch` with no timeout) used to keep its run open\n * for the life of the process, and the live-run registry with it: nobody is\n * watching, nobody calls `/stop`, and nothing expires. Ten minutes is far\n * past any interactive turn (a turn is `maxSteps` model calls plus their\n * tools), and it is per run, not per thread. Time spent waiting for the user\n * does not count, since a run waiting for input has already ended\n * (`awaiting-input`). Raise it for an agent whose runs are legitimately\n * long, such as a batch job or a long research loop.\n *\n * A sub-run started with `ctx.runAgent` is bounded by its parent's limit,\n * since it shares the parent's signal, and has none of its own unless its\n * agent sets one explicitly.\n */\n maxRunDurationMs?: number | null;\n /**\n * Bounds what each model call of this agent is sent: the latest turns of the\n * history that fit, cut at a turn start, with the cut moving in steps so the\n * provider's prompt cache keeps hitting. See `ContextWindowOptions` and\n * `windowMessages`. Unset (the default) sends the whole history, as before.\n *\n * Only the request changes. The run's history, `onMessage`, the store and\n * `result().messages` hold every message, so a thread stays whole and a\n * later turn can be sent a different window.\n */\n contextWindow?: ContextWindowOptions;\n /**\n * Called before every model call of a run of this agent, with the messages\n * about to be sent (after `contextWindow`), and may answer other ones, or\n * other instructions, for that call alone. See `PrepareStep`.\n */\n prepareStep?: PrepareStep;\n /**\n * Background jobs (#461). `contextBlock` bounds the `<jobs>` block the\n * controller adds to the system prompt on a thread with jobs: 20 by\n * default, `false` for none. See `AgentJobsOptions`.\n */\n jobs?: AgentJobsOptions;\n}\n\n/**\n * What `prepareStep` is told before a model call.\n */\nexport type PrepareStepContext = {\n /** 1 for the run's first model call, 2 for the one after its tools ran, … */\n step: number;\n /**\n * What this call would send: the run's history (stored and new), with older\n * tool-produced files already swapped for a line of text, and cut to\n * `contextWindow` when one is set. Copies where anything was changed; never\n * mutate a message in it, since the others are the run's own.\n */\n messages: AgentMessage[];\n /** The same history before `contextWindow` cut it. */\n history: readonly AgentMessage[];\n /** The system prompt this call would send. */\n instructions: string | undefined;\n /** What the run has spent so far, tools' sub-runs included. */\n usage: Usage;\n /** The previous model call's own usage, when it reported one. Its\n * `inputTokens` is how big the last request actually was. */\n lastStepUsage?: Usage;\n /** How the previous model call of this run ended. Absent on step 1. */\n lastFinishReason?: FinishReason;\n runId: string;\n threadId?: string;\n /** The agent's name. */\n agent: string;\n /** 0 for a run started at the top, 1 for a sub-run of one of its tools, … */\n depth: number;\n context: AgentContext;\n signal: AbortSignal;\n};\n\n/**\n * What `prepareStep` may change for one model call. Anything left out is sent\n * as it would have been.\n */\nexport type PrepareStepResult = {\n /**\n * The messages to send instead. Never stored, and the next step starts from\n * the run's history again rather than from these. A tool call left without\n * its result (or a result without its call) is repaired by the provider's\n * request builder, but cutting at `turnStarts` avoids it altogether.\n */\n messages?: AgentMessage[];\n /** The system prompt to send instead. */\n instructions?: string;\n};\n\n/**\n * A hook before every model call: see `CreateAgentParams.prepareStep`. It may\n * be async, and anything it throws fails the run (`finishReason: \"error\"`).\n *\n * The usual job is the context window: `windowMessages` with options decided\n * per call, a summary in place of older turns, a note. Keep it deterministic\n * for the same history and the provider's prompt cache keeps working.\n */\nexport type PrepareStep = (\n ctx: PrepareStepContext,\n) => PrepareStepResult | void | Promise<PrepareStepResult | void>;\n\n/**\n * How long a run may take when its agent does not say. See\n * `CreateAgentParams.maxRunDurationMs`.\n */\nexport const DEFAULT_MAX_RUN_DURATION_MS = 10 * 60 * 1000;\n\n/**\n * One call per client turn — a first message and an answer to a pending\n * approval take the same path, because they are the same thing: the next turn\n * of a conversation.\n */\nexport type AgentStreamParams = AgentStreamParamsBase & ContextParam;\n\ninterface AgentStreamParamsBase {\n /** Prior turns. The controller loads these from its store, or takes what the\n * client sent when running stateless. */\n messages: AgentMessage[];\n /** The client's turn: text, answers to pending calls, or both. */\n turn?: ClientTurn;\n /** Aborted by an explicit `stop`, not by a disconnect. */\n signal?: AbortSignal;\n runId?: string;\n threadId?: string;\n /** Appended to the agent's own `instructions` for this request only. */\n instructions?: string;\n /**\n * The app's own fields from the turn's request body, handed to every tool of\n * this run as `ctx.body`.\n *\n * Carried on the run because a run outlives the request that started it, so\n * that a refresh can reattach, and by the time a tool executes there is no\n * body left to read. See `AgentController`'s `Body`.\n */\n body?: Record<string, unknown>;\n /** Per-request model choice, e.g. letting a user pick. */\n provider?: AgentProvider;\n maxSteps?: number;\n reasoning?: ReasoningEffort;\n /** Overrides the agent's own for this run. A generation whose size varies by\n * request — a page with ten components against one with two — is the case\n * a fixed ceiling on the agent cannot serve. */\n maxOutputTokens?: number;\n temperature?: number;\n /** Overrides the agent's `maxRunDurationMs` for this run. `null` turns the\n * limit off. */\n maxRunDurationMs?: number | null;\n /**\n * Overrides the agent's `contextWindow` for this run. `false` sends the whole\n * history even when the agent sets one. Not handed down to a sub-run, which\n * uses its own agent's.\n */\n contextWindow?: ContextWindowOptions | false;\n /**\n * Runs after the agent's own `prepareStep`, on what that answered. Not\n * handed down to a sub-run. `AgentController` sets this from its\n * `prepareStep` method.\n */\n prepareStep?: PrepareStep;\n /**\n * Where `contextWindow.compact` keeps this thread's summaries, unless the\n * window names its own `store`. `AgentController` passes its `AgentStore`\n * when that implements the summary methods. Default\n * `defaultSummaryStore`, in memory.\n */\n summaryStore?: SummaryStore;\n /**\n * Fires once for every message this run completes — the user's turn, each\n * assistant turn, and any earlier message this turn amended by resolving a\n * pending call. It is the controller's persistence point, and it fires\n * whether or not anyone is still reading the stream, which is what makes a\n * run that outlives its request useful.\n *\n * A message may be reported twice across runs under the same id when a\n * pending call is resolved later; a store keyed by id should upsert.\n */\n onMessage?: (message: AgentMessage) => void | Promise<void>;\n /**\n * Fires once for the message this run made of the client's `turn` (its text\n * and files), right after `onMessage` has been called for it and before the\n * model is asked anything (#806). Not for an earlier message the turn\n * amended, nor for a file a tool showed, both of which are user messages\n * too: this is how a caller tells the turn itself apart from them. Not\n * called for a turn with no text and no files, or one the run failed before\n * taking in. `AgentController` uses it to call the app's `onMessage` for the\n * turn while the run is still going.\n */\n onTurn?: (message: AgentMessage) => void | Promise<void>;\n /**\n * What a client is told about a failure: the run's `error` frame, and the\n * result of a tool that threw (which the model reads too). Default\n * `redactError`, which keeps the code and replaces any message gemi did not\n * write (a provider's error body, an exception's text) with a fixed\n * sentence, since those carry hostnames, resource names, request ids and\n * connection strings. A tool that throws a `ToolError` keeps its message.\n *\n * Full detail stays server-side: on `result().error`, in the log, and in\n * the controller's `onError`. `AgentController` sets this from its\n * `redactError` method. Handed down unchanged to a sub-run.\n */\n redactError?: ErrorRedactor;\n /**\n * Where the nonces of answered pending calls and re-entered sub-run records\n * are spent, which is what makes a signed answer single-use (#445). Default\n * the process-wide `MemoryNonceStore`: exact for one instance, but with\n * several each would accept a replayed answer once. Give a shared store\n * (`RedisNonceStore`, or your own `NonceStore`) when running more than one.\n * `AgentController` sets this from its `nonces`. Handed down unchanged to a\n * sub-run.\n */\n nonces?: NonceStore;\n /**\n * Where an approved tool's execution is claimed and its result recorded,\n * which is what makes an approval run its tool at most once (#458). Before\n * an approved tool runs, the run claims an id derived from the call the\n * approval covers: a presentation of an approval that already ran gets the\n * recorded result back instead of running the tool again, and one presented\n * while another instance is still running it gets a `tool_error` result.\n * Without a store an approved tool runs as before, guarded by the nonce\n * alone. `AgentController` sets this from its `receipts`. Handed down\n * unchanged to a sub-run.\n */\n receipts?: ReceiptStore;\n /**\n * Who this run is answering: the principal every pending call and parked\n * sub-run record it mints is bound to (#447). An answer, or a record, only\n * verifies on a later run with the same `subject`, so a token lifted from\n * one user's history cannot be spent in another user's turn. `null`, or\n * omitted, is an anonymous run, and only verifies on another anonymous one.\n *\n * `AgentController` sets this from `runOwner` (`user:<id>` by default), so it\n * must answer the same on the turn that asks and the turn that answers.\n * Handed down unchanged to a sub-run.\n */\n subject?: string | null;\n /**\n * The attachment handle every tool of this run is given as `ctx.attachments`.\n *\n * Resolved by the controller from the request — `attachmentsFor(req,\n * threadId)` — and passed in rather than reached for, because the scope is a\n * fact about the caller and the run has no way to derive one. `null`, or\n * omitted, is a request with no subject: the object tools get still exists\n * and every method on it throws a sentence naming `attachmentScope()`.\n *\n * Handed down unchanged to a sub-run started by `ctx.runAgent`. A sub-agent\n * is running on behalf of the same caller — that is the only reason it is\n * allowed to run at all — so it reads and writes the same scope, and a tool\n * three levels down can be given an id its parent parked. Widening it here\n * would be the confused-deputy hole in reverse.\n */\n attachments?: ScopedAttachments | null;\n /**\n * Lets this run's tools start background jobs with `ctx.jobs` (#461).\n * `AgentController` passes it on a threaded turn: a job settles into the\n * thread, so a run with no thread has nowhere to put the result. Without it\n * `ctx.jobs.start` throws `JobsRequireThreadError`. Not handed to sub-runs.\n */\n jobs?: RunJobs;\n /**\n * Set by `ctx.runAgent` and by nothing else.\n *\n * It rides on the public params rather than on a back door because\n * `Agent.stream` is the only way to start a run and a sub-run is a run —\n * giving nesting its own construction path would mean two places where a run\n * is set up, and the second one would drift. Omitted, a run is a root: depth\n * 0, no path, signatures over its own id.\n */\n nesting?: NestedContext;\n}\n\n/**\n * Where a run sits inside a tree of runs. Carried down by `ctx.runAgent`.\n *\n * `signingRunId` and `signingPath` are the reason this is threaded rather than\n * recomputed: a pending call a sub-agent raises is answered by the *client*,\n * which only ever sees the root run, so the token has to be minted under the\n * root's id and the sub-run's path from the start. Re-signing the token at each\n * level on the way up would work too, and would throw away every signature but\n * the outermost one — this way the run that asks the question is also the run\n * that can check the answer, which is where the tool, its schema and its `kind`\n * all already are.\n */\nexport type NestedContext = {\n /** 0 at the root; `ctx.depth` inside a tool of this run. */\n depth: number;\n /** The `maxDepth` of the run at the root of the tree. */\n maxDepth: number;\n /** Agent names from the root down to and including this one, so a cycle can\n * be reported as the chain that caused it. */\n chain: string[];\n /** The root run's id: what a pending call raised here is signed under. */\n signingRunId: string;\n /** Tool-call ids from the root down to the call that started this run. */\n signingPath: string[];\n /**\n * Inherited, and once it is `\"deny\"` it stays `\"deny\"` all the way down. A\n * caller that asked for an autonomous sub-agent must not have a question\n * surface from three levels below it, and the only way to promise that is to\n * make the whole subtree refuse rather than to check at the top.\n */\n onPending: \"escalate\" | \"deny\";\n};\n\n/**\n * Why a run ended with `finishReason: \"error\"`, as the server sees it.\n *\n * The same `code`, `message` and `retryable` as the `error` frame the run put\n * on its stream, plus what only the server should have: the HTTP `status` and\n * the provider's `requestId` when the failure was a response from the\n * provider. Neither is ever written to a frame. A frame is built from this\n * through one method (`redact`), which copies the `AgentError` fields by name,\n * so a field added here stays server-side unless someone puts it there on\n * purpose, and redacts the message (#446, see `redactError`).\n *\n * `message` is the provider's own sentence (\"Unsupported parameter:\n * 'temperature' ...\"), which is what a log needs and why this is kept off the\n * wire in any form richer than the frame already is.\n */\nexport type AgentRunFailure = AgentError & {\n /** The provider's HTTP status, when the failure was a non-2xx response. */\n status?: number;\n /** The provider's request id (`x-request-id`), when it sent one. */\n requestId?: string;\n};\n\nexport type AgentRunResult<T extends ToolShapes, O> = {\n runId: string;\n /** Everything produced this run — the controller persists these. */\n messages: AgentMessage<T, O>[];\n finishReason: FinishReason;\n usage: Usage;\n /** Set when the agent declares an `output` schema and the run finished. */\n output?: O;\n /**\n * Why the run failed. Set exactly when `finishReason` is `\"error\"`, and\n * absent otherwise — an aborted run, `max-steps` and `length` are outcomes,\n * not failures, and carry no error.\n *\n * Before this field a server-side caller that awaited `result()` saw only\n * `finishReason: \"error\"` and no output: the cause was an `error` event on a\n * stream it never read. Pass `result({ throwOnError: true })` to have the run\n * reject with an `AgentRunError` instead.\n */\n error?: AgentRunFailure;\n};\n\nexport type AgentResultOptions = {\n /**\n * Reject with an `AgentRunError` when the run ends with\n * `finishReason: \"error\"`, instead of resolving with `result.error` set.\n * Every other finish reason resolves as usual. Default `false`.\n */\n throwOnError?: boolean;\n};\n\n/**\n * What `result({ throwOnError: true })` rejects with.\n *\n * It carries the whole `result` as well as the error's fields, because a run\n * that failed on step three still produced steps one and two — their messages\n * and their usage are billed and may need persisting — and a rejection that\n * dropped them would make `throwOnError` the lossy way to call `result()`.\n */\nexport class AgentRunError extends Error {\n readonly code: AgentRunFailure[\"code\"];\n readonly retryable: boolean;\n readonly status?: number;\n readonly requestId?: string;\n readonly toolCallId?: string;\n readonly runId: string;\n readonly result: AgentRunResult<ToolShapes, unknown>;\n\n constructor(result: AgentRunResult<ToolShapes, unknown> & { error: AgentRunFailure }) {\n super(result.error.message);\n this.name = \"AgentRunError\";\n this.code = result.error.code;\n this.retryable = result.error.retryable;\n this.status = result.error.status;\n this.requestId = result.error.requestId;\n this.toolCallId = result.error.toolCallId;\n this.runId = result.runId;\n this.result = result;\n }\n}\n\n/**\n * A run is an async iterable of events, and the SSE encoding is a method on it\n * rather than a separate helper — so the same object serves a controller\n * returning a `Response` and a server-side caller that just wants to await the\n * result.\n *\n * A run keeps going when its request ends. That is what makes reattaching after\n * a refresh possible, and it is why `stop()` is an explicit call rather than the\n * client closing a socket.\n */\nexport interface AgentRun<T extends ToolShapes = ToolShapes, O = unknown> extends AsyncIterable<\n AgentStreamEvent<T, O>\n> {\n readonly runId: string;\n /** Numbered events, replayable from a cursor. `toResponse` is this, encoded. */\n frames(from?: number): AsyncIterable<AgentStreamFrame<T, O>>;\n toResponse(params?: { from?: number }): Response;\n /**\n * Settles when the run is over. Resolves for every finish reason, `\"error\"`\n * included, with the cause on `result.error`; pass `{ throwOnError: true }`\n * to reject with an `AgentRunError` for that one instead.\n */\n result(options?: AgentResultOptions): Promise<AgentRunResult<T, O>>;\n /**\n * Cancels the run and closes the conversation behind it: every tool call\n * still in flight gets a `denied` result with `cause: \"stopped\"`, the\n * assistant message is finalized with `finishReason: \"aborted\"`, and both go\n * through `onMessage` like any other message.\n *\n * That last part is the point. A cancel that merely stops emitting leaves a\n * history the provider will reject on the next turn, so the run's last act is\n * to make the transcript valid — which is also what lets the user carry on\n * talking instead of starting over.\n */\n stop(params?: { reason?: string }): void;\n}\n\n/**\n * A tool plus where it sits in the prompt. Fixed for the life of the agent,\n * except `inputSchema`, which a run fills in for a tool whose schema is\n * resolved per run (`ToolInputSchema`).\n */\ntype ResolvedTool = {\n tool: AnyAgentTool;\n namespace?: string;\n deferred: boolean;\n /** `undefined` until the run resolves a per-run schema. */\n inputSchema?: Schema<any>;\n};\n\n/** What a run needs from its agent, resolved once at `Agent.create`. */\ntype RunConfig = {\n name: string;\n instructions?: string;\n provider: AgentProvider;\n registry: Map<string, ResolvedTool>;\n providerTools: (ProviderToolSpec | ProviderToolNamespace)[];\n output?: Schema<any>;\n maxSteps: number;\n maxDepth: number;\n reasoning?: ReasoningEffort;\n maxOutputTokens?: number;\n temperature?: number;\n logErrors: boolean;\n /**\n * As the agent or the stream params gave it, with `Infinity` already folded\n * into `null`. `undefined` is \"not said\", which a root run reads as\n * `DEFAULT_MAX_RUN_DURATION_MS` and a sub-run as no limit of its own.\n */\n maxRunDurationMs: number | null | undefined;\n contextWindow?: ContextWindowOptions;\n /** The agent's hook, then the stream's, in that order. */\n prepareStep: PrepareStep[];\n};\n\nconst DEFAULT_MAX_STEPS = 8;\n/** Three is enough for \"agent, sub-agent, specialist\" and small enough that a\n * runaway tree is a readable error rather than a stack trace. */\nconst DEFAULT_MAX_DEPTH = 3;\n\nexport class Agent<\n T extends readonly ToolEntry[] = readonly ToolEntry[],\n S extends readonly Skill[] = readonly Skill[],\n O extends Schema<any> | undefined = undefined,\n> {\n readonly name: string;\n readonly tools: T;\n readonly skills: S;\n readonly provider: AgentProvider;\n readonly output: O;\n readonly instructions?: string;\n readonly maxSteps: number;\n readonly maxDepth: number;\n readonly reasoning?: ReasoningEffort;\n /**\n * The time limit a run of this agent gets when it is started at the top (a\n * sub-run is bounded by its parent): `DEFAULT_MAX_RUN_DURATION_MS` unless\n * `Agent.create` said otherwise, and `null` for no limit.\n */\n readonly maxRunDurationMs: number | null;\n /** See `CreateAgentParams.jobs`. */\n readonly jobs: AgentJobsOptions;\n\n private readonly config: RunConfig;\n\n private constructor(params: CreateAgentParams<T, S, O>) {\n this.name = params.name;\n this.instructions = params.instructions;\n this.provider = params.provider;\n this.tools = (params.tools ?? ([] as unknown as T)) as T;\n this.skills = (params.skills ?? ([] as unknown as S)) as S;\n this.output = params.output as O;\n this.maxSteps = params.maxSteps ?? DEFAULT_MAX_STEPS;\n this.maxDepth = params.maxDepth ?? DEFAULT_MAX_DEPTH;\n this.reasoning = params.reasoning;\n this.jobs = params.jobs ?? {};\n const limit = normalizeDuration(params.maxRunDurationMs);\n this.maxRunDurationMs = limit === undefined ? DEFAULT_MAX_RUN_DURATION_MS : limit;\n\n const { registry, providerTools } = lowerTools(this.tools, this.skills);\n this.config = {\n name: this.name,\n instructions: this.instructions,\n provider: this.provider,\n registry,\n providerTools,\n output: params.output as Schema<any> | undefined,\n maxSteps: this.maxSteps,\n maxDepth: this.maxDepth,\n reasoning: this.reasoning,\n maxOutputTokens: params.maxOutputTokens,\n temperature: params.temperature,\n logErrors: params.logErrors ?? true,\n maxRunDurationMs: limit,\n contextWindow: params.contextWindow,\n prepareStep: params.prepareStep ? [params.prepareStep] : [],\n };\n }\n\n static create<\n const T extends readonly ToolEntry[],\n const S extends readonly Skill[],\n O extends Schema<any> | undefined = undefined,\n >(params: CreateAgentParams<T, S, O>): Agent<T, S, O> {\n if (params.output) {\n assertObjectRoot(params.output as Schema<any>, `The agent \"${params.name}\"`, \"output\");\n }\n if (params.maxRunDurationMs != null) {\n assertDuration(params.maxRunDurationMs, `The agent \"${params.name}\"`, \"maxRunDurationMs\");\n }\n const block = params.jobs?.contextBlock;\n if (block && block.max !== undefined && !(Number.isInteger(block.max) && block.max > 0)) {\n throw new Error(\n `The agent \"${params.name}\" sets \\`jobs.contextBlock.max\\` to ${String(block.max)}, but it has to be a whole number above 0. Use \\`contextBlock: false\\` for no block.`,\n );\n }\n return new Agent(params);\n }\n\n stream(params: AgentStreamParams): AgentRun<ToolShapesOf<T>, OutputOf<O>> {\n const config: RunConfig = {\n ...this.config,\n provider: params.provider ?? this.config.provider,\n maxSteps: params.maxSteps ?? this.config.maxSteps,\n reasoning: params.reasoning ?? this.config.reasoning,\n maxOutputTokens: params.maxOutputTokens ?? this.config.maxOutputTokens,\n temperature: params.temperature ?? this.config.temperature,\n maxRunDurationMs:\n params.maxRunDurationMs !== undefined\n ? normalizeDuration(params.maxRunDurationMs)\n : this.config.maxRunDurationMs,\n contextWindow:\n params.contextWindow === false\n ? undefined\n : (params.contextWindow ?? this.config.contextWindow),\n prepareStep: params.prepareStep\n ? [...this.config.prepareStep, params.prepareStep]\n : this.config.prepareStep,\n };\n if (params.maxRunDurationMs != null) {\n assertDuration(\n params.maxRunDurationMs,\n `Agent.stream for \"${this.name}\"`,\n \"maxRunDurationMs\",\n );\n }\n return new AgentRunImpl(config, params) as unknown as AgentRun<ToolShapesOf<T>, OutputOf<O>>;\n }\n}\n\nexport type OutputOf<O> = O extends Schema<any> ? Infer<O> : never;\n\nexport type AnyAgent = Agent<any, any, any>;\n\n// --- lowering ------------------------------------------------------------\n\nfunction toolSpec(resolved: ResolvedTool): ProviderToolSpec {\n const schema = resolved.inputSchema;\n return {\n name: resolved.tool.name,\n description: resolved.tool.description,\n // A per-run schema is not known yet; the run swaps this spec for one built\n // from the resolved schema (`AgentRunImpl.resolveToolSchemas`) before the\n // provider ever sees it.\n parameters: schema ? schema.toJSONSchema() : EMPTY_PARAMETERS,\n // Read off the schema, not asserted: an input containing an `s.json()`\n // field cannot be sent strict, and the tool that says so is the only place\n // that knows.\n strict: schema ? supportsStrict(schema) : true,\n deferred: resolved.deferred,\n };\n}\n\n/** The tool's schema when it is fixed, `undefined` when it is resolved per run. */\nfunction staticInputSchema(tool: AnyAgentTool): Schema<any> | undefined {\n return typeof tool.inputSchema === \"function\" ? undefined : tool.inputSchema;\n}\n\n/**\n * Flattens the declared tuple into the registry the loop dispatches on, and the\n * shape the provider is shown.\n *\n * Both are built once, at `Agent.create`, because neither depends on the\n * request: a tool is a singleton and a namespace is a static grouping. Building\n * them per run would be work repeated on every turn for an answer that cannot\n * change — and it would move the name-collision errors below out of startup and\n * into the first user's first message.\n */\nfunction lowerTools(\n entries: readonly ToolEntry[],\n skills: readonly Skill[],\n): {\n registry: Map<string, ResolvedTool>;\n providerTools: (ProviderToolSpec | ProviderToolNamespace)[];\n} {\n const registry = new Map<string, ResolvedTool>();\n const providerTools: (ProviderToolSpec | ProviderToolNamespace)[] = [];\n\n const register = (resolved: ResolvedTool) => {\n if (registry.has(resolved.tool.name)) {\n throw new Error(\n `Two tools are named \"${resolved.tool.name}\". Tool names are global within an agent — the client discriminates a tool part by name alone.`,\n );\n }\n registry.set(resolved.tool.name, resolved);\n };\n\n for (const entry of entries) {\n if (entry instanceof ToolNamespace) {\n if (entry.name === SKILLS_NAMESPACE) {\n throw new Error(\n `\"${SKILLS_NAMESPACE}\" is reserved for the namespace skills are lowered into. Rename the namespace — silently shadowing it would make every skill unreachable with no error to read.`,\n );\n }\n const members: ProviderToolSpec[] = [];\n for (const tool of entry.tools) {\n const resolved = {\n tool,\n namespace: entry.name,\n deferred: entry.deferred || tool.deferred,\n inputSchema: staticInputSchema(tool),\n };\n register(resolved);\n members.push(toolSpec(resolved));\n }\n providerTools.push({ name: entry.name, description: entry.description, tools: members });\n continue;\n }\n const resolved = {\n tool: entry,\n deferred: entry.deferred,\n inputSchema: staticInputSchema(entry),\n };\n register(resolved);\n providerTools.push(toolSpec(resolved));\n }\n\n if (skills.length > 0) {\n const members: ProviderToolSpec[] = [];\n for (const skill of skills) {\n const tool = skillTool(skill);\n register({\n tool,\n namespace: SKILLS_NAMESPACE,\n deferred: false,\n inputSchema: staticInputSchema(tool),\n });\n members.push({\n name: skill.name,\n description: skill.description,\n parameters: EMPTY_PARAMETERS,\n strict: true,\n // Not deferred: the whole cost of a skill in the prompt is its name and\n // description, and those are exactly what deferral keeps. Withholding\n // an empty parameter object saves nothing and adds a round trip.\n deferred: false,\n });\n }\n providerTools.push({\n name: SKILLS_NAMESPACE,\n description: SKILLS_NAMESPACE_DESCRIPTION,\n tools: members,\n });\n }\n\n return { registry, providerTools };\n}\n\n/** The zero-parameter tool a skill becomes. */\nfunction skillTool(skill: Skill): AnyAgentTool {\n return AgentTool.create({\n name: skill.name,\n description: skill.description,\n inputSchema: {\n toJSONSchema: () => EMPTY_PARAMETERS,\n parse: () => ({}),\n safeParse: () => ({ ok: true as const, value: {} }),\n } as unknown as Schema<Record<string, never>>,\n // The thunk is called here, on load, and not at startup: a skill body can\n // be a megabyte of markdown, and an agent that declares twelve of them\n // should not read twelve files to answer \"hello\".\n execute: async () => {\n const body =\n typeof skill.instructions === \"function\" ? await skill.instructions() : skill.instructions;\n const sections = [body];\n for (const file of skill.files ?? []) {\n sections.push(`--- ${file} ---\\n${await readSkillFile(file)}`);\n }\n return sections.join(\"\\n\\n\");\n },\n }) as unknown as AnyAgentTool;\n}\n\nasync function readSkillFile(file: string): Promise<string> {\n try {\n return await Bun.file(file).text();\n } catch (error) {\n // A missing file is told to the model rather than thrown: the rest of the\n // skill is still worth having, and a run should not die because one of\n // several appendices moved.\n return `(could not be read: ${(error as Error).message})`;\n }\n}\n\n// --- the run -------------------------------------------------------------\n\nfunction isAsyncGenerator(value: unknown): value is AsyncGenerator<unknown, unknown, void> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as AsyncGenerator).next === \"function\" &&\n Symbol.asyncIterator in (value as object)\n );\n}\n\ntype StepOutcome = {\n reason: FinishReason;\n error?: AgentError;\n /** The HTTP response behind `error`, when the provider reported one. */\n detail?: { status?: number; requestId?: string };\n};\n\n/**\n * The prior transcript plus what a later run produced, upserted by id.\n *\n * A run only reports the messages it *made*, so a resumed sub-run's\n * `result().messages` is the tail and not the whole thing — and a message it\n * amended (the one holding the call that was finally answered) comes back under\n * an id the prior transcript already has. Appending would duplicate it and\n * replacing the array would lose everything before the resume, so the record on\n * `ToolCallPart.nested` is rebuilt by upsert, which is the same rule a store\n * keyed by message id follows.\n */\nfunction mergeMessages(prior: AgentMessage[], produced: AgentMessage[]): AgentMessage[] {\n const merged = [...prior];\n const index = new Map(merged.map((message, at) => [message.id, at]));\n for (const message of produced) {\n const at = index.get(message.id);\n if (at === undefined) {\n index.set(message.id, merged.length);\n merged.push(message);\n } else {\n merged[at] = message;\n }\n }\n return merged;\n}\n\n/** Tool calls in a transcript with no result anywhere in it. */\nfunction openCallIds(messages: AgentMessage[]): Set<string> {\n const resolved = new Set<string>();\n for (const message of messages) {\n for (const part of message.content) {\n if (part.type === \"tool-result\") resolved.add(part.toolCallId);\n }\n }\n const open = new Set<string>();\n for (const message of messages) {\n for (const part of message.content) {\n if (part.type === \"tool-call\" && !resolved.has(part.toolCallId)) open.add(part.toolCallId);\n }\n }\n return open;\n}\n\n/**\n * A sub-agent's structured answer, read back out of its transcript.\n *\n * `NestedRun` has nowhere to put an `output` — it is a transcript, and the\n * output part is already in it — so a memoized run recovers the value the same\n * way a client would. That keeps the memo honest: what a replay returns is\n * derived from what was persisted, not from a second copy that could disagree\n * with it.\n */\nfunction outputOf(messages: AgentMessage[]): unknown {\n for (let i = messages.length - 1; i >= 0; i--) {\n const content = messages[i].content;\n for (let j = content.length - 1; j >= 0; j--) {\n const part = content[j];\n if (part.type === \"output\" && part.partial !== true) return part.value;\n }\n }\n return undefined;\n}\n\n/** For the replay-mismatch message, where the label is what tells two runs of\n * the same agent apart. */\nfunction describeRun(agent: string, label: string | undefined): string {\n return label === undefined ? `\"${agent}\"` : `\"${agent}\" labelled \"${label}\"`;\n}\n\n/** A message flattened to text, for comparing one turn's seed against another's. */\nfunction textOfMessage(message: AgentMessage): string {\n return message.content\n .map((part) => (part.type === \"text\" ? part.text : `<${part.type}>`))\n .join(\"\");\n}\n\n/**\n * What a `runAgent` call would start its sub-run from, as a comparable string.\n *\n * `null` when the call names no seed at all — `runAgent(agent, {})` — which is\n * the one shape with nothing to compare against, since the record's first\n * message would then be something the sub-agent said rather than something it\n * was told.\n */\nfunction seedOf(params: RunAgentParams): string | null {\n if (params.prompt !== undefined) return `user:${params.prompt}`;\n const first = params.messages?.[0];\n return first ? `${first.role}:${textOfMessage(first)}` : null;\n}\n\n// Moved to `contextWindow.ts`, which splits a thread into turns with it, and\n// re-exported here for the controller and the tests that import it from here.\nexport { injectedMessageIds };\n\n/**\n * How many tool-produced files stay attached to the request. See\n * `AgentRunImpl.historyForProvider`, which is where the reasoning lives.\n */\nconst SHOWN_FILE_WINDOW = 1;\n\n/**\n * Why the Nth attachment of a replayed tool body is not the Nth attachment of\n * the turn that escalated, or `null` when it is.\n *\n * DELIBERATELY WEAKER THAN `replayMismatch`, and the reason is what each of them\n * is protecting. A crossed sub-run pairs a human's answer with a question they\n * never saw, which is consent applied to the wrong thing and is invisible\n * afterwards; a crossed attachment shows the model the wrong picture, which is\n * wrong and is also the sort of wrong the next turn can talk its way out of. So\n * this checks the two things that cannot change for an honest reason and\n * nothing else.\n *\n * Not the size, and not any digest of the bytes: the body that produced this\n * blob ran again from the top and produced it again, and almost nothing that\n * makes an image — a model, a renderer with a timestamp in it, a compressor\n * with a thread pool — is byte-identical twice. Comparing bytes would fail the\n * common case and catch the rare one.\n *\n * Not the name either, for a smaller version of the same reason: filenames\n * carry dates and counters, and an app that names its output\n * `chart-${Date.now()}.png` would find its tool broken on every resume.\n *\n * What is left is the media type and whether the caller asked to show it, which\n * is exactly what changes when a body takes a different branch — the CSV path\n * instead of the PNG path, the quiet `put` instead of the `showModel` one.\n */\nfunction putMismatch(\n recorded: ToolAttachmentPut,\n blob: Blob,\n params: PutAttachmentParams,\n): string | null {\n const mimeType = params.mimeType || blob.type || \"\";\n if (mimeType && recorded.attachment.mimeType !== mimeType) {\n return (\n `was ${JSON.stringify(recorded.attachment.mimeType)} on the turn that escalated ` +\n `and is ${JSON.stringify(mimeType)} on the replay`\n );\n }\n const shown = Boolean(params.showModel);\n if (shown !== Boolean(recorded.shown)) {\n return shown\n ? \"was stored without showModel on the turn that escalated and asks for showModel on the replay\"\n : \"was stored with showModel on the turn that escalated and asks for a plain put on the replay\";\n }\n return null;\n}\n\n/**\n * Why the Nth sub-run of a replayed tool body is not the Nth sub-run of the\n * turn that escalated, or `null` when it is.\n *\n * Agent and label catch the branchy shape. THE SEED IS WHAT CATCHES THE SHAPE\n * THE DOC COMMENT NAMES FIRST: `runAgent` in a loop, the same agent every time,\n * no label — the default and the common case — over a list that came back in a\n * different order, from a `Set`, a re-sorted query, or a second read of a\n * mutable column. Agent and label match for every element of such a loop, so\n * without this the user's answer to the second question is folded into the run\n * the tool now believes is the first, and the model is told the crossed pair as\n * fact. Nothing in the transcript, the stream or the store shows it happened.\n *\n * The record's first message is the seed because `runNested` records it that\n * way — the user turn built from `prompt`, or the first of `params.messages`.\n * `instructions` is not compared: it never enters the transcript, and\n * `NestedRun` has nowhere to keep it.\n */\nfunction replayMismatch(\n recorded: NestedRun,\n agent: AnyAgent,\n params: RunAgentParams,\n): string | null {\n if (recorded.agent !== agent.name || recorded.label !== params.label) {\n return (\n `was ${describeRun(recorded.agent, recorded.label)} on the turn that escalated ` +\n `and is ${describeRun(agent.name, params.label)} on the replay`\n );\n }\n const seed = seedOf(params);\n const first = recorded.messages[0];\n const was = first ? `${first.role}:${textOfMessage(first)}` : null;\n if (seed !== null && was !== null && seed !== was) {\n return (\n `was started with ${JSON.stringify(was)} on the turn that escalated ` +\n `and with ${JSON.stringify(seed)} on the replay`\n );\n }\n return null;\n}\n\n/**\n * What is left of an answer's path once this run's own prefix is removed.\n *\n * `null` means the answer is not addressed to this run at all, which is a\n * client error rather than a routing decision — an empty remainder means \"a\n * call this run made itself\", and a non-empty one names the tool call to\n * re-enter.\n */\nfunction pathBelow(path: string[] | undefined, prefix: string[]): string[] | null {\n const full = path ?? [];\n if (full.length < prefix.length) return null;\n for (let i = 0; i < prefix.length; i++) {\n if (full[i] !== prefix[i]) return null;\n }\n return full.slice(prefix.length);\n}\n\n/**\n * The one memo rule a re-entered tool body plays by, in one place.\n *\n * A tool that escalates cannot be suspended — a paused async generator does not\n * fit in a message history — so it is re-entered FROM THE TOP on the next turn\n * and everything it did the first time has to be recognised rather than done\n * again. The only key available is the order the calls happened in, and the only\n * place a record can live is the message history, because that is the sole state\n * that crosses a turn boundary in a thread and in the browser alike.\n *\n * So: an array on the `ToolCallPart`, a snapshot of its length taken before the\n * body runs (everything already there came from an earlier turn and is\n * replayable; everything appended past that point is happening for the first\n * time), and an index that walks it. `ctx.runAgent` and `ctx.attachments.put`\n * both need exactly this and they share it here rather than each growing their\n * own copy — the failure of two copies is that one of them is fixed and the\n * other is not, and both are invisible until someone resumes.\n *\n * The array is created by the first WRITE and not before. `nested: []` or\n * `attachments: []` on every tool call would be a wire and store change paid for\n * by every app that has neither — and \"on first use\" is not good enough, because\n * a slot is handed out before the work that fills it can fail. A tool whose only\n * `put` throws (no attachment scope, a provider that cannot read files) must\n * leave a tool call with no `attachments` field, not an empty array announcing\n * an attachment that does not exist.\n *\n * A SLOT IS RESERVED WHEN IT IS ASKED FOR, THOUGH, NOT WHEN IT IS FILLED, and\n * that is deliberate: a tool body may run its `put`s or its `runAgent`s\n * concurrently — `await Promise.all(images.map((i) => ctx.attachments.put(i)))`\n * is the obvious way to write it — and every one of them takes its index\n * synchronously, in map order, before its first `await`. Handing out the index\n * on success instead would number them by the order they *finished*, which the\n * network decides and which the next turn will not reproduce. So the index\n * always advances, and a slot whose work threw stays unwritten.\n *\n * An unwritten slot before a written one would be a hole, and a hole is `null`\n * once it goes through JSON — which is what a consumer walking `part.attachments`\n * would crash on. `fill` is what stands in its place. `runAgent` passes none, so\n * `nested` keeps exactly the shape it has had since sub-agents existed, holes\n * and all: `NestedRun` describes a sub-run that happened and has no honest shape\n * for one that did not, and inventing one is a change to nesting rather than to\n * the issue this memo was extracted for.\n *\n * What is NOT shared is what to do with a hit, and it could not be: a recorded\n * sub-run that parked has to be *continued*, so `runAgent`'s memo sometimes\n * returns and sometimes falls through, while a recorded `put` is total — the\n * bytes are already stored and the id is already in the transcript the model\n * read, so there is nothing left to finish. The drift check differs too, and for\n * a reason worth reading: see `replayMismatch` against the note on\n * `putMismatch`.\n */\nclass ReplayMemo<R> {\n private index = 0;\n private readonly replayable: number;\n\n constructor(\n private readonly read: () => R[] | undefined,\n private readonly create: () => R[],\n /** What stands in for a slot whose work threw. See the note above. */\n private readonly fill?: () => R,\n ) {\n this.replayable = read()?.length ?? 0;\n }\n\n /**\n * The next slot: its index, the record a previous turn left there if it left\n * one, and the way to write this turn's.\n *\n * `write` is the only thing that touches the array. Call it once the record\n * exists and not before — everything between `next()` and `write()` is work\n * that may throw, and a slot nobody writes is a slot that costs nothing.\n */\n next(): { at: number; recorded: R | undefined; write: (record: R) => void } {\n const at = this.index++;\n return {\n at,\n recorded: at < this.replayable ? this.read()?.[at] : undefined,\n write: (record: R) => {\n const rows = this.read() ?? this.create();\n if (this.fill) {\n for (let i = rows.length; i < at; i++) rows[i] = this.fill();\n }\n rows[at] = record;\n },\n };\n }\n}\n\nclass AgentRunImpl implements AgentRun<ToolShapes, unknown> {\n readonly runId: string;\n\n /** Replaced once, by `resolveToolSchemas`, when the agent has per-run tool schemas. */\n private config: RunConfig;\n private readonly params: AgentStreamParams;\n /** `params.context`, or `{}` for a run started without one. See `AgentContext`. */\n private readonly context: AgentContext;\n private readonly controller = new AbortController();\n\n private readonly buffer: AgentStreamFrame<ToolShapes, unknown>[] = [];\n private readonly waiters = new Set<() => void>();\n private seq = 0;\n private ended = false;\n\n /** The working history handed to the provider, and what this run produced. */\n private history: AgentMessage[] = [];\n /** `contextWindow.compact`'s summaries for this run, by cut. */\n private readonly compactMemo = new Map<string, ThreadSummary | null>();\n /** How the previous model call ended, for `prepareStep`. */\n private lastStep: { reason: FinishReason; usage?: Usage } | undefined;\n private produced: AgentMessage[] = [];\n private current: AgentMessage | null = null;\n /**\n * Whether a step of the message now open ran out of output budget.\n *\n * Separate from `finishReason` because they are different facts: a step that\n * hits the ceiling and also calls a tool closes its message `awaiting-input` or\n * `max-steps`. Cleared as each message is finalized.\n */\n private outputTruncated = false;\n\n /** Messages from an earlier run this one has amended, by id. Cloned once and\n * reused, so two results for the same message do not fork it. */\n private readonly amended = new Map<string, AgentMessage>();\n /**\n * Messages this run finished outside `finalizeMessage` that have not yet gone\n * through `onMessage`: earlier turns' messages it amended, and messages it\n * injected for a file a tool showed.\n *\n * They wait rather than being reported where they are made, because\n * `onMessage` is the persistence point for an app that has no `store` and an\n * append-only table keyed by a serial id reads back in the order the hook was\n * called. Reporting an injected message from inside `runTools` would call the\n * hook for it BEFORE the assistant message whose tool call produced it, since\n * that message is only finalized once the step is over — so the transcript in\n * the app's database would put the file above the turn that made it, while\n * `result.messages`, the stream and `history` all put it below.\n */\n private readonly unreported = new Set<AgentMessage>();\n\n private usage: Usage = emptyUsage();\n private finishReason: FinishReason = \"stop\";\n /** Set by `fail`, and only there: the cause of a run that ends `\"error\"`. */\n private failure: AgentRunFailure | undefined;\n private output: unknown;\n private stopReason: string | undefined;\n /**\n * The limit that stopped this run, when it was `maxRunDurationMs` rather\n * than `stop()` that did. Read by the abort path, which is shared: a run that\n * ran out of time is closed exactly like a stopped one, and only its finish\n * reason and its `error` differ.\n */\n private timedOutAfter: number | undefined;\n /** Clears the `maxRunDurationMs` timer. A no-op for a run without one. */\n private cancelDeadline: () => void = () => {};\n\n private readonly settled: Promise<AgentRunResult<ToolShapes, unknown>>;\n\n /**\n * Where this run sits in a tree of runs, all of it constant for the run.\n *\n * `signingRunId` is the *root's* id rather than this one's: the client only\n * ever sees the root run, so a question a sub-agent asks has to travel under\n * an id the client can hand back. `pathPrefix` is the chain of tool calls\n * above this run, and it is both what a pending call raised here is signed\n * over and what an answer coming back is matched against.\n */\n private readonly depth: number;\n private readonly maxDepth: number;\n private readonly chain: string[];\n private readonly signingRunId: string;\n private readonly pathPrefix: string[];\n private readonly onPending: \"escalate\" | \"deny\";\n /**\n * Sub-runs that have not yet written their transcript to the tool call.\n *\n * The abort path waits on these. A `stop()` reaches a sub-run through the\n * shared signal, so it is already closing — but `raceAbort` in `runTools`\n * returns the moment the signal fires, which would finalize and persist the\n * parent's message before the sub-run had recorded what it managed to do.\n * The work would be on the stream and missing from the store.\n */\n private readonly nestedSettling = new Set<Promise<unknown>>();\n /**\n * Messages for files a tool asked to show, held until its call settles, keyed\n * by tool call id. See `queueShown`.\n */\n private readonly shownQueue = new Map<string, AgentMessage[]>();\n\n constructor(config: RunConfig, params: AgentStreamParams) {\n this.config = config;\n this.params = params;\n // Cast because an app whose `AgentContext` has required fields makes `{}`\n // unassignable here — and such an app cannot reach this default, since\n // `ContextParam` makes it pass one.\n this.context = params.context ?? ({} as AgentContext);\n this.runId = params.runId ?? `run_${crypto.randomUUID()}`;\n this.history = [...params.messages];\n\n const nesting = params.nesting;\n this.depth = nesting?.depth ?? 0;\n this.maxDepth = nesting?.maxDepth ?? config.maxDepth;\n this.chain = nesting?.chain ?? [config.name];\n this.signingRunId = nesting?.signingRunId ?? this.runId;\n this.pathPrefix = nesting?.signingPath ?? [];\n this.onPending = nesting?.onPending ?? \"escalate\";\n\n if (params.signal) {\n if (params.signal.aborted) this.controller.abort();\n else params.signal.addEventListener(\"abort\", () => this.stop(), { once: true });\n }\n\n // The root's default, not a sub-run's: a sub-run shares its parent's\n // signal, so the parent's deadline already reaches it, and a default of its\n // own would cut short a parent that was deliberately given longer.\n const limit =\n config.maxRunDurationMs !== undefined\n ? config.maxRunDurationMs\n : nesting\n ? null\n : DEFAULT_MAX_RUN_DURATION_MS;\n this.cancelDeadline = startTimer(limit, () => this.expire(limit!));\n\n // Started here, not on first read. A run outlives the request that began\n // it, so nothing may depend on someone being attached — a client that\n // never reads still gets its tools run and its messages persisted.\n this.settled = this.execute();\n // And a request that started it stays open until it settles. A tool may\n // still read ambient request state — `Auth.user()`, a policied query — and\n // a client that leaves mid-run cancels the response body without stopping\n // the run; ending the request there would take the user away from step\n // four's tool call. Read ambiently rather than from a param because a run\n // need not come from a request at all: in a job or a script there is no\n // store, and nothing to hold open.\n RequestContext.getStore()?.waitUntil(this.settled);\n }\n\n // --- event plumbing ----------------------------------------------------\n\n private emit(event: AgentStreamEvent<ToolShapes, unknown>) {\n if (this.ended) return;\n this.buffer.push({ seq: ++this.seq, event });\n this.wake();\n }\n\n private wake() {\n const pending = [...this.waiters];\n this.waiters.clear();\n for (const resolve of pending) resolve();\n }\n\n private nextFrame(): Promise<void> {\n return new Promise<void>((resolve) => this.waiters.add(resolve));\n }\n\n /**\n * Replays from the buffer, then follows the run live.\n *\n * The whole run is buffered rather than a sliding window: a run is bounded by\n * `maxSteps`, and a client that reconnects two steps late wanting frame 42\n * must get frame 42 and not \"the oldest I still have\". Bounding it is the\n * live-run registry's job, where the policy question is how long a *finished*\n * run is kept.\n */\n async *frames(from = 0): AsyncIterable<AgentStreamFrame<ToolShapes, unknown>> {\n let index = from > 0 ? from - 1 : 0;\n for (;;) {\n while (index < this.buffer.length) {\n yield this.buffer[index++];\n }\n if (this.ended) return;\n await this.nextFrame();\n }\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<AgentStreamEvent<ToolShapes, unknown>> {\n for await (const frame of this.frames()) {\n yield frame.event;\n }\n }\n\n toResponse(params?: { from?: number }): Response {\n const frames = this.frames(params?.from);\n const encoder = new TextEncoder();\n let cancelled = false;\n\n let keepalive!: ReturnType<typeof sseKeepalive>;\n\n const body = new ReadableStream<Uint8Array>({\n start: async (controller) => {\n // A slow tool or a thinking sub-agent can leave the connection silent\n // for longer than a proxy's idle timeout, and a proxy that closes it\n // looks to the client exactly like a run that finished.\n keepalive = sseKeepalive(controller);\n try {\n for await (const frame of frames) {\n if (cancelled) break;\n // `id:` carries the cursor so a browser reconnecting with\n // `Last-Event-ID` is already asking the right question.\n controller.enqueue(\n encoder.encode(`id: ${frame.seq}\\ndata: ${JSON.stringify(frame.event)}\\n\\n`),\n );\n keepalive.touch();\n }\n } catch {\n // A stream that cannot be written to is a dead reader, not a dead\n // run. Nothing to report and nothing to stop.\n }\n keepalive.stop();\n try {\n controller.close();\n } catch {\n // already closed by a cancel\n }\n },\n cancel: () => {\n // Deliberately does not touch the run. A disconnect is a reader\n // leaving; `stop()` is the only thing that cancels work, because the\n // tool loop is here and a closed tab has not stopped step four from\n // charging a card.\n cancelled = true;\n keepalive.stop();\n },\n });\n\n return new Response(body, {\n headers: {\n \"Content-Type\": \"text/event-stream; charset=utf-8\",\n \"Cache-Control\": \"no-cache, no-transform\",\n Connection: \"keep-alive\",\n // Tells nginx not to buffer, which would otherwise hold every frame\n // until the response ended and make a stream look like a long pause.\n \"X-Accel-Buffering\": \"no\",\n },\n });\n }\n\n result(options?: AgentResultOptions): Promise<AgentRunResult<ToolShapes, unknown>> {\n if (!options?.throwOnError) return this.settled;\n return this.settled.then((result) => {\n if (result.error) throw new AgentRunError({ ...result, error: result.error });\n return result;\n });\n }\n\n stop(params?: { reason?: string }): void {\n if (this.ended || this.controller.signal.aborted) return;\n this.stopReason = params?.reason;\n this.controller.abort();\n }\n\n /**\n * `maxRunDurationMs` ran out. Stopped through the same controller as\n * `stop()`, so everything that already honours a stop (the provider request,\n * `raceAbort` around the tools, `ctx.signal`, sub-runs) honours this too.\n * The difference is only in how the run ends: see `finalizeAborted`.\n */\n private expire(limit: number): void {\n if (this.ended || this.controller.signal.aborted) return;\n this.timedOutAfter = limit;\n this.stopReason = `The run reached its time limit of ${formatDuration(limit)} and was stopped.`;\n this.controller.abort(new DOMException(this.stopReason, \"TimeoutError\"));\n }\n\n // --- the loop ----------------------------------------------------------\n\n private async execute(): Promise<AgentRunResult<ToolShapes, unknown>> {\n this.emit({ type: \"run-start\", runId: this.runId, threadId: this.params.threadId });\n\n try {\n // First, because everything after it reads a tool's schema: re-entering\n // a parked call below validates its input, and the model is shown them.\n const unresolved = await this.resolveToolSchemas();\n // A turn that answers a sub-agent's question re-enters the tool that\n // asked it, and that tool may ask again — so the run can be finished\n // before it has taken a single model step. Going on to `loop()` here\n // would step the model with a tool call still open, which is exactly the\n // history the provider rejects.\n const escalated = unresolved ? [] : await this.ingestTurn();\n if (unresolved) {\n this.fail(unresolved);\n this.finishReason = \"error\";\n } else if (escalated.length > 0) {\n this.finishReason = \"awaiting-input\";\n this.emit({ type: \"awaiting-input\", runId: this.runId, pending: escalated });\n } else {\n await this.loop();\n }\n } catch (error) {\n if (error instanceof RunAborted || this.controller.signal.aborted) {\n await this.finalizeAborted();\n } else {\n this.fail(this.config.provider.normalizeError(error), httpErrorDetail(error));\n await this.finalizeMessage(\"error\");\n this.finishReason = \"error\";\n }\n }\n this.cancelDeadline();\n\n this.emit({ type: \"usage\", usage: this.usage });\n this.emit({ type: \"run-end\", runId: this.runId, finishReason: this.finishReason });\n this.ended = true;\n this.wake();\n // After the turn, not in it: the run's usage is final, and the summary\n // is billed to the next run that uses it.\n this.precompact();\n\n const failure = this.finishReason === \"error\" ? this.failure : undefined;\n if (failure && this.config.logErrors) this.logFailure(failure);\n\n return {\n runId: this.runId,\n messages: this.produced as AgentMessage<ToolShapes, unknown>[],\n finishReason: this.finishReason,\n usage: this.usage,\n output: this.output,\n // Only when there is one, so a successful result has the same keys it\n // always had.\n ...(failure ? { error: failure } : {}),\n };\n }\n\n /**\n * Resolves the per-run input schemas (`ToolInputSchema`'s function form) and\n * swaps them into this run's registry and provider tool list. A no-op for\n * an agent whose tool schemas are all fixed, which is the common case.\n *\n * Returns the run's error when a resolver throws or returns a schema the\n * provider cannot take; the caller fails the run with it. Its message names\n * the tool and the cause — server-side only, since the client's copy is\n * redacted like any `tool_error`. The run fails before the turn is ingested,\n * so a client turn it carried is not reported to `onMessage`.\n */\n private async resolveToolSchemas(): Promise<AgentError | undefined> {\n const pending = [...this.config.registry.values()].filter((entry) => !entry.inputSchema);\n if (pending.length === 0) return undefined;\n const ctx: ToolSchemaContext = {\n context: this.context,\n body: this.params.body ?? {},\n runId: this.runId,\n threadId: this.params.threadId,\n signal: this.controller.signal,\n };\n const schemas = new Map<string, Schema<any>>();\n const failures = await Promise.all(\n pending.map(async (entry) => {\n try {\n const resolve = entry.tool.inputSchema as (\n ctx: ToolSchemaContext,\n ) => Schema<any> | Promise<Schema<any>>;\n const schema = await resolve(ctx);\n assertObjectRoot(schema, `The tool \"${entry.tool.name}\"`, \"inputSchema\");\n schemas.set(entry.tool.name, schema);\n return undefined;\n } catch (error) {\n return `\"${entry.tool.name}\": ${error instanceof Error ? error.message : String(error)}`;\n }\n }),\n );\n if (this.controller.signal.aborted) throw new RunAborted();\n const failed = failures.filter((failure) => failure !== undefined);\n if (failed.length > 0) {\n return {\n code: \"tool_error\",\n message: `Could not resolve the input schema of ${failed.join(\"; \")}`,\n retryable: false,\n };\n }\n\n const registry = new Map<string, ResolvedTool>();\n for (const [name, entry] of this.config.registry) {\n registry.set(name, schemas.has(name) ? { ...entry, inputSchema: schemas.get(name) } : entry);\n }\n const swap = (spec: ProviderToolSpec): ProviderToolSpec =>\n schemas.has(spec.name) ? toolSpec(registry.get(spec.name)!) : spec;\n const providerTools = this.config.providerTools.map((tool) =>\n \"tools\" in tool ? { ...tool, tools: tool.tools.map(swap) } : swap(tool),\n );\n this.config = { ...this.config, registry, providerTools };\n return undefined;\n }\n\n /**\n * Records why the run is failing and puts the client's copy on the stream.\n *\n * The two are built apart on purpose. `failure` is the server's record —\n * what `result().error` returns and what is logged — and carries the HTTP\n * status and request id of the provider's response, when there was one.\n * The frame gets the redacted copy (`redact`): the `AgentError` fields\n * only, named one by one so a field added to `AgentRunFailure` cannot reach\n * a browser by accident, and a message gemi did not write replaced (#446).\n */\n private fail(error: AgentError, detail: { status?: number; requestId?: string } = {}): void {\n const failure: AgentRunFailure = { ...error, ...detail };\n this.failure = failure;\n this.emit({ type: \"error\", error: this.redact(failure, { source: \"run\", failure }) });\n }\n\n /**\n * The one place an error is redacted for the client, through the app's\n * `redactError` or the default. The original is remembered against the\n * copy so the controller's `onError`, which hears the frame in this\n * process, still gets the full detail.\n */\n private redact(error: AgentError, info: Parameters<ErrorRedactor>[1]): AgentError {\n const redacted = applyRedaction(this.params.redactError, error, info, (err) =>\n this.writeLog(`[gemi/ai] agent \"${this.config.name}\" redactError threw`, { error: err }),\n );\n rememberUnredacted(redacted, error);\n return redacted;\n }\n\n /**\n * Through the app's logger, so it lands in `storage/logs` and `onLogCreated`.\n *\n * Outside an application — a script, a test, a run started before boot —\n * there is no logger to resolve, and `Log.error` throws on the lookup. That\n * case falls back to `console.error` rather than being dropped, since the\n * point of this is that a failed run is never silent. In development it goes\n * to the console as well, because `gemi dev` does not print the log file and\n * the terminal is where a developer is looking.\n */\n private logFailure(failure: AgentRunFailure): void {\n const message = `[gemi/ai] agent \"${this.config.name}\" run failed (${failure.code}${\n failure.status !== undefined ? ` ${failure.status}` : \"\"\n }): ${failure.message}`;\n this.writeLog(message, { error: failure });\n }\n\n /**\n * A tool that threw something other than a `ToolError`. The model and the\n * client are only told that it failed (see `redactError`), so this is the\n * one place its message and stack survive.\n */\n private logToolFailure(call: ToolCallPart, error: unknown): void {\n const text = error instanceof Error ? error.message : String(error);\n this.writeLog(\n `[gemi/ai] agent \"${this.config.name}\" tool \"${String(call.name)}\" threw: ${text}`,\n { toolCallId: call.toolCallId, error },\n );\n }\n\n private writeLog(message: string, extra: Record<string, unknown>): void {\n const metadata = {\n agent: this.config.name,\n runId: this.runId,\n ...(this.params.threadId ? { threadId: this.params.threadId } : {}),\n ...(this.depth > 0 ? { chain: this.chain } : {}),\n ...extra,\n };\n let logged = false;\n try {\n Log.error(message, metadata);\n logged = true;\n } catch {\n // No application to resolve a logger from. Reported below instead.\n }\n if (!logged || process.env.NODE_ENV === \"development\") {\n console.error(message, metadata);\n }\n }\n\n private async loop(): Promise<void> {\n const maxSteps = Math.max(1, this.config.maxSteps);\n\n for (let step = 1; step <= maxSteps; step++) {\n const message = this.startMessage();\n const outcome = await this.runStep(message, step);\n this.lastStep = { reason: outcome.reason, usage: message.usage };\n\n if (outcome.error) {\n this.fail(outcome.error, outcome.detail);\n await this.finalizeMessage(\"error\");\n this.finishReason = \"error\";\n return;\n }\n\n const calls = message.content.filter(\n (part): part is ToolCallPart => part.type === \"tool-call\",\n );\n\n if (calls.length === 0) {\n this.finishReason = outcome.reason;\n await this.finalizeMessage(outcome.reason);\n return;\n }\n\n const pending = await this.runTools(message, calls, step);\n\n if (pending.length > 0) {\n // The message closes first, then the run says what it is waiting for:\n // `awaiting-input` is terminal, and everything needed to answer it has\n // to already be on the stream when it arrives.\n this.finishReason = \"awaiting-input\";\n await this.finalizeMessage(\"awaiting-input\");\n this.emit({ type: \"awaiting-input\", runId: this.runId, pending });\n return;\n }\n\n if (step === maxSteps) {\n // Not an exception. An agent that will not stop calling tools is a bug\n // the app has to be able to see and show, and a throw here would put it\n // in a log instead of in the transcript.\n this.finishReason = \"max-steps\";\n await this.finalizeMessage(\"max-steps\");\n return;\n }\n\n await this.finalizeMessage(outcome.reason);\n }\n }\n\n private startMessage(): AgentMessage {\n const message: AgentMessage = {\n id: `msg_${crypto.randomUUID()}`,\n role: \"assistant\",\n content: [],\n createdAt: new Date().toISOString(),\n };\n this.current = message;\n this.history.push(message);\n this.produced.push(message);\n this.emit({ type: \"message-start\", messageId: message.id, role: \"assistant\" });\n return message;\n }\n\n private async finalizeMessage(reason: FinishReason): Promise<void> {\n const message = this.current;\n if (!message) return;\n this.current = null;\n // Read and cleared together: it describes the message being closed, and the\n // next one starts with no opinion.\n const outputTruncated = this.outputTruncated;\n this.outputTruncated = false;\n message.finishReason = reason;\n // On the message and not only on the frame. The frame reaches a live client,\n // which is half the audience: `onMessage` persists this object and\n // `result().messages` hands it back, and a transcript restored through\n // `useChat({ initialMessages })` has nothing else to read. `finishReason`\n // cannot answer it — a step that ran out of budget while calling a tool\n // closes `awaiting-input`, which is the case this exists for.\n if (outputTruncated) message.outputTruncated = true;\n // Before the message is handed to `onMessage` to be persisted and before it\n // reaches `result()` — the two places it stops being written and starts\n // being kept. Every exit lands here, aborted and errored runs included.\n for (const part of message.content) {\n if (part.type === \"text\" || part.type === \"reasoning\") {\n if (typeof part.text === \"string\") part.text = resolveRope(part.text);\n }\n }\n this.emit({\n type: \"message-end\",\n messageId: message.id,\n finishReason: reason,\n // Only when true, so the frame an ordinary message ends with is unchanged.\n ...(outputTruncated ? { outputTruncated: true as const } : {}),\n // The model call's usage for this message alone (#467). Absent when the\n // call never reported one — aborted mid-stream, or a provider that sent\n // no terminal frame — rather than a zero that reads as \"free\".\n ...(message.usage ? { usage: message.usage } : {}),\n });\n await this.report(message);\n // After it, never before: a file a tool showed during this message belongs\n // below the message whose tool call produced it, in the hook exactly as it\n // is in `result().messages` and on the stream. Empty on every step of a run\n // with no such file, which is most of them.\n await this.reportDeferred();\n }\n\n private async report(message: AgentMessage): Promise<void> {\n if (!this.params.onMessage) return;\n try {\n await this.params.onMessage(message);\n } catch {\n // Persistence failing must not take the transcript with it: the messages\n // are still on the stream and still in `result()`.\n }\n }\n\n // --- one model call ----------------------------------------------------\n\n private async runStep(message: AgentMessage, step: number): Promise<StepOutcome> {\n const signal = this.controller.signal;\n const provider = this.config.provider;\n\n const request = await this.prepareRequest(message, step);\n if (\"error\" in request) return { reason: \"error\", error: request.error };\n\n let outcome: StepOutcome = { reason: \"stop\" };\n const partialArgs = new Map<string, { name: string; args: string; namespace?: string }>();\n // Searches the model ran in this step, waiting for the call that follows\n // them. See `ToolCallPart.toolSearches` for why they are kept at all.\n let searches: ToolSearchRecord[] = [];\n const takeSearches = (): { toolSearches?: ToolSearchRecord[] } => {\n if (searches.length === 0) return {};\n const taken = searches;\n searches = [];\n return { toolSearches: taken };\n };\n let outputText = \"\";\n\n const stream = provider.stream({\n // Not `this.history` directly: an image a tool showed is in the history\n // forever and must not be in every *request* forever, and a long thread\n // is cut to the context window. See `prepareRequest`.\n messages: request.messages,\n systemPrompt: request.instructions,\n tools: this.config.providerTools.length > 0 ? this.config.providerTools : undefined,\n output: this.config.output ? outputFormat(this.config.output) : undefined,\n reasoning: this.config.reasoning,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n signal,\n });\n\n const iterator = stream[Symbol.asyncIterator]();\n for (;;) {\n const next = await raceAbort(Promise.resolve(iterator.next()), signal);\n if (next.done) break;\n const event = next.value;\n\n switch (event.type) {\n case \"text-delta\": {\n appendText(message, \"text\", event.delta);\n this.emit({ type: \"text-delta\", messageId: message.id, delta: event.delta });\n break;\n }\n case \"reasoning-delta\": {\n appendReasoning(message, event.id, event.delta);\n this.emit({\n type: \"reasoning-delta\",\n messageId: message.id,\n delta: event.delta,\n id: event.id,\n });\n break;\n }\n case \"output-delta\": {\n outputText += event.delta;\n this.emit({\n type: \"output-delta\",\n messageId: message.id,\n delta: event.delta,\n snapshot: bestEffortParse(outputText),\n });\n break;\n }\n case \"tool-search\": {\n searches.push({\n namespaces: event.namespaces,\n loaded: event.loaded,\n ...(event.arguments !== undefined ? { arguments: event.arguments } : {}),\n });\n this.emit({ type: \"tool-search\", loaded: event.loaded });\n break;\n }\n case \"tool-call-delta\": {\n const held: { name: string; args: string; namespace?: string } = partialArgs.get(\n event.toolCallId,\n ) ?? { name: event.name, args: \"\" };\n held.args += event.argsDelta;\n held.name = event.name || held.name;\n held.namespace = event.namespace || held.namespace;\n partialArgs.set(event.toolCallId, held);\n this.emit({\n type: \"tool-call\",\n messageId: message.id,\n part: {\n type: \"tool-call\",\n toolCallId: event.toolCallId,\n name: held.name,\n input: bestEffortParse(held.args),\n partial: true,\n ...(held.namespace ? { namespace: held.namespace } : {}),\n },\n });\n break;\n }\n case \"tool-call\": {\n const namespace = event.namespace || partialArgs.get(event.toolCallId)?.namespace;\n partialArgs.delete(event.toolCallId);\n const part: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: event.toolCallId,\n name: event.name,\n // A raw string when the model produced something that is not JSON.\n // Keeping it is what makes the `invalid_tool_input` result below\n // readable instead of an empty object nobody can explain.\n input: parseArgs(event.args),\n // Both are for the provider, which has to replay the call the way\n // the model made it (#776).\n ...(namespace ? { namespace } : {}),\n ...takeSearches(),\n };\n message.content.push(part);\n this.emit({ type: \"tool-call\", messageId: message.id, part });\n break;\n }\n case \"finish\": {\n this.usage = addUsage(this.usage, event.usage);\n // This step's own cost, on the message the step wrote (#467). The run\n // total above is the whole turn — every step plus tools' sub-runs,\n // `generate()` calls and images — and putting it on the last message\n // showed a three-step run's every token on step three. Added rather\n // than assigned in case a provider ever closes a call with more than\n // one finish frame.\n message.usage = addUsage(message.usage ?? emptyUsage(), event.usage);\n // The usage is taken either way, the reason only if nothing has\n // already failed. A provider is allowed to report an error and then\n // close the call with a finish frame — a content filter does exactly\n // that, and it still bills for the tokens — and letting the closing\n // frame overwrite the outcome would turn \"blocked\" into an empty\n // answer with no explanation anywhere.\n if (!outcome.error) outcome = { reason: event.reason };\n break;\n }\n case \"error\": {\n outcome = {\n reason: \"error\",\n error: event.error,\n detail: httpErrorDetail(event),\n };\n break;\n }\n case \"file-rejected\": {\n this.markFileRejected(event.fileId, event.message, httpErrorDetail(event));\n break;\n }\n }\n }\n\n // A tool call whose arguments never finished arriving. It is still a call\n // the model made, so it gets a part and, below, an `invalid_tool_input`\n // result — dropping it would leave the model unable to see what went wrong.\n for (const [toolCallId, held] of partialArgs) {\n const part: ToolCallPart = {\n type: \"tool-call\",\n toolCallId,\n name: held.name,\n input: parseArgs(held.args),\n ...(held.namespace ? { namespace: held.namespace } : {}),\n ...takeSearches(),\n };\n message.content.push(part);\n this.emit({ type: \"tool-call\", messageId: message.id, part });\n }\n\n // `length` is excluded, and it is the reason `maxOutputTokens` is worth\n // having at all. A cut-off answer is a prefix of the JSON the model meant\n // to write, and `bestEffortParse` closes whatever brackets are open — so a\n // truncated document arrives at `safeParse` looking like a whole one. For\n // a schema of `s.json()` fields it then *passes*, and the app is handed a\n // half-written page with nothing to distinguish it from a finished one.\n //\n // So a run that hit the ceiling produces no `output` part and ends with\n // `finishReason: \"length\"`, which is the channel for \"not an error, and not\n // a finished answer\" — the argument `max-steps` already makes in the\n // `FinishReason` type.\n //\n // No error is emitted, and that is a deliberate change rather than a\n // consequence of the cap. `length` does not mean the app set one: the\n // provider reports it from the model's own ceiling too, which is how this\n // was reachable before `maxOutputTokens` existed at all. Before this, a\n // truncated run fell through to `safeParse`, and a schema with required\n // keys among the missing ones failed it and raised a schema-mismatch error.\n // That diagnostic is gone on purpose — it described the truncation as a\n // model mistake, and it never fired for a schema loose enough to accept the\n // repaired prefix, which is the case that actually needed saying. What\n // replaces it is one answer for every schema: no output, and a finish\n // reason that says why.\n const truncated = outcome.reason === \"length\";\n // Recorded on the run rather than inferred from the message's finish reason,\n // which is not this: a step that hits the ceiling and also calls a tool ends\n // the message `awaiting-input` or `max-steps`. The client needs the fact\n // itself, or it completes a partial output the server withheld.\n if (truncated) this.outputTruncated = true;\n if (this.config.output && outputText && !outcome.error && !truncated) {\n const parsed = parseOutput(this.config.output, outputText);\n if (parsed.ok === true) {\n this.output = parsed.value;\n message.content.push({ type: \"output\", value: parsed.value });\n } else {\n this.emit({ type: \"error\", error: parsed.error });\n }\n }\n\n return outcome;\n }\n\n /**\n * What `contextWindow.compact` works from on this run, or `undefined` when\n * the run isn't compacted: compaction needs a stored thread (`threadId`) to\n * key summaries on, so stateless runs and sub-runs get the plain window.\n */\n private compactJobParams(\n history: AgentMessage[],\n current: AgentMessage | undefined,\n ): CompactJobParams | undefined {\n const window = this.config.contextWindow;\n if (!window?.compact || !this.params.threadId || this.depth !== 0) return undefined;\n const compact = window.compact === true ? {} : window.compact;\n return {\n history,\n stored: this.history.filter((message) => message !== current),\n window,\n compact,\n threadId: this.params.threadId,\n provider: this.config.provider,\n store: compact.store || this.params.summaryStore || defaultSummaryStore,\n };\n }\n\n /**\n * Starts the summary the thread's next turn will need, without waiting on\n * it (`ContextCompactOptions.background`). Never fails the run.\n */\n private precompact(): void {\n const window = this.config.contextWindow;\n if (!window?.compact || (window.compact !== true && window.compact.background === false)) {\n return;\n }\n try {\n const params = this.compactJobParams(this.historyForProvider(undefined), undefined);\n if (params) void precompactWindow(params);\n } catch {\n // Best effort: the next turn makes it inline.\n }\n }\n\n /**\n * What one model call is sent: the history as `historyForProvider` shapes\n * it, cut to `contextWindow`, then whatever the `prepareStep` hooks answer.\n *\n * Nothing here touches `this.history`. The hooks are handed copies of the\n * arrays, and what they answer is used for this call only, so the next step\n * starts from the whole history again and the store is never told about a\n * window.\n */\n private async prepareRequest(\n current: AgentMessage,\n step: number,\n ): Promise<{ messages: AgentMessage[]; instructions: string | undefined } | { error: AgentError }> {\n const history = this.historyForProvider(current);\n const window = this.config.contextWindow;\n const compact = this.compactJobParams(history, current);\n let messages = !window\n ? history\n : compact\n ? await compactWindow({\n ...compact,\n signal: this.controller.signal,\n // Billed whether or not the summary came out, as `ctx.generate` is.\n onUsage: (usage) => {\n this.usage = addUsage(this.usage, usage);\n },\n memo: this.compactMemo,\n })\n : windowMessages(history, window).messages;\n let instructions = await this.systemPrompt();\n\n for (const hook of this.config.prepareStep) {\n let answer: PrepareStepResult | void;\n try {\n answer = await hook({\n step,\n messages: [...messages],\n history: [...history],\n instructions,\n usage: this.usage,\n ...(this.lastStep?.usage ? { lastStepUsage: this.lastStep.usage } : {}),\n ...(this.lastStep ? { lastFinishReason: this.lastStep.reason } : {}),\n runId: this.runId,\n threadId: this.params.threadId,\n agent: this.config.name,\n depth: this.depth,\n context: this.context,\n signal: this.controller.signal,\n });\n } catch (error) {\n if (error instanceof RunAborted || this.controller.signal.aborted) throw error;\n const text = error instanceof Error ? error.message : String(error);\n return {\n error: { code: \"unknown\", message: `prepareStep threw: ${text}`, retryable: false },\n };\n }\n if (!answer) continue;\n if (answer.messages !== undefined) {\n if (!Array.isArray(answer.messages)) {\n return {\n error: {\n code: \"unknown\",\n message: \"prepareStep answered `messages` that is not an array.\",\n retryable: false,\n },\n };\n }\n messages = answer.messages;\n }\n if (answer.instructions !== undefined) instructions = answer.instructions || undefined;\n }\n\n return { messages, instructions };\n }\n\n private async systemPrompt(): Promise<string | undefined> {\n const parts = [this.config.instructions, this.params.instructions].filter(\n (part): part is string => Boolean(part && part.trim()),\n );\n return parts.length > 0 ? parts.join(\"\\n\\n\") : undefined;\n }\n\n // --- tools -------------------------------------------------------------\n\n private async runTools(\n message: AgentMessage,\n calls: ToolCallPart[],\n step: number,\n ): Promise<PendingToolCall[]> {\n const pending: PendingToolCall[] = [];\n const running: Promise<void>[] = [];\n\n for (const call of calls) {\n const resolved = this.config.registry.get(String(call.name));\n\n if (!resolved) {\n this.addResult(message, {\n type: \"tool-result\",\n toolCallId: call.toolCallId,\n name: call.name,\n status: \"error\",\n error: {\n code: \"tool_error\",\n message: `There is no tool named \"${String(call.name)}\".`,\n toolCallId: call.toolCallId,\n retryable: true,\n },\n });\n continue;\n }\n\n const parsed = resolved.inputSchema!.safeParse(call.input);\n if (parsed.ok === false) {\n // Back to the model, not up the stack. A model that mis-typed one\n // argument can usually fix it on the next step, and throwing turns a\n // recoverable mistake into a dead run.\n this.addResult(message, {\n type: \"tool-result\",\n toolCallId: call.toolCallId,\n name: call.name,\n status: \"error\",\n error: {\n code: \"invalid_tool_input\",\n message: `Invalid arguments for \"${String(call.name)}\": ${parsed.errors.join(\", \")}`,\n toolCallId: call.toolCallId,\n retryable: true,\n },\n });\n continue;\n }\n\n // The parsed value replaces the raw arguments on the part, and from here\n // on it is the only input this call has.\n //\n // A schema normalizes — it fills defaults, coerces, and drops the `null`s\n // that strict mode forces a model to send for an omitted optional. So\n // `safeParse(input)` and `input` are different values, and a pending call\n // has to be signed over, shown as, verified against and executed with the\n // *same* one. Keeping the raw value in the transcript and signing the\n // parsed one meant the MACs could not match on the way back: every\n // approval of a tool with an optional field came back looking forged, and\n // the user who clicked Approve was told they had refused.\n //\n // Writing it here rather than re-parsing on the way back also avoids\n // assuming `safeParse` is idempotent — the history now carries the value\n // the signature covers, so verification is a comparison and not a second\n // guess at what the first parse produced.\n call.input = parsed.value;\n\n const kind = pendingKind(resolved.tool);\n if (kind) {\n if (this.onPending === \"deny\") {\n this.addResult(message, this.deniedByPolicy(call));\n continue;\n }\n pending.push({\n toolCallId: call.toolCallId,\n name: call.name,\n input: parsed.value,\n kind,\n signature: signPendingCall(\n this.claimsFor(call.toolCallId, String(call.name), kind, parsed.value),\n ),\n ...(this.pathPrefix.length > 0 ? { path: [...this.pathPrefix] } : {}),\n });\n continue;\n }\n\n running.push(\n this.executeTool(resolved, message.id, call, parsed.value, step)\n .then(async (result) => {\n this.addResult(message, result);\n // The call has settled. Anything it asked to show goes into the\n // history now, after its own result — which is the order the\n // provider validates and the order it happened in.\n await this.settleShown(call.toolCallId);\n })\n .catch((error) => {\n if (error instanceof PendingEscalation) {\n if (this.onPending === \"deny\") {\n this.addResult(message, this.deniedByPolicy(call));\n return;\n }\n // Collected exactly like a pending call this run made itself, and\n // deliberately without a result on `call`: the tool did not\n // finish, so its call stays open and the next turn re-enters it.\n // Siblings are untouched — `Promise.all` below still waits for\n // them, and one that completes keeps its result rather than being\n // thrown away because a different tool asked a question.\n pending.push(...error.pending);\n return;\n }\n // Only `RunAborted` reaches here, and the abort path denies every\n // unresolved call at once — swallowing it keeps a stopped run from\n // also raising an unhandled rejection.\n }),\n );\n }\n\n await raceAbort(\n Promise.all(running).then(() => undefined),\n this.controller.signal,\n );\n return pending;\n }\n\n /**\n * What a pending call is signed over.\n *\n * `signingRunId` is the root run's, not this one's: the client only ever sees\n * the root, so a sub-agent's question has to be minted under an id the client\n * can hand back and this run can still recognise on the way in.\n */\n private claimsFor(\n toolCallId: string,\n name: string,\n kind: \"approval\" | \"question\" | \"client\",\n input: unknown,\n ) {\n return {\n runId: this.signingRunId,\n toolCallId,\n name,\n kind,\n input,\n // Absent rather than empty at the top level, so the signature a root run\n // mints is byte-for-byte the one it minted before nesting existed.\n path: this.pathPrefix.length > 0 ? [...this.pathPrefix] : undefined,\n // The principal the question is asked of (#447): an answer presented by\n // anyone else fails the MAC.\n subject: this.params.subject ?? null,\n };\n }\n\n /**\n * The refusal a sub-run running under `onPending: \"deny\"` gives itself.\n *\n * Told to the model rather than dropped, like every other denial: the\n * sub-agent asked for something it cannot have here, and the next step goes\n * better for knowing that than for finding a hole where a result should be.\n */\n private deniedByPolicy(call: ToolCallPart): ToolResultPart {\n return {\n type: \"tool-result\",\n toolCallId: call.toolCallId,\n name: call.name,\n status: \"denied\",\n cause: \"refused\",\n reason: `\"${String(call.name)}\" needs the user, and this run was started with onPending: \"deny\". Answer from what you already have.`,\n };\n }\n\n private async executeTool(\n resolved: ResolvedTool,\n messageId: string,\n call: ToolCallPart,\n input: unknown,\n step: number,\n resume?: { answers: ClientToolResult[] },\n ): Promise<ToolResultPart> {\n const timeoutMs = resolved.tool.timeoutMs;\n if (timeoutMs === undefined) {\n return this.runToolBody(\n resolved,\n messageId,\n call,\n input,\n step,\n resume,\n this.controller.signal,\n () => false,\n );\n }\n\n // The call's own signal: the run's, plus this call's `timeoutMs`. Everything\n // the call starts is handed this one rather than the run's, so a timeout\n // cancels its image calls and sub-runs too, and the run's stop still\n // reaches them through it. The forwarding is never removed, so a stop\n // reaches whatever the call left running after it answered, exactly as it\n // does with the run's own signal.\n const callController = new AbortController();\n const runSignal = this.controller.signal;\n const forwardStop = () => callController.abort(runSignal.reason);\n if (runSignal.aborted) forwardStop();\n else runSignal.addEventListener(\"abort\", forwardStop, { once: true });\n\n // Set once the call has answered, by either route. Whatever the body yields\n // after that belongs to a call the model has already been told about, and\n // must not reach the stream.\n let answered = false;\n const body = this.runToolBody(\n resolved,\n messageId,\n call,\n input,\n step,\n resume,\n callController.signal,\n () => answered,\n );\n\n let cancelTimer = () => {};\n const timedOut = new Promise<ToolResultPart>((resolve) => {\n cancelTimer = startTimer(timeoutMs, () => {\n const message = `\"${String(call.name)}\" did not finish within ${formatDuration(timeoutMs)} (timeoutMs: ${timeoutMs}) and was cancelled.`;\n callController.abort(new DOMException(message, \"TimeoutError\"));\n resolve({\n type: \"tool-result\",\n toolCallId: call.toolCallId,\n name: call.name,\n status: \"error\",\n error: { code: \"timeout\", message, toolCallId: call.toolCallId, retryable: true },\n });\n });\n });\n // A body that settles after the timeout has nobody to tell. Its rejection\n // (an `AbortError` from honouring the signal, usually) is swallowed here\n // rather than surfacing as an unhandled one.\n body.catch(() => {});\n try {\n return await Promise.race([body, timedOut]);\n } finally {\n answered = true;\n cancelTimer();\n }\n }\n\n /** One call of a server tool, from `execute` to the result the model sees. */\n private async runToolBody(\n resolved: ResolvedTool,\n messageId: string,\n call: ToolCallPart,\n input: unknown,\n step: number,\n resume: { answers: ClientToolResult[] } | undefined,\n signal: AbortSignal,\n answered: () => boolean,\n ): Promise<ToolResultPart> {\n // One object, because the three of them share a memo — see `toolFiles`.\n const files = this.toolFiles(call, signal);\n const ctx: ToolContext = {\n context: this.context,\n // `{}` rather than undefined, so a tool can read a field without a guard\n // and get the same answer — absent — whether the client sent nothing or\n // the run was started without a body at all.\n body: this.params.body ?? {},\n runId: this.runId,\n threadId: this.params.threadId,\n toolCallId: call.toolCallId,\n signal,\n step,\n depth: this.depth,\n resumed: resume !== undefined,\n attachments: files.attachments,\n generateImage: files.generateImage,\n editImage: files.editImage,\n turn: this.toolTurn(messageId),\n runAgent: this.nestedRunner(messageId, call, signal, resume),\n generate: ((params: GenerateParams) =>\n this.generateForTool(params, signal, call.toolCallId)) as ToolContext[\"generate\"],\n jobs: toolJobs({\n jobs: this.depth === 0 ? this.params.jobs : undefined,\n threadId: this.params.threadId,\n runId: this.runId,\n toolCallId: call.toolCallId,\n toolName: String(call.name),\n depth: this.depth,\n async: resolved.tool.async,\n attachments: this.params.attachments ?? null,\n }),\n };\n\n try {\n const started = resolved.tool.execute!(input as any, ctx);\n let output: unknown;\n if (isAsyncGenerator(started)) {\n let next = await started.next();\n while (!next.done) {\n if (answered()) {\n // Timed out. Closed rather than drained: nothing it yields from\n // here can be shown, and a generator that is still being pulled\n // is one that keeps working.\n void started.return(undefined as never).catch(() => {});\n throw new RunAborted();\n }\n this.emit({ type: \"tool-progress\", toolCallId: call.toolCallId, data: next.value });\n next = await started.next();\n }\n output = next.value;\n } else {\n output = await started;\n }\n if (isJobHandle(output)) {\n // The call went to the background (#461). Its result is `running`,\n // and the job's own outcome replaces it once it settles.\n if (output.toolCallId !== call.toolCallId) {\n throw new ToolError(\n `\"${String(call.name)}\" returned the handle of a job another tool call started. Return the handle from this call's own ctx.jobs.`,\n { retryable: false },\n );\n }\n return {\n type: \"tool-result\",\n toolCallId: call.toolCallId,\n name: call.name,\n status: \"running\",\n job: {\n id: output.id,\n ...(output.summary !== undefined ? { summary: output.summary } : {}),\n },\n };\n }\n return {\n type: \"tool-result\",\n toolCallId: call.toolCallId,\n name: call.name,\n status: \"ok\",\n output,\n };\n } catch (error) {\n if (error instanceof RunAborted || this.controller.signal.aborted) {\n // Left to the abort path, which denies every unresolved call at once.\n throw new RunAborted();\n }\n if (error instanceof PendingEscalation) {\n // The one throw that is not a failure. Turning it into a `tool_error`\n // here would tell the model the tool broke and tell the user nothing,\n // and the question the sub-agent asked would be lost with no trace of\n // where it went — which is precisely the silent failure this branch\n // exists to prevent.\n throw error;\n }\n // A throwing tool is a result, not an exception out of the run: the model\n // is told the call failed and can try something else, which is what a\n // person would do. What it is told is redacted (#446): the same part goes\n // to the model, to the client and into the store, and an exception's\n // message is whatever the code under the tool said, connection strings\n // and internal hostnames included. A `ToolError` is the tool saying its\n // message is meant to be read; anything else is logged in full here.\n const deliberate = error instanceof ToolError;\n if (!deliberate && this.config.logErrors) this.logToolFailure(call, error);\n const raw: AgentError = {\n code: \"tool_error\",\n message: error instanceof Error ? error.message : String(error),\n toolCallId: call.toolCallId,\n retryable: deliberate ? error.retryable : true,\n };\n return {\n type: \"tool-result\",\n toolCallId: call.toolCallId,\n name: call.name,\n status: \"error\",\n error: this.redact(raw, { source: \"tool\", toolName: String(call.name), cause: error }),\n };\n }\n }\n\n /**\n * `ctx.generate`. See `ToolContext.generate` for why the binding matters.\n *\n * The usage is added before the abort check on purpose: a call cut short by\n * `stop()` may still have been billed for what it produced, and the turn's\n * total is the one place an app reads what the turn cost.\n */\n private async generateForTool(\n params: GenerateParams,\n callSignal: AbortSignal,\n toolCallId: string,\n ): Promise<GenerateResult<unknown>> {\n // `callSignal` is the tool call's `ctx.signal`: it aborts on a stop, at the\n // run's deadline, and at the tool's own `timeoutMs`. Only the first two\n // abort the turn (`controller.signal`), and only those throw below.\n const turn = this.controller.signal;\n return generateWithin(\n {\n ...params,\n signal: params.signal ? AbortSignal.any([callSignal, params.signal]) : callSignal,\n },\n {\n origin: {\n agent: this.config.name,\n runId: this.runId,\n ...(this.params.threadId ? { threadId: this.params.threadId } : {}),\n toolCallId,\n },\n // Before the failure is logged or thrown: the usage was billed either\n // way, and a stopped turn throws `RunAborted` rather than a\n // `throwOnError` rejection the tool might catch and carry on from.\n settled: (result) => {\n this.usage = addUsage(this.usage, result.usage);\n if (turn.aborted) throw new RunAborted();\n },\n },\n );\n }\n\n // --- nested runs -------------------------------------------------------\n\n /**\n * The `ctx.runAgent` given to one tool call, with its own memo.\n *\n * MEMOIZATION IS BY CALL INDEX, and the index is the only key there is. A\n * paused async generator cannot be put into a message history, so an\n * escalating tool is re-entered from the top rather than resumed in place,\n * and the Nth `runAgent` of the re-entered body has to be paired with the Nth\n * sub-run of the previous attempt. `ToolCallPart.nested` is that record, which\n * is also why it lives on the message: it is exactly the history the next turn\n * loads anyway, from the store or from the client.\n *\n * A tool whose `runAgent` calls sit inside a branch or a loop can produce a\n * different sequence on replay, and then index N means two different things.\n * That is checked below rather than trusted — pairing a user's answer with the\n * wrong sub-run is the failure this whole mechanism exists to avoid, and it\n * would be invisible.\n */\n private nestedRunner(\n messageId: string,\n call: ToolCallPart,\n signal: AbortSignal,\n resume?: { answers: ClientToolResult[] },\n ): ToolContext[\"runAgent\"] {\n // Snapshotted before the tool body runs, and lazily created on first use.\n // Both rules, and the reasoning behind them, are on `ReplayMemo` — which\n // `ctx.attachments.put` shares, so that the two memos on one tool call\n // cannot drift apart in how they decide what is a replay.\n const memo = new ReplayMemo<NestedRun>(\n () => call.nested,\n () => (call.nested = []),\n );\n\n return async (agent: AnyAgent, params: RunAgentParams = {}): Promise<NestedRunResult> => {\n const { at, recorded, write } = memo.next();\n\n if (recorded) {\n const mismatch = replayMismatch(recorded, agent, params);\n if (mismatch) {\n throw new ToolError(\n `Nested run ${at} of \"${String(call.name)}\" ${mismatch}. ` +\n `runAgent is memoized by call index, so a body whose runAgent calls depend on a condition that changed between turns cannot be resumed — the answer would be paired with a different sub-run. ` +\n `Make the sequence of runAgent calls, and what each one is asked, the same every time this tool runs, or branch on ctx.resumed.`,\n );\n }\n if (recorded.finishReason !== \"awaiting-input\") {\n // The whole point of the memo: no provider is called, no sub-tool\n // runs, and no usage is counted a second time — this turn did not\n // spend it, an earlier one did.\n return {\n runId: recorded.runId,\n agent: recorded.agent,\n messages: recorded.messages,\n finishReason: recorded.finishReason ?? \"stop\",\n usage: recorded.usage ?? emptyUsage(),\n output: outputOf(recorded.messages),\n nested: recorded,\n };\n }\n }\n\n return this.runNested(\n messageId,\n call,\n signal,\n agent,\n params,\n write,\n recorded,\n resume?.answers ?? [],\n );\n };\n }\n\n /**\n * Starts, or continues, one sub-run and joins it to this one.\n *\n * Joining is the only reason this exists — a tool can already make an agent\n * and iterate it. What it cannot do by hand is put the sub-run's events on\n * this run's stream in this run's `seq`, roll its usage up, record its\n * transcript where the next turn will look for it, and carry the depth and\n * the name chain so a cycle is a sentence rather than a stack overflow.\n */\n private async runNested(\n messageId: string,\n call: ToolCallPart,\n signal: AbortSignal,\n agent: AnyAgent,\n params: RunAgentParams,\n write: (record: NestedRun) => void,\n recorded: NestedRun | undefined,\n answers: ClientToolResult[],\n ): Promise<NestedRunResult> {\n // Both checks before anything starts, so the failure is a tool result the\n // model can read rather than a partly-run tree. The name chain catches the\n // common cycle (A runs A, A runs B runs A) exactly; the depth limit catches\n // the shapes a name cannot see, such as the same agent under two names.\n const chain = [...this.chain, agent.name];\n if (this.chain.includes(agent.name)) {\n throw new ToolError(\n `\"${agent.name}\" is already running further up this chain: ${chain.join(\" -> \")}. An agent cannot run itself, directly or through another agent.`,\n );\n }\n const depth = this.depth + 1;\n if (depth > this.maxDepth) {\n throw new ToolError(\n `Nested agent runs are ${this.maxDepth} deep at most and this one would be ${depth}: ${chain.join(\" -> \")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`,\n );\n }\n\n const label = params.label;\n const signingPath = [...this.pathPrefix, call.toolCallId];\n // Inherited downwards and never relaxed: a caller that asked for an\n // autonomous sub-agent must not have a question surface from two levels\n // below it, and only the subtree refusing can promise that.\n const onPending = this.onPending === \"deny\" ? \"deny\" : (params.onPending ?? \"escalate\");\n\n const resuming = recorded !== undefined;\n const open = resuming ? openCallIds(recorded.messages) : new Set<string>();\n // Only the answers this sub-run can actually attach to a call of its own,\n // or route further down. Handing it the rest would make it report a result\n // for a call nobody made.\n const mine = resuming\n ? answers.filter((answer) => {\n const below = pathBelow(answer.path, signingPath);\n if (below === null) return false;\n return open.has(below.length > 0 ? below[0] : answer.toolCallId);\n })\n : [];\n\n const sub = agent.stream({\n // A resume starts from what was persisted, not from what the tool passed\n // this time: the body ran again from the top and rebuilt its `prompt`,\n // and honouring it would replay a first turn the sub-agent has already\n // had. The persisted transcript already contains it.\n messages: resuming ? recorded.messages : (params.messages ?? []),\n turn: resuming ? { toolResults: mine } : params.prompt ? { text: params.prompt } : undefined,\n // The same caller, so the same context. See `ToolContext.context`.\n context: this.context,\n // The same scope, down the whole tree. A sub-agent runs on behalf of the\n // caller who started the parent — that is the only reason it is allowed\n // to run at all — so it reads and writes the caller's attachments, and a\n // tool three levels down can be handed an id its parent parked. There is\n // nothing to widen here and nothing to narrow: a second scope would be a\n // second answer to a question the request already answered once.\n attachments: this.params.attachments,\n // Inherited for the same reason the scope above is: a sub-agent is part\n // of the turn its parent is serving, so the fields the client sent with\n // that turn are as much its context as the parent's. A generator run\n // through `runAgent` whose tools could not see `pageId` would have to be\n // passed it through the prompt, as text, for the model to copy back.\n body: this.params.body,\n // Inherited, not new: this is what makes the parent's `stop()` reach a\n // sub-run three levels down without anything in between forwarding it.\n // The call's signal rather than the run's: it is the run's plus the\n // tool's own `timeoutMs`, so a tool that times out takes its sub-runs\n // with it instead of leaving them to finish for nobody.\n signal,\n threadId: this.params.threadId,\n // The same caller is reading, so the same rules for what it is told.\n redactError: this.params.redactError,\n // The same store, so a sub-run's answers are single-use across every\n // instance exactly as the parent's are.\n nonces: this.params.nonces,\n // And the same receipts, so a sub-agent's approved tool runs once too.\n receipts: this.params.receipts,\n // The same principal, so a sub-agent's question is bound to the user the\n // root run was started for.\n subject: this.params.subject,\n instructions: params.instructions,\n maxOutputTokens: params.maxOutputTokens,\n temperature: params.temperature,\n // Kept across turns so the transcript the client already has keeps its\n // identity when the run continues.\n runId: resuming ? recorded.runId : undefined,\n nesting: {\n depth,\n maxDepth: this.maxDepth,\n chain,\n signingRunId: this.signingRunId,\n signingPath,\n onPending,\n },\n }) as AgentRun;\n\n let asked: PendingToolCall[] = [];\n const forward = (event: AgentStreamEvent) =>\n this.emit({\n type: \"nested-event\",\n toolCallId: call.toolCallId,\n runId: sub.runId,\n agent: agent.name,\n label,\n event,\n });\n const forwarding: Promise<void> = (async () => {\n for await (const event of sub as AsyncIterable<AgentStreamEvent>) {\n if (event.type === \"awaiting-input\") asked = event.pending;\n forward(event);\n if (event.type === \"run-start\" && !resuming) {\n // The seed, streamed (#470). It is recorded below as the head of the\n // transcript, but the sub-run never emits it — a run streams only the\n // messages it makes — so a client building the transcript from these\n // frames had none of it, while one that loaded the record (or got the\n // re-sent `tool-call`) did, and the two rendered different\n // conversations. Whole `message` frames, because the seed is finished\n // before the sub-run starts. A `prompt` is the sub-run's own turn and\n // is emitted by the sub-run itself (`ingestTurn`). A resume emits\n // nothing here: the record it continues already holds the seed.\n for (const message of params.messages ?? []) forward({ type: \"message\", message });\n }\n if (event.type === \"error\") {\n // Re-raised on the parent's own stream (#468). Wrapped in a\n // `nested-event` it reaches nobody: the client reduces it into a\n // throwaway sub-state, and the controller's hooks only hear\n // top-level frames, so `useChat.error`, `onError` and the\n // controller's `onError` never heard that a sub-agent failed. The\n // same object, not a copy: it was redacted by the sub-run already,\n // and the controller's `onError` finds the unredacted original by\n // identity. Not terminal — the tool decides what the failure means.\n this.emit({\n type: \"error\",\n error: event.error,\n nested: { toolCallId: call.toolCallId, runId: sub.runId, agent: agent.name },\n });\n }\n }\n })();\n\n // Recording is its own promise so that the abort path can wait for exactly\n // this — the transcript reaching the tool call — rather than for the whole\n // tool, which may be ignoring the signal.\n const recording = (async () => {\n const result = await sub.result();\n await forwarding;\n // The seed leads, because a run only reports the messages it *made* and\n // `params.messages` is not one of them. Recording the transcript without\n // its opening is two bugs: a resume re-enters the sub-agent with the\n // conversation it was started from missing, and the replay check below\n // has nothing to fingerprint the seed against. Upserted rather than\n // concatenated because the sub-run may have amended one of these on its\n // way through.\n const messages = resuming\n ? mergeMessages(recorded.messages, result.messages)\n : mergeMessages(params.messages ?? [], result.messages);\n const record: NestedRun = {\n runId: sub.runId,\n agent: agent.name,\n label,\n messages,\n finishReason: result.finishReason,\n usage: resuming ? addUsage(recorded.usage ?? emptyUsage(), result.usage) : result.usage,\n // A parked record is what the next turn re-enters the tool on, and in\n // stateless mode it comes back from the browser. Signed here, by the\n // run that knows it is true, over where the sub-run parked, what it is\n // waiting on and the input the tool was running with — `parkedBelow`\n // will not act on a record without it. `call.input` is the parsed\n // value by now, on every path that reaches here, so the transcript\n // carries exactly what was signed.\n ...(result.finishReason === \"awaiting-input\"\n ? {\n signature: signNestedRun({\n runId: this.signingRunId,\n path: signingPath,\n nestedRunId: sub.runId,\n open: [...openCallIds(messages)],\n input: call.input,\n subject: this.params.subject ?? null,\n }),\n }\n : {}),\n };\n // Written before anything below can throw. An escalation is a pause, not\n // a lost run, and a cancelled sub-run is still work the user should be\n // able to read — both of those depend on the transcript already being on\n // the part when the throw happens.\n write(record);\n // Only what this turn actually spent. A memoized sub-run adds nothing,\n // above, because the turn that ran it already counted it.\n this.usage = addUsage(this.usage, result.usage);\n return { result, record };\n })();\n\n const settling = recording.then(\n () => undefined,\n () => undefined,\n );\n this.nestedSettling.add(settling);\n let result: AgentRunResult<ToolShapes, unknown>;\n let record: NestedRun;\n try {\n ({ result, record } = await recording);\n } finally {\n this.nestedSettling.delete(settling);\n }\n\n if (this.controller.signal.aborted) {\n // The sub-run was cancelled by the parent's `stop()`. Failing the tool\n // rather than returning an aborted result is what stops the tool body\n // from carrying on with half an answer while the run around it is dying.\n throw new RunAborted();\n }\n\n if (result.finishReason === \"awaiting-input\") {\n if (asked.length === 0) {\n // Nothing to ask means nothing the client could answer, and escalating\n // an empty list would end the parent awaiting-input with a tool call\n // that can never be resolved.\n throw new ToolError(\n `\"${agent.name}\" ended awaiting input but asked nothing, so there is no question to escalate.`,\n );\n }\n // The signature is on the server's copy of the record, and a stateless\n // client has built its own from the forwarded events. Re-sending the\n // call is what puts the server's copy in the client's hands to carry\n // back: the reducer takes a re-sent `nested` as authoritative, so this\n // replaces what the client accumulated rather than adding to it. Marked\n // `resent` because it is not a call: the model made this one earlier —\n // in this run or, on a re-park, in a previous one — and a hook that\n // counts calls has already seen it.\n this.emit({ type: \"tool-call\", messageId, part: call, resent: true });\n throw new PendingEscalation({ pending: asked, path: signingPath, nested: record });\n }\n\n return {\n runId: record.runId,\n agent: agent.name,\n messages: record.messages,\n finishReason: result.finishReason,\n usage: record.usage ?? emptyUsage(),\n output: result.output ?? outputOf(record.messages),\n ...(result.error ? { error: result.error } : {}),\n nested: record,\n };\n }\n\n private addResult(message: AgentMessage, part: ToolResultPart) {\n message.content.push(part);\n this.emit({ type: \"tool-result\", messageId: message.id, part });\n }\n\n // --- files a tool made -------------------------------------------------\n\n /**\n * The `ctx.attachments` given to one tool call.\n *\n * Built per call rather than per run for one reason, and it is the same\n * reason `runAgent` is: the memo. A `put` has to be recognisable on the next\n * turn as the same `put`, and the only address a re-entered body has is \"the\n * Nth attachment of this tool call\" — so the object that counts them has to\n * belong to the call, not to the run.\n */\n /**\n * The file half of a tool's context: `ctx.attachments`, `ctx.generateImage`\n * and `ctx.editImage`.\n *\n * BUILT TOGETHER BECAUSE THEY SHARE ONE MEMO, and sharing it is not an\n * optimization. `ToolCallPart.attachments` is a list indexed by the order the\n * puts happened in, and a generated image *is* a put — so two `ReplayMemo`s\n * over the same list would each start at zero and hand out the same slots,\n * and a tool that both stored a file and generated one would replay the wrong\n * record for each. One list, one cursor.\n */\n private toolFiles(\n call: ToolCallPart,\n signal: AbortSignal,\n ): {\n attachments: ToolAttachments;\n generateImage: ToolContext[\"generateImage\"];\n editImage: ToolContext[\"editImage\"];\n } {\n const scoped = this.params.attachments ?? null;\n const memo = new ReplayMemo<ToolAttachmentRecord>(\n () => call.attachments,\n () => (call.attachments = []),\n // A put that threw took an index and wrote nothing, and if a later put in\n // the same call succeeds the gap has to be something rather than a hole:\n // `[null, { attachment }]` is what a hole becomes on the wire and in the\n // store, and it is what a UI or an app walking the memo crashes on. The\n // slot is re-attempted on a replay — `put` treats a failed record as no\n // record — so a transient failure heals itself on the turn the call\n // finally settles, and a permanent one stays legible as \"this put did not\n // produce a file\" instead of pretending it produced nothing at all.\n () => ({ failed: true }),\n );\n\n /**\n * The scope, or a sentence saying why there isn't one.\n *\n * A request with no subject gets no attachments at all — that is #489's\n * rule and this is where a tool meets it. The throw lands in `executeTool`,\n * which turns it into a `tool_error` the model reads, so the model is told\n * the tool cannot store files rather than being told nothing while the tool\n * quietly answers an id for bytes nobody kept. The message names the hook\n * an app has to override, because the reader who can act on it is the\n * developer looking at the transcript, not the model.\n */\n const scopeOrThrow = (): ScopedAttachments => {\n if (!scoped) {\n throw new InvalidAttachmentScopeError(\n \"This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null — put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.\",\n );\n }\n return scoped;\n };\n\n /**\n * Everything a filled slot needs, with nothing of the memo in it.\n *\n * Shared by `put` and by the two image calls, which differ only in where the\n * bytes came from and in whether a `generated` record rides along. The\n * upload-then-store ordering, the `fileInput` refusal and the minted message\n * id are one copy for all three.\n */\n const park = async (\n blob: Blob,\n params: PutAttachmentParams,\n generated?: ToolAttachmentPut[\"generated\"],\n ): Promise<ToolAttachmentPut> => {\n const attachments = scopeOrThrow();\n const mimeType = params.mimeType || blob.type || \"\";\n // A name is settled here rather than left to `ScopedAttachments.put`,\n // which falls back to the attachment id. The provider's upload wants a\n // filename, the injected `FilePart` carries one, and the stored record\n // has one — three copies that have to agree, so there is one value.\n const name = params.name ?? (blob instanceof File ? blob.name : \"attachment\");\n\n let fileId: string | undefined;\n if (params.showModel) {\n const provider = this.config.provider;\n if (!provider.capabilities.fileInput) {\n // Refused before a byte moves. `toResponsesInput` drops a file part\n // for a provider that cannot read one, so without this the tool\n // pays for an upload, stores a record claiming the model was shown\n // the file, and the model answers about an image that never reached\n // the wire — with nothing in the transcript, the logs or the bill\n // saying which of those three things went wrong.\n throw new ToolError(\n `\"${String(call.name)}\" asked to show a file to ${provider.model}, which does not accept file input. Drop \\`showModel\\` for this provider, or run this agent on a model that takes files — \\`capabilities.fileInput\\` is what says which do.`,\n );\n }\n // The provider first, storage second — the opposite of `upload`'s\n // order in `AgentController`, deliberately.\n //\n // That route stores first because either failure fails the request\n // and the only question is whose orphan it becomes. Here there is a\n // second question and it decides: the record this writes claims\n // `destination: \"both\"`, and a record cannot claim the vendor has a\n // copy before the vendor says so. Uploading first also means a file\n // the vendor refuses — a type it will not take, a size over its cap —\n // costs no storage write at all, and `showModel` is exactly the path\n // where that refusal is likeliest. The orphan when storage fails\n // afterwards is a file at the vendor with no record here, which is\n // the same orphan `AgentController.upload` accepts in the other\n // direction.\n fileId = await provider.upload(new File([blob], name, { type: mimeType || undefined }));\n }\n\n const attachment = await attachments.put(blob, { name, mimeType, fileId });\n return {\n attachment,\n ...(generated ? { generated } : {}),\n ...(fileId\n ? {\n shown: {\n fileId,\n // Minted here and written down, not derived later. The next\n // turn replays this record and has to produce the same\n // message — same id, same timestamp — or a reattached client\n // and a live one hold two copies of one image.\n messageId: `msg_${crypto.randomUUID()}`,\n createdAt: new Date().toISOString(),\n },\n }\n : {}),\n };\n };\n\n /**\n * A slot that was filled by a different call than the one asking for it now.\n *\n * The sequence of file calls inside a tool body is the memo's only key, so a\n * body that stored a file on the first attempt and generates one at the same\n * index on the replay has changed in a way nothing can reconcile — and the\n * failure without this check is silent and expensive: `generateImage` would\n * hand back an attachment nobody rendered, or `put` would return the id of a\n * generated image in place of the bytes it was given.\n */\n const assertKind = (recorded: ToolAttachmentPut, wanted: \"put\" | \"image\", at: number) => {\n const was = recorded.generated ? \"image\" : \"put\";\n if (was === wanted) return;\n throw new ToolError(\n `Attachment ${at} of \"${String(call.name)}\" was ${was === \"image\" ? \"a generated image\" : \"a stored file\"} on the first attempt and is ${wanted === \"image\" ? \"a generated image\" : \"a stored file\"} now. ` +\n `ctx.attachments.put, ctx.generateImage and ctx.editImage share one memo indexed by call order within a tool call, so the sequence has to be the same every time this tool runs. Branch on ctx.resumed if it cannot be.`,\n );\n };\n\n const runImage = async (\n model: ImageModel,\n params: ToolGenerateImageParams,\n render: () => Promise<GeneratedImage>,\n ): Promise<GeneratedAttachment> => {\n const { at, recorded, write } = memo.next();\n\n // Read BEFORE the render, which is the whole point of memoizing this\n // rather than letting it fall through to `ctx.attachments.put`. `put`\n // checks its memo when it is called, and by then the image has been\n // rendered and paid for — its own docblock says so: \"Work before a `put`\n // still runs again.\" Here the expensive part is the work before.\n if (recorded && \"attachment\" in recorded) {\n assertKind(recorded, \"image\", at);\n if (recorded.shown) this.queueShown(call.toolCallId, recorded);\n return {\n attachment: recorded.attachment,\n size: recorded.generated!.size,\n mimeType: recorded.attachment.mimeType,\n usage: recorded.generated!.usage,\n };\n }\n\n const image = await render();\n // Counted against the run exactly as a nested agent's is, so\n // `AgentRunResult.usage` is the whole cost of the turn and not only its\n // text. `imageInputTokens` keeps the image share legible inside it.\n this.usage = addUsage(this.usage, image.usage);\n\n const extension = image.mimeType === \"image/jpeg\" ? \"jpg\" : \"png\";\n const record = await park(\n image.image,\n {\n name: params.name ?? `${model.name}.${extension}`,\n mimeType: image.mimeType,\n ...(params.showModel ? { showModel: true } : {}),\n },\n { size: image.size, usage: image.usage },\n );\n\n write(record);\n if (record.shown) this.queueShown(call.toolCallId, record);\n return {\n attachment: record.attachment,\n size: image.size,\n mimeType: image.mimeType,\n usage: image.usage,\n };\n };\n\n /** An attachment id resolves through the scope; bytes pass through. */\n const asInput = async (input: ImageInput | string): Promise<ImageInput> =>\n typeof input === \"string\" ? await scopeOrThrow().file(input) : input;\n\n return {\n generateImage: (model, params) =>\n runImage(model, params, () => model.generate({ ...params, signal })),\n\n editImage: (model, params) =>\n runImage(model, params, async () => {\n // `images` and `mask` are peeled off rather than spread over: both\n // may be attachment ids here and neither is one by the time it\n // reaches `ImageModel`, so letting the originals through would type\n // as `string | Blob` and ship an id where bytes belong.\n const { images, mask, ...rest } = params;\n return await model.edit({\n ...rest,\n images: (await Promise.all(images.map(asInput))) as [ImageInput, ...ImageInput[]],\n ...(mask ? { mask: await asInput(mask) } : {}),\n signal,\n });\n }),\n\n attachments: {\n get: (id: string) => scopeOrThrow().get(id),\n read: (id: string) => scopeOrThrow().read(id),\n file: (id: string) => scopeOrThrow().file(id),\n put: async (blob: Blob, params: PutAttachmentParams = {}): Promise<Attachment> => {\n const { at, recorded, write } = memo.next();\n\n // A `failed` record is a slot an earlier turn took and could not fill,\n // so there is nothing to replay and the work is done again.\n if (recorded && \"attachment\" in recorded) {\n assertKind(recorded, \"put\", at);\n const mismatch = putMismatch(recorded, blob, params);\n if (mismatch) {\n throw new ToolError(\n `Attachment ${at} of \"${String(call.name)}\" ${mismatch}. ` +\n `ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed — the model would be shown a file under an id that names different bytes. ` +\n `Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.`,\n );\n }\n // Nothing is stored and nothing is uploaded. What IS repeated is the\n // queueing: the first attempt escalated before its result attached,\n // so the message was queued and never flushed, and this turn is the\n // one where the call finally settles. `settleShown` refuses a message\n // id the history already holds, which is what makes queueing twice\n // safe rather than merely unlikely.\n if (recorded.shown) this.queueShown(call.toolCallId, recorded);\n return recorded.attachment;\n }\n\n const record = await park(blob, params);\n // The slot is filled only now, with everything that could throw behind\n // it: a put that fails leaves the tool call exactly as it found it.\n write(record);\n if (record.shown) this.queueShown(call.toolCallId, record);\n return record.attachment;\n },\n },\n };\n }\n\n /**\n * The `ctx.turn` given to one tool call. The reasoning is on `ToolTurn`.\n *\n * Anchored on `messageId`, the assistant message holding the call, which is\n * the same id on a re-entry: `amend` replaces the history entry with a clone\n * under the original's id, so the lookup is by id rather than by reference.\n * A message that is not in the history at all gets an empty list rather than\n * a guess.\n */\n private toolTurn(messageId: string): ToolTurn {\n const at = this.history.findIndex((message) => message.id === messageId);\n const injected = injectedMessageIds(this.history);\n let user: AgentMessage | undefined;\n for (let i = at - 1; i >= 0; i--) {\n const message = this.history[i];\n if (message.role !== \"user\" || injected.has(message.id)) continue;\n user = message;\n break;\n }\n const ids: string[] = [];\n for (const part of user?.content ?? []) {\n if (part.type !== \"file\") continue;\n // The prefix test `providers/request.ts` applies before telling the model\n // an id. A stateless client's history can put anything here, and a value\n // the model was never shown as an id should not reach a tool as one.\n const id = part.attachmentId;\n if (typeof id !== \"string\" || !id.startsWith(ATTACHMENT_ID_PREFIX)) continue;\n if (!ids.includes(id)) ids.push(id);\n }\n return Object.freeze({ attachments: Object.freeze(ids) });\n }\n\n /**\n * Holds the message for a shown file until its tool call settles.\n *\n * WHY IT WAITS. The message is input-role and it has to sit *after* the tool\n * call's result, because that is the order it happened in and the order the\n * provider validates: a `function_call` and its `function_call_output` are a\n * pair, and a user message wedged between them is a history the API rejects.\n * Emitting it the moment `put` returns would do exactly that, since the tool\n * is still running.\n *\n * WHY A TOOL THAT ESCALATED GETS NOTHING. Its call has no result yet, so\n * flushing would leave an image in the transcript attached to a call that has\n * not finished — and the next turn re-enters the body, replays the `put` and\n * would queue a second copy. The queue simply dies with the run; the record\n * on the tool call survives, and the turn that finally settles the call is\n * the turn that shows the file.\n */\n private queueShown(toolCallId: string, record: ToolAttachmentPut) {\n const shown = record.shown;\n if (!shown) return;\n const queued = this.shownQueue.get(toolCallId) ?? [];\n if (queued.some((message) => message.id === shown.messageId)) return;\n queued.push({\n id: shown.messageId,\n role: \"user\",\n content: [\n {\n type: \"file\",\n fileId: shown.fileId,\n name: record.attachment.name,\n mimeType: record.attachment.mimeType,\n // Shown to the model beside the file (see `attachmentLine` in\n // `providers/request.ts`), so a file one tool made can be the input\n // of the next. Not what marks the part as injected — a user's upload\n // carries one too; `historyForProvider` keys on the message id.\n attachmentId: record.attachment.id,\n },\n ],\n createdAt: shown.createdAt,\n // Complete the instant it is made. Without this the client's `run-end`\n // safety net would find a message with no finish reason and stamp one on,\n // which is a difference between a live client and a reattached one over a\n // message that was never streaming in the first place.\n finishReason: \"stop\",\n });\n this.shownQueue.set(toolCallId, queued);\n }\n\n /**\n * The tool call settled: its files go into the transcript now.\n *\n * Pushed to `history` (so the next step sees them), to `produced` (so\n * `result().messages` carries them and the controller persists them), emitted\n * (so a client watching live sees the same conversation a reattached one\n * replays), and queued for `onMessage` (so an app that persists from the hook\n * stores it). A message that is in some of those four and not the others is\n * the bug class #470 is about, and an injected message is the easiest place in\n * the codebase to write it.\n *\n * QUEUED FOR THE HOOK RATHER THAN REPORTED HERE, so that all four agree on\n * ORDER and not merely on contents. The assistant message that made this tool\n * call has not been finalized yet — `loop` does that after `runTools`\n * returns — so calling `onMessage` from here would hand an app the file\n * before the turn that produced it. `reportDeferred` is where the queue is\n * drained, immediately after that assistant message is reported.\n *\n * The id guard is for a history that already holds the message — a stateless\n * client posting back a transcript that contains the injection *and* still\n * shows the call as open, which is a rewind the server cannot rule out. One\n * copy either way.\n *\n * NOTHING IS SHOWN ONCE THE RUN IS OVER, and the check belongs here rather than\n * at the three call sites because one of those sites fires after the run has\n * finished. `finalizeAborted` never calls this — it denies every open call\n * instead — but a `/stop` does not wait for a tool that is already running:\n * `raceAbort` in `runTools` returns the moment the signal fires, the run\n * finalizes and ends, and the tool's own `.then` lands afterwards and calls\n * this. Without the guard the message goes into `history` and `produced` and\n * through `onMessage` while `emit` is already a no-op, so it is persisted and\n * never announced, and a client that reloads the thread sees an image a client\n * that watched it live never saw. That is the exact divergence this issue\n * asked to avoid, arrived at from the one direction nobody looks. Appending an\n * image to a conversation the user has just cancelled would also be the run\n * getting the last word. The bytes are kept and the record is on the tool\n * call, so a tool that runs again can still resolve the id; nothing is lost\n * but the showing.\n */\n private async settleShown(toolCallId: string): Promise<void> {\n const queued = this.shownQueue.get(toolCallId);\n if (!queued || queued.length === 0) return;\n this.shownQueue.delete(toolCallId);\n if (this.ended || this.controller.signal.aborted) return;\n for (const message of queued) {\n if (this.history.some((held) => held.id === message.id)) continue;\n this.history.push(message);\n this.produced.push(message);\n this.emit({ type: \"message\", message });\n this.unreported.add(message);\n }\n }\n\n /**\n * The history as the provider sees it: everything, minus all but the most\n * recent tool-produced file.\n *\n * THE PROBLEM. `buildResponsesRequest` is handed the whole history on every\n * step, so a file injected at step two is re-sent at steps three, four and\n * five. An edit loop that iterates three times therefore pays for three\n * images on every later call — image tokens are not small, and they are\n * charged again each step — on top of one provider upload per iteration. Left\n * alone this is a cost that grows with the square of the loop and shows up on\n * an invoice rather than in a stack trace.\n *\n * WHAT IS TRIMMED, AND WHERE. Here, on the way to the provider, and nowhere\n * else. The transcript keeps every injected message: `history`, `produced`,\n * `onMessage`, the stream, and the client all hold the same conversation they\n * would have held without this method, so a `/attach` replay still matches a\n * live stream and a user scrolling back still sees every version the agent\n * made. Trimming the stored transcript instead would have meant editing a\n * message after it was persisted and announced, which is the one thing the\n * message contract does not allow.\n *\n * WHAT IT COSTS, AND IT IS A REAL CAPABILITY. With a window of one, the model\n * cannot compare this iteration against the last one. \"Is this closer than\n * the previous attempt?\" is a question it can no longer answer from what it\n * can see, and an agent whose job is to converge on a target by comparison\n * genuinely wants two. One is the default because the failure of too small a\n * window is visible and cheap — the model says it cannot see the earlier\n * image, in the transcript, on the first run — while the failure of too large\n * a one is a bill nobody reads until the end of the month. The dropped part\n * is replaced by a line of text rather than removed, so the model is told the\n * image existed and why it is gone; a hole would leave it to conclude it had\n * imagined seeing anything.\n *\n * IT IS A CONSTANT, NOT A KNOB, ON PURPOSE. A configurable window is one line\n * to add later and cannot be taken back once apps depend on it, and nobody\n * has a second value to name yet. Only files the run injected are counted —\n * a file the *user* attached is one they expect to stay attached, and\n * dropping it would be the agent losing the thing it was asked about.\n */\n private historyForProvider(current: AgentMessage | undefined): AgentMessage[] {\n const messages = this.history.filter((message) => message !== current);\n\n // Injected messages are named by the tool call that made them, and that\n // record is the test — not `attachmentId` on the part. A user's own upload\n // carries an `attachmentId` too: `ingestTurn` copies it from `turn.files`,\n // and `useChat` spreads the entry onto its local user message.\n const injected = injectedMessageIds(messages);\n\n const shown: FilePart[] = [];\n for (const message of messages) {\n if (!injected.has(message.id)) continue;\n for (const part of message.content) {\n if (part.type === \"file\") shown.push(part);\n }\n }\n if (shown.length <= SHOWN_FILE_WINDOW) return messages;\n\n const dropped = new Set(shown.slice(0, shown.length - SHOWN_FILE_WINDOW));\n return messages.map((message) => {\n if (!message.content.some((part) => part.type === \"file\" && dropped.has(part))) {\n return message;\n }\n return {\n ...message,\n content: message.content.map((part) =>\n part.type === \"file\" && dropped.has(part)\n ? {\n type: \"text\" as const,\n text: `[A ${part.mimeType || \"file\"} produced by a tool (attachment ${part.attachmentId}) was attached here and has been dropped from this request: only the most recent tool-produced file is kept attached, to keep the context bounded. Call the tool again if you need to look at it.]`,\n }\n : part,\n ),\n };\n });\n }\n\n // --- the client's turn -------------------------------------------------\n\n /**\n * Resolves what the client sent back, then adds its words.\n *\n * Every pending call has to come out of this with a result — signed, refused\n * or implicitly denied. The provider rejects a history holding a tool call\n * with no result, so leaving one open would break not this turn but the next\n * one, at a point where the cause is no longer visible.\n */\n private async ingestTurn(): Promise<PendingToolCall[]> {\n const turn = this.params.turn;\n const open = this.openCalls();\n /** Questions a re-entered tool asked again. The run ends on these. */\n const escalated: PendingToolCall[] = [];\n\n if (open.length > 0) {\n const answered = new Set<string>();\n const seen = new Set<string>();\n /** Answers addressed *below* one of this run's tool calls, grouped by the\n * call that has to be re-entered to deliver them. */\n const reentry = new Map<string, ClientToolResult[]>();\n\n for (const answer of turn?.toolResults ?? []) {\n // One answer per call, first one wins. A turn carrying the same entry\n // twice is a retried submit or a double-clicked form, and without this\n // it ran the approved tool twice and left two results for one\n // toolCallId — a history the provider rejects, arrived at by exactly\n // the machinery that exists to keep the history well formed.\n //\n // Keyed by path *and* id, because a tool-call id is only unique within\n // one run: two sub-agents under two different tools each number their\n // calls from their own provider, and dropping the second as a duplicate\n // would strand the tool that was waiting on it. For a top-level answer\n // the key is the id, exactly as before.\n const key = `${(answer.path ?? []).join(\"/\")}#${answer.toolCallId}`;\n if (seen.has(key)) continue;\n seen.add(key);\n\n const reject = (message: string) =>\n this.emit({\n type: \"error\",\n error: {\n code: \"invalid_tool_result\",\n message,\n toolCallId: answer.toolCallId,\n retryable: false,\n },\n });\n\n // The path says which run the answer belongs to; `toolCallId` only says\n // which call *within* that run. Both are covered by the signature, so a\n // client that moves an answer to another tool's sub-run does not\n // redirect anything — it routes the answer somewhere the MAC no longer\n // verifies, which is the property that makes carrying the path safe.\n const below = pathBelow(answer.path, this.pathPrefix);\n if (below === null) {\n reject(\n `The answer for \"${answer.toolCallId}\" is addressed to a tool call this run is not inside.`,\n );\n continue;\n }\n\n if (below.length > 0) {\n const host = below[0];\n const hosting = open.find((entry) => entry.call.toolCallId === host);\n if (!hosting) {\n reject(`No pending tool call with id \"${host}\" to deliver a nested answer to.`);\n continue;\n }\n // THE ONE CHECK THAT MAKES RE-ENTRY SAFE, and the reason it is here\n // rather than in `reenter`.\n //\n // Re-entry runs the tool. Everything else in this method verifies a\n // signature first, but a path cannot be verified here — the claims\n // are the *inner* call's, and only the run that minted them knows its\n // tool, its `kind` and its input, which is why `resolveAnswer` runs\n // down there and not up here. So the decision to execute has to be\n // gated on something the server derived instead: there must be a\n // sub-run parked on this exact call, and it must be waiting on the\n // exact question the answer names. Without this, a turn that posts\n // `{ path: [<any open call>], signature: \"\" }` re-enters a tool that\n // is merely awaiting an *approval* — running, unapproved, a call the\n // user was shown and never said yes to, with its input taken from a\n // client-carried history. Content is still checked below, in the\n // sub-run; this is what stops an unsigned request from choosing to\n // execute at all.\n const parked = this.parkedBelow(hosting.call, below, answer.toolCallId);\n if (parked.ok === false) {\n const under = `The answer for \"${answer.toolCallId}\" is addressed under \"${host}\", which`;\n reject(\n parked.reason === \"unparked\"\n ? `${under} has no sub-agent run waiting on that question.`\n : parked.reason === \"expired\"\n ? `${under} parked a sub-agent run that has since expired. Ask again.`\n : `${under} carries a record of a parked sub-agent run the server did not sign.`,\n );\n continue;\n }\n let group = reentry.get(host);\n if (!group) {\n // Spent here, ahead of the body, for the reason the record is\n // signed at all: re-entry runs the tool before the sub-run gets to\n // refuse a spent answer, so a history rewound to before the result\n // would run it once per replay. Once per record per turn — the\n // sub-run may have asked two things at once, and every answer to\n // it re-enters the same tool a single time.\n if (!(await this.spend(spendNestedRun, parked.signature))) {\n reject(\n `The answer for \"${answer.toolCallId}\" is addressed under \"${host}\", which has already been re-entered on that record. Ask again.`,\n );\n continue;\n }\n group = [];\n reentry.set(host, group);\n // Marked answered so the refusal pass below leaves it alone: the\n // tool is about to be re-entered and will produce the real result.\n answered.add(host);\n }\n group.push(answer);\n continue;\n }\n\n const target = open.find((entry) => entry.call.toolCallId === answer.toolCallId);\n if (!target) {\n // Nothing to attach it to, so it cannot be told to the model even as\n // an error part — a result for a call that was never made.\n reject(`No pending tool call with id \"${answer.toolCallId}\".`);\n continue;\n }\n\n const result = await this.resolveAnswer(target, answer, escalated);\n if (result === null) continue;\n answered.add(answer.toolCallId);\n // `\"open\"` is an approved tool whose own sub-agent asked something on\n // the way through: answered, so the refusal pass leaves it alone, but\n // no result attaches — the call stays open and the next turn re-enters\n // it, exactly as an escalation from the step loop does. Nothing it\n // showed is flushed either, for the same reason: the call has not\n // settled, so the file waits for the turn where it does.\n if (result !== \"open\") {\n this.attachToHistory(target, result);\n await this.settleShown(answer.toolCallId);\n }\n }\n\n for (const [host, answers] of reentry) {\n const entry = open.find((item) => item.call.toolCallId === host)!;\n const result = await this.reenter(entry, answers, escalated);\n if (result) {\n this.attachToHistory(entry, result);\n // The turn a re-entered tool finally settles on is the turn its files\n // are shown, however many turns ago it stored them.\n await this.settleShown(host);\n }\n }\n\n for (const entry of open) {\n if (answered.has(entry.call.toolCallId)) continue;\n // The turn said something else. That is a refusal — the honest reading,\n // and the only one that cannot strand the thread. A tool whose\n // sub-agent asked a question and did not get an answer is refused here\n // like any other: the sub-run is abandoned with its transcript intact,\n // and the call gets a result rather than dangling into the next turn.\n this.attachToHistory(entry, {\n type: \"tool-result\",\n toolCallId: entry.call.toolCallId,\n name: entry.call.name,\n status: \"denied\",\n cause: \"refused\",\n });\n }\n\n await this.reportDeferred();\n }\n\n if (turn && (turn.text || (turn.files && turn.files.length > 0))) {\n const message: AgentMessage = {\n id: `msg_${crypto.randomUUID()}`,\n role: \"user\",\n content: [\n ...(turn.text ? [{ type: \"text\" as const, text: turn.text }] : []),\n // Field by field rather than spread: an entry can carry whatever\n // `attach()` answered (`downgraded`, `size`), and only these four\n // mean anything on a `FilePart`. `attachmentId` is among them — it is\n // what lets the model name this file to a tool — and an absent\n // `fileId` is a storage-only upload, left out rather than written as\n // `undefined`.\n ...(turn.files ?? []).map((file) => ({\n type: \"file\" as const,\n ...(file.fileId ? { fileId: file.fileId } : {}),\n name: file.name,\n mimeType: file.mimeType,\n ...(file.attachmentId ? { attachmentId: file.attachmentId } : {}),\n })),\n ],\n createdAt: new Date().toISOString(),\n finishReason: \"stop\",\n };\n this.history.push(message);\n this.produced.push(message);\n // A sub-run's turn was written by the tool that started it, not typed by\n // the client watching, so nothing on the stream would ever tell that\n // client it exists (#470). A top-level turn is not echoed: the client\n // sent it and already has it. What it does not have is this id, so it is\n // told that alone, keyed by the id it gave its own copy (#466). The\n // message rides along for any other client watching the run (#778): a\n // tab that attached to it never held the copy, and the reducer appends\n // it only there.\n if (this.depth > 0) this.emit({ type: \"message\", message });\n else if (turn.localId) {\n this.emit({ type: \"message-id\", localId: turn.localId, messageId: message.id, message });\n }\n await this.report(message);\n // After `report`, so a caller that persists from `onMessage` has queued\n // the message before it hears that this is the turn (#806).\n if (this.params.onTurn) {\n try {\n await this.params.onTurn(message);\n } catch {\n // As `report`: the turn is still on the stream and in `result()`.\n }\n }\n }\n\n return escalated;\n }\n\n /**\n * Whether a sub-run under `call` is actually parked on the question named.\n *\n * The transcript is the server's own record of where the run stopped:\n * `nested` is written from the sub-run's result before the escalation throws,\n * so a call that has never nested has no `nested` at all, and one whose\n * sub-runs all finished has none with `awaiting-input`. In stateless mode\n * that record arrives from the client and could say anything, and what\n * saying it buys is not small: the tool body runs — from the top, with the\n * input the history carries — before the sub-run gets to verify the answer,\n * so everything the body does ahead of its first `runAgent` happens on the\n * client's say-so. Which is why the record has to carry the server's\n * signature over the sub-run it parked, the calls it left open and the\n * input the tool was given, and why a record without one, or with one that\n * does not match what it now says, is not a parked run at all.\n *\n * The failure says which of those it was. \"Expired\" is an ordinary outcome\n * in threaded mode — a question answered a day late — and telling that\n * user the run never parked would send them looking for a bug that is not\n * there; a record that fails its MAC is the other thing entirely, and the\n * two are kept apart for the same reason `resolveAnswer` keeps them apart.\n *\n * `below` is the answer's path with this run's prefix already removed, so\n * `below[0]` is `call` itself and `below[1]`, when there is one, names the\n * call to re-enter one level further down.\n */\n private parkedBelow(\n call: ToolCallPart,\n below: string[],\n toolCallId: string,\n ): { ok: true; signature: string } | { ok: false; reason: \"unparked\" | \"unsigned\" | \"expired\" } {\n const wanted = below.length > 1 ? below[1] : toolCallId;\n const path = [...this.pathPrefix, call.toolCallId];\n const parked = (call.nested ?? []).find(\n (run) => run.finishReason === \"awaiting-input\" && openCallIds(run.messages).has(wanted),\n );\n if (!parked) return { ok: false, reason: \"unparked\" };\n if (typeof parked.signature !== \"string\") return { ok: false, reason: \"unsigned\" };\n const verified = verifyNestedRun(parked.signature, {\n path,\n nestedRunId: parked.runId,\n open: [...openCallIds(parked.messages)],\n input: call.input,\n subject: this.params.subject ?? null,\n });\n if (verified.ok === false) {\n return { ok: false, reason: verified.reason === \"expired\" ? \"expired\" : \"unsigned\" };\n }\n return { ok: true, signature: parked.signature };\n }\n\n /**\n * Re-enters a tool whose sub-agent asked the user something.\n *\n * From the top, with `ctx.resumed === true` — there is no other way. A JS\n * async generator cannot be suspended across a turn boundary, so the body\n * runs again and `runAgent` replays its finished sub-runs out of\n * `ToolCallPart.nested` instead of re-running them. Which means the code\n * *before* the escalating `runAgent` runs twice; that bargain is documented on\n * `ToolContext.runAgent` and it is the price of not needing a checkpoint API.\n */\n private async reenter(\n entry: { message: AgentMessage; call: ToolCallPart },\n answers: ClientToolResult[],\n escalated: PendingToolCall[],\n ): Promise<ToolResultPart | null> {\n const name = String(entry.call.name);\n const resolved = this.config.registry.get(name);\n if (!resolved || !resolved.tool.execute) {\n return {\n type: \"tool-result\",\n toolCallId: entry.call.toolCallId,\n name: entry.call.name,\n status: \"error\",\n error: {\n code: \"invalid_tool_result\",\n message: `The tool \"${name}\" no longer exists, so the sub-agent's question cannot be delivered.`,\n toolCallId: entry.call.toolCallId,\n retryable: false,\n },\n };\n }\n\n // Checked the way `runTools` checked the model's arguments. The record's\n // signature has already said this is the input the tool parked on, so what\n // this catches is the tool itself having moved: a schema that changed\n // between the turn that parked and the turn that answers. The tool's typed\n // input is a contract with the tool as it is now, and a value the schema\n // rejects must not reach it — the failure is a result the model can read,\n // exactly like a mis-typed argument on the way in.\n const parsed = resolved.inputSchema!.safeParse(entry.call.input);\n if (parsed.ok === false) {\n return {\n type: \"tool-result\",\n toolCallId: entry.call.toolCallId,\n name: entry.call.name,\n status: \"error\",\n error: {\n code: \"invalid_tool_input\",\n message: `Invalid arguments for \"${name}\": ${parsed.errors.join(\", \")}`,\n toolCallId: entry.call.toolCallId,\n retryable: true,\n },\n };\n }\n\n const call = this.amendCall(entry);\n // The parsed value is the only input the call has from here on, as in\n // `runTools` — the clone carries what the tool was actually given.\n call.input = parsed.value;\n try {\n // Step 0, like an approval executed on the way in: this belongs to the\n // turn, not to a step of the loop that has not started yet.\n return await raceAbort(\n this.executeTool(resolved, entry.message.id, call, parsed.value, 0, { answers }),\n this.controller.signal,\n );\n } catch (error) {\n if (error instanceof PendingEscalation) {\n // Asked again. No result attaches, so the call stays open and the next\n // turn re-enters it exactly as this one did.\n escalated.push(...error.pending);\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Clones the tool-call part before a replay writes to its `nested`.\n *\n * The message holding it came from an earlier run and belongs to the caller's\n * `messages` array; the run must not reach back into its own input and change\n * it under a controller that has already persisted it. Cloning the part into\n * the amended copy is also what makes the updated sub-run transcript\n * something `onMessage` can report — see `reportDeferred`, which is why the\n * message is marked unreported here even though no result may ever attach.\n */\n private amendCall(entry: { message: AgentMessage; call: ToolCallPart }): ToolCallPart {\n const message = this.amend(entry.message);\n const at = message.content.indexOf(entry.call);\n const call: ToolCallPart = {\n ...entry.call,\n nested: (entry.call.nested ?? []).map((run) => ({ ...run })),\n // Cloned for the same reason `nested` is: the replayed body's memo writes\n // into this array, and the array on the original part belongs to the\n // caller's `messages`, which is an input and not scratch space.\n ...(entry.call.attachments\n ? { attachments: entry.call.attachments.map((record) => ({ ...record })) }\n : {}),\n };\n if (at >= 0) message.content[at] = call;\n this.unreported.add(message);\n return call;\n }\n\n /** Tool calls in the history with no result anywhere after them. */\n private openCalls(): { message: AgentMessage; call: ToolCallPart }[] {\n const resolvedIds = new Set<string>();\n for (const message of this.history) {\n for (const part of message.content) {\n if (part.type === \"tool-result\") resolvedIds.add(part.toolCallId);\n }\n }\n const open: { message: AgentMessage; call: ToolCallPart }[] = [];\n for (const message of this.history) {\n for (const part of message.content) {\n if (part.type === \"tool-call\" && !resolvedIds.has(part.toolCallId)) {\n open.push({ message, call: part });\n }\n }\n }\n return open;\n }\n\n /**\n * Verifies one answer and turns it into a result part, or reports why not.\n *\n * `null` means the call stays unanswered and falls through to the implicit\n * denial above — which is the right outcome for a bad signature: the model\n * must not see a result the server cannot vouch for. `\"open\"` means the\n * opposite: the answer was good, the tool ran, and it is now waiting on a\n * question of its own, so the call must stay open *without* being denied.\n */\n /**\n * Spends a token's nonce in the run's `NonceStore`. A store that throws (its\n * Redis is down, say) is logged and counted as spent: the answer is refused\n * and the user asked again, rather than acted on unchecked.\n */\n private async spend(\n spendIn: (signature: string, store: NonceStore) => Promise<boolean>,\n signature: string,\n ): Promise<boolean> {\n try {\n return await spendIn(signature, this.params.nonces ?? defaultNonceStore);\n } catch (error) {\n this.writeLog(`[gemi/ai] agent \"${this.config.name}\" could not spend a nonce`, { error });\n return false;\n }\n }\n\n /**\n * Records an approved tool's result on its receipt once it is known (#458),\n * and only then hands it on, so a presentation that arrives after this run\n * answered finds it. Chained to the execution rather than to the run's race,\n * so a tool that finishes after a `stop()` still records what it did.\n *\n * A tool that never produces a result — it rejected, or escalated a question\n * of its own — leaves the claim held: whether it acted is unknown, and a\n * later presentation is `blocked` rather than run again.\n */\n private async recordReceipt(\n receipt: { store: ReceiptStore; id: string; expiresAt: number },\n execution: Promise<ToolResultPart>,\n ): Promise<ToolResultPart> {\n const result = await execution;\n try {\n await receipt.store.complete(receipt.id, result, receipt.expiresAt);\n } catch (error) {\n this.writeLog(`[gemi/ai] agent \"${this.config.name}\" could not record a tool receipt`, {\n error,\n });\n }\n return result;\n }\n\n private async resolveAnswer(\n entry: { message: AgentMessage; call: ToolCallPart },\n answer: ClientToolResult,\n escalated: PendingToolCall[],\n ): Promise<ToolResultPart | \"open\" | null> {\n const call = entry.call;\n const name = String(call.name);\n const resolved = this.config.registry.get(name);\n const reject = (message: string) => {\n this.emit({\n type: \"error\",\n error: {\n code: \"invalid_tool_result\",\n message,\n toolCallId: call.toolCallId,\n retryable: false,\n },\n });\n return null;\n };\n\n if (!resolved) {\n return reject(`The tool \"${name}\" no longer exists, so its answer cannot be checked.`);\n }\n const kind = pendingKind(resolved.tool);\n if (!kind) {\n return reject(`\"${name}\" is a server tool with no pending question.`);\n }\n if (typeof answer.signature !== \"string\" || answer.signature.length === 0) {\n return reject(`The answer for \"${name}\" carried no signature.`);\n }\n\n // The issuing run, read out of the token. The turn answering a pending call\n // is a *new* run with a new id, so the id the signature was made under has\n // to travel with the signature — and it is covered by the MAC, so a client\n // that edits it fails below rather than being believed.\n const issued = readSignature(answer.signature);\n if (!issued) {\n return reject(`The signature for \"${name}\" is malformed.`);\n }\n\n // The path is this run's own, not the one the client sent. The client's\n // copy was used to route the answer here and nothing else; recomputing the\n // MAC over what the server issued is what makes a moved answer fail instead\n // of being believed.\n const verified = verifyPendingCall(answer.signature, {\n ...this.claimsFor(call.toolCallId, name, kind, call.input),\n runId: issued.runId,\n });\n\n if (verified.ok === false) {\n return reject(\n verified.reason === \"expired\"\n ? `The approval for \"${name}\" has expired. Ask again.`\n : `The answer for \"${name}\" does not match the call the server made.`,\n );\n }\n\n // An approval that already ran is answered with what it did, before the\n // nonce is looked at (#458): its nonce was spent by the run that executed\n // it, so the check below would refuse it, and a retried submit whose\n // response was lost would tell the user the approval was not used when the\n // tool has already acted on it. Claimed before spending, so that two\n // instances whose nonce stores are not shared still run it once.\n let receipt: { store: ReceiptStore; id: string; expiresAt: number } | undefined;\n if (\n this.params.receipts &&\n kind === \"approval\" &&\n \"approve\" in answer &&\n answer.approve === true\n ) {\n const store = this.params.receipts;\n const id = executionReceiptId(this.config.name, {\n ...this.claimsFor(call.toolCallId, name, kind, call.input),\n runId: issued.runId,\n });\n let claim: ReceiptClaim;\n try {\n claim = await store.claim(id, issued.expiresAt);\n } catch (error) {\n // As with a nonce store that throws: refused, not run unchecked.\n this.writeLog(`[gemi/ai] agent \"${this.config.name}\" could not claim a tool receipt`, {\n error,\n });\n return reject(`The approval for \"${name}\" could not be checked. Ask again.`);\n }\n if (claim.status === \"replay\") {\n return { ...claim.result, toolCallId: call.toolCallId, name: call.name } as ToolResultPart;\n }\n if (claim.status === \"blocked\") {\n return {\n type: \"tool-result\",\n toolCallId: call.toolCallId,\n name: call.name,\n status: \"error\",\n error: {\n code: \"tool_error\",\n message: `\"${name}\" was already approved and started, and its result is not recorded yet: it is still running, or it stopped before finishing. It was not run again.`,\n toolCallId: call.toolCallId,\n retryable: false,\n },\n };\n }\n receipt = { store, id, expiresAt: issued.expiresAt };\n }\n\n // Verifying says the server once asked this exact question; spending the\n // nonce says nobody has answered it yet. Without this step a captured token\n // approves the same call every time it is presented — the client rewinds to\n // the history from before the result existed and replays, and the human who\n // approved once has approved forever.\n if (!(await this.spend(spendPendingCall, answer.signature))) {\n // Claimed for nothing: nothing ran, so a later presentation must not be\n // told it is running. Answered by a run that predates the store, or\n // denied before: either way there is no result to replay.\n await receipt?.store.release(receipt.id).catch((error) => {\n this.writeLog(`[gemi/ai] agent \"${this.config.name}\" could not release a tool receipt`, {\n error,\n });\n });\n return reject(`The answer for \"${name}\" has already been used. Ask again.`);\n }\n\n if (\"approve\" in answer) {\n if (kind !== \"approval\") {\n return reject(`\"${name}\" is answered by the client, not approved.`);\n }\n if (answer.approve === true) {\n // Raced against the abort signal exactly as `runTools` does. A tool\n // that does not honour `ctx.signal` must not be able to hold the run\n // open, and this is the one execution outside the loop — a `stop()`\n // landing here used to hang the run forever, which is precisely the\n // dangling state `stop()` exists to prevent.\n //\n // Step 0: the approval landed before this run took its first model\n // step, so it belongs to no step of this loop. `call.input` is the\n // value the signature covers — see `runTools`.\n //\n // Cloned first, for the same reason `reenter` clones: an approved tool\n // may nest, and `nestedRunner` writes `nested` onto the part it is\n // given. That part belongs to the caller's `messages` array, which is\n // an input and not scratch space — and the clone is what makes the\n // sub-run transcript something `onMessage` can report.\n const executing = this.amendCall(entry);\n const execution = this.executeTool(\n resolved,\n entry.message.id,\n executing,\n executing.input,\n 0,\n );\n try {\n return await raceAbort(\n receipt ? this.recordReceipt(receipt, execution) : execution,\n this.controller.signal,\n );\n } catch (error) {\n if (error instanceof PendingEscalation) {\n // An approval whose tool asked the user something of its own. The\n // step loop and `reenter` both collect this; without the same catch\n // here the rejection left `ingestTurn` and was normalized into a\n // `provider_error`, which ended the run with the sub-agent's\n // question thrown away and the approval's nonce already spent.\n escalated.push(...error.pending);\n return \"open\";\n }\n throw error;\n }\n }\n return {\n type: \"tool-result\",\n toolCallId: call.toolCallId,\n name: call.name,\n status: \"denied\",\n cause: \"refused\",\n reason: answer.reason,\n };\n }\n\n if (\"output\" in answer) {\n if (kind === \"approval\") {\n // An approval is a tool the *server* runs. A client handing back its\n // output would be fabricating a result, not approving one.\n return reject(`\"${name}\" is approved, not answered: the server produces its result.`);\n }\n const schema = resolved.tool.outputSchema;\n const parsed = schema\n ? schema.safeParse(answer.output)\n : { ok: true as const, value: answer.output };\n if (parsed.ok === false) {\n return {\n type: \"tool-result\",\n toolCallId: call.toolCallId,\n name: call.name,\n status: \"error\",\n error: {\n code: \"invalid_tool_result\",\n message: `The answer for \"${name}\" did not match its output schema: ${parsed.errors.join(\", \")}`,\n toolCallId: call.toolCallId,\n retryable: true,\n },\n };\n }\n return {\n type: \"tool-result\",\n toolCallId: call.toolCallId,\n name: call.name,\n status: \"ok\",\n output: parsed.value,\n };\n }\n\n return reject(`The answer for \"${name}\" carried neither an approval nor an output.`);\n }\n\n /**\n * Puts the result next to the call that asked for it.\n *\n * The message being amended came from an earlier run, so it is cloned before\n * it is touched — the caller's `messages` array is an input, not scratch\n * space, and a controller that persisted it would otherwise see it change\n * under it. The clone is reported through `onMessage` and returned in\n * `result()`, which is why a store keyed by message id has to upsert.\n */\n private attachToHistory(\n entry: { message: AgentMessage; call: ToolCallPart },\n result: ToolResultPart,\n ) {\n const message = this.amend(entry.message);\n message.content.push(result);\n this.unreported.add(message);\n this.emit({ type: \"tool-result\", messageId: message.id, part: result });\n }\n\n /**\n * The provider refused a stored file and the call went ahead without it\n * (#684). Every part holding that id is marked `providerRejected`, so the\n * next request sends a note in its place rather than an id that fails the\n * request again — the history is sent whole on every turn, and without the\n * mark one dead file costs every later turn a refused request.\n *\n * Persisted the way a late tool result is: a message from an earlier run is\n * amended (cloned, then reported and returned in `result()`), and one this\n * run made is changed in place and reported again. Either way the store\n * sees the same id with new content, which its contract says to upsert.\n * The part is replaced rather than written to, because the original object\n * may still be the caller's.\n *\n * Logged as a warning, not an error: the run goes on, and the model is told\n * the file could not be read, so the user hears about it in the answer. The\n * log is for whoever has to work out why a file stopped being readable.\n */\n private markFileRejected(\n fileId: string,\n reason: string,\n detail: { status?: number; requestId?: string },\n ): void {\n for (const original of this.history) {\n const hit = original.content.some(\n (part) => part.type === \"file\" && part.fileId === fileId && !part.providerRejected,\n );\n if (!hit) continue;\n const message = this.produced.includes(original) ? original : this.amend(original);\n message.content = message.content.map((part) =>\n part.type === \"file\" && part.fileId === fileId && !part.providerRejected\n ? { ...part, providerRejected: true as const }\n : part,\n );\n // The message being built by this step is reported when it is finalized;\n // queueing it here as well would report it before it is finished.\n if (message !== this.current) this.unreported.add(message);\n }\n if (!this.config.logErrors) return;\n const message = `[gemi/ai] agent \"${this.config.name}\": the provider refused file ${fileId}${\n detail.status !== undefined ? ` (${detail.status})` : \"\"\n }; it was left out of the request and will not be sent again: ${reason}`;\n const metadata = {\n agent: this.config.name,\n runId: this.runId,\n ...(this.params.threadId ? { threadId: this.params.threadId } : {}),\n fileId,\n ...detail,\n };\n let logged = false;\n try {\n Log.warning(message, metadata);\n logged = true;\n } catch {\n // No application to resolve a logger from.\n }\n if (!logged || process.env.NODE_ENV === \"development\") console.warn(message, metadata);\n }\n\n /** The clone of an earlier run's message that this run may write to. One per\n * message id, so two results for the same message do not fork it. */\n private amend(original: AgentMessage): AgentMessage {\n const existing = this.amended.get(original.id);\n if (existing) return existing;\n const message: AgentMessage = { ...original, content: [...original.content] };\n const index = this.history.indexOf(original);\n if (index >= 0) this.history[index] = message;\n this.produced.push(message);\n this.amended.set(original.id, message);\n return message;\n }\n\n /**\n * Persists the messages this run finished outside `finalizeMessage`, once each\n * and in the order it finished them.\n *\n * Called from the end of `ingestTurn`, from the abort path, and from\n * `finalizeMessage`. From the abort path because a stop that lands while an\n * approved tool is running has to persist the results that *did* attach this\n * turn — otherwise the work is done, the transcript on the stream shows it,\n * and the store never hears about it. From `finalizeMessage` because an\n * injected message has to reach `onMessage` after the assistant message it\n * sits below, and a `Set` preserves insertion order, which here is transcript\n * order.\n */\n private async reportDeferred(): Promise<void> {\n const pending = [...this.unreported];\n this.unreported.clear();\n for (const message of pending) await this.report(message);\n }\n\n // --- stopping ----------------------------------------------------------\n\n /**\n * The run's last act: leave a transcript the next turn can be built on.\n *\n * Everything the model asked for and did not get becomes a `denied` result\n * with `cause: \"stopped\"`, and the interrupted message is finalized as\n * `aborted` keeping whatever text it had produced. Both go out on the stream\n * and through `onMessage`. A cancel that merely stopped emitting would leave\n * a dangling tool call, and the provider would reject the history on the very\n * next message the user sent.\n */\n private async finalizeAborted(): Promise<void> {\n // Sub-runs first. They share this run's signal so they are already closing;\n // what is being waited for is the moment each writes its transcript onto\n // its tool call, because everything below this line persists messages.\n if (this.nestedSettling.size > 0) {\n await Promise.all([...this.nestedSettling]);\n }\n // Calls left open anywhere in the history, not just on the message this run\n // was building. A stop that lands while an approval this turn is executing\n // has no current message at all — the call belongs to an *earlier* turn's\n // message — and denying only `this.current` would leave that one dangling\n // in the very transcript this method exists to keep valid.\n for (const entry of this.openCalls()) {\n if (entry.message === this.current) continue;\n this.attachToHistory(entry, {\n type: \"tool-result\",\n toolCallId: entry.call.toolCallId,\n name: entry.call.name,\n status: \"denied\",\n cause: \"stopped\",\n reason: this.stopReason,\n });\n }\n // Results that did attach this turn have not been persisted yet: the report\n // pass at the end of `ingestTurn` is one of the things the abort skipped.\n await this.reportDeferred();\n\n const message = this.current;\n if (message) {\n const answered = new Set(\n message.content\n .filter((part): part is ToolResultPart => part.type === \"tool-result\")\n .map((part) => part.toolCallId),\n );\n for (const part of [...message.content]) {\n if (part.type !== \"tool-call\" || answered.has(part.toolCallId)) continue;\n // A call whose arguments were still arriving is finalized too: the\n // client has already been shown it, and an unresolved part is exactly\n // what this method exists to prevent.\n delete part.partial;\n this.addResult(message, {\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n name: part.name,\n status: \"denied\",\n cause: \"stopped\",\n reason: this.stopReason,\n });\n }\n }\n if (this.timedOutAfter !== undefined) {\n // An error, not an outcome: nobody asked for this run to end, and an app\n // has to be able to see that it did — in the log, on `result().error`,\n // and as a rejection under `throwOnError`. Recorded before the message\n // closes, as every other failure is.\n this.fail({\n code: \"timeout\",\n message: `The run did not finish within its time limit of ${formatDuration(this.timedOutAfter)} (maxRunDurationMs: ${this.timedOutAfter}) and was stopped.`,\n retryable: true,\n });\n this.finishReason = \"error\";\n await this.finalizeMessage(\"error\");\n return;\n }\n this.finishReason = \"aborted\";\n await this.finalizeMessage(\"aborted\");\n }\n}\n\nfunction pendingKind(tool: AnyAgentTool): \"approval\" | \"question\" | \"client\" | null {\n if (tool.answeredBy === \"client\") {\n // A question is a client tool whose input is the prompt itself. The\n // distinction is for the UI — one renders a dialog, the other runs code —\n // and it costs nothing to carry.\n return tool.inputSchema === questionSchema ? \"question\" : \"client\";\n }\n return tool.requiresApproval ? \"approval\" : null;\n}\n\nfunction parseArgs(args: string): any {\n if (!args || !args.trim()) return {};\n try {\n return JSON.parse(args);\n } catch {\n return args;\n }\n}\n",
15
- "import { Log } from \"../facades/Log\";\nimport { AgentRunError, type AgentRunFailure, type ReasoningEffort } from \"./Agent\";\nimport type { AgentProvider } from \"./AgentProvider\";\nimport { httpErrorDetail } from \"./providers/errors\";\nimport {\n addUsage,\n appendReasoning,\n appendText,\n emptyUsage,\n outputFormat,\n parseOutput,\n raceAbort,\n resolveRope,\n RunAborted,\n} from \"./runtime\";\nimport type { Infer, Schema } from \"./Schema\";\nimport type { AgentError, AgentMessage, FinishReason, Usage } from \"./types\";\n\n/**\n * One model call with an output schema: no tools, no loop, no stream to a client.\n *\n * const result = await generate({\n * provider,\n * instructions: \"You are the copywriter of …\",\n * prompt: `The business: ${description}`,\n * output: s.object({ headline: s.string(), cta: s.string() }),\n * });\n * if (result.ok) save(result.output);\n *\n * WHAT IT IS FOR. Before this, the only structured generation gemi offered was\n * an `Agent` with an `output` schema, and an app that wanted one typed answer\n * got a tool loop it did not want and — through `ctx.runAgent` — a nested\n * transcript streamed to the browser for a value the browser never renders\n * (#594, #595). This is the agent's step without the agent: it assembles the\n * same provider call and parses the answer the same way (`runtime.ts` holds\n * both halves, shared), and that is all it does.\n *\n * INSIDE A TOOL, CALL `ctx.generate` INSTEAD. It is this function with the turn\n * bound in, not a second implementation: it aborts when the turn is stopped and\n * adds its usage to the turn's, two things a tool passing `ctx.signal` by hand\n * would forget invisibly. See `ToolContext.generate`.\n *\n * IT DOES NOT THROW FOR A BAD ANSWER. It returns `{ ok: false, error }`, and\n * `messages` and `usage` are on both arms. That is the requesting app's retry\n * pattern, and the reason for the shape: a rejected answer is retried by\n * continuing the conversation — `messages` plus \"your output was rejected:\n * <problems>\" — so the transcript holding the reply that failed is exactly\n * what the retry needs, and a throw would have lost it or buried it on an\n * exception. Usage is on both because the tokens were billed either way, and\n * the failed attempt is the one an app repeats. It is also how the rest of the\n * module already reports: `Schema.safeParse` returns a result, and a failing\n * tool is a result the model reads. Pass `throwOnError: true` to have it\n * reject with an `AgentRunError` instead, as `run.result()` can.\n *\n * A FAILURE IS LOGGED through `Log.error` by default, as a failed agent run is\n * (`logErrors: false` turns it off); a stop is not a failure and is not. On\n * `ok: false`, `error` also carries the provider's HTTP `status` and\n * `requestId` when it answered with an error, as `result().error` does.\n *\n * `error.code` says which failure it was:\n *\n * - `invalid_output` — the answer did not match the schema, was cut off at\n * `maxOutputTokens` (then `finishReason` is `\"length\"`), or never came.\n * - `timeout` — `signal` fired with a `TimeoutError`: an\n * `AbortSignal.timeout`, or the tool's `timeoutMs` under `ctx.generate`.\n * - `aborted` — `signal` fired for any other reason: a stop.\n * - anything else — the provider failed, normalized by the provider's own\n * `normalizeError` exactly as a failed agent step is (`rate_limited`,\n * `content_filtered`, `provider_error`, …).\n *\n * The one thing that does throw is a call that could never work: neither\n * `prompt` nor `messages`. That is a bug in the caller, not an outcome.\n *\n * NOT MEMOIZED, AND NOT RECORDED. It writes nothing to a thread and sends no\n * frame, which is the point of it — and it also means a tool body that is\n * re-entered after an escalation (see `ToolContext.runAgent`) calls the model\n * again. `ctx.runAgent` and `ctx.generateImage` can replay because they record\n * on the tool call; this has nothing to record into by design.\n */\nexport function generate<O extends Schema<any>>(\n params: GenerateParams<O> & { throwOnError: true },\n): Promise<GenerateSuccess<Infer<O>>>;\nexport function generate<O extends Schema<any>>(\n params: GenerateParams<O>,\n): Promise<GenerateResult<Infer<O>>>;\nexport function generate(params: GenerateParams): Promise<GenerateResult<unknown>> {\n return generateWithin(params);\n}\n\n/**\n * Where a `generate` call was made from, for its log line: `ctx.generate`\n * passes the agent, run and tool call it belongs to.\n */\nexport type GenerateOrigin = Record<string, unknown>;\n\n/**\n * `generate`, plus what `ctx.generate` needs to bind it to a turn: the origin\n * for the log line, and `settled`, which sees the result before it is logged\n * or thrown. That is where the turn adds the usage (billed whether or not the\n * answer parsed, and whether or not it is about to throw) and throws when the\n * turn itself was stopped.\n */\nexport async function generateWithin(\n params: GenerateParams,\n hooks: { origin?: GenerateOrigin; settled?: (result: GenerateResult<unknown>) => void } = {},\n): Promise<GenerateResult<unknown>> {\n // An id for the call, so the log line and an `AgentRunError` can be matched\n // up. `gen_` rather than `run_`: there is no run, and nothing is stored.\n const id = `gen_${crypto.randomUUID()}`;\n const result = await callModel(params);\n hooks.settled?.(result);\n if (!result.ok) {\n // A stop is an outcome the caller asked for, not a failure — the same rule\n // an agent run follows (an aborted run carries no `error` and is not\n // logged). A timeout is a failure: it reports `timeout`, as a run's\n // deadline does, and is logged.\n if (params.logErrors !== false && result.error.code !== \"aborted\") {\n logFailure(id, result.error, hooks.origin);\n }\n if (params.throwOnError) {\n throw new AgentRunError({\n runId: id,\n messages: result.messages,\n finishReason: result.finishReason,\n usage: result.usage,\n error: result.error,\n });\n }\n }\n return result;\n}\n\n/**\n * Through the app's logger, as a failed agent run is (`AgentRunImpl.logFailure`):\n * `Log.error`, so it lands in `storage/logs` and `onLogCreated`; outside an\n * application, where there is no logger to resolve, `console.error` instead;\n * and in development the console as well.\n */\nfunction logFailure(id: string, failure: AgentRunFailure, origin?: GenerateOrigin): void {\n const message = `[gemi/ai] generate() failed (${failure.code}${\n failure.status !== undefined ? ` ${failure.status}` : \"\"\n }): ${failure.message}`;\n const metadata = { ...origin, generateId: id, error: failure };\n let logged = false;\n try {\n Log.error(message, metadata);\n logged = true;\n } catch {\n // No application to resolve a logger from. Reported below instead.\n }\n if (!logged || process.env.NODE_ENV === \"development\") {\n console.error(message, metadata);\n }\n}\n\nasync function callModel<O extends Schema<any>>(\n params: GenerateParams<O>,\n): Promise<GenerateResult<Infer<O>>> {\n const prior = params.messages ?? [];\n if (prior.length === 0 && !params.prompt) {\n throw new Error(\n \"generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.\",\n );\n }\n\n const messages: AgentMessage[] = [...prior];\n if (params.prompt) {\n messages.push({\n id: `msg_${crypto.randomUUID()}`,\n role: \"user\",\n content: [{ type: \"text\", text: params.prompt }],\n createdAt: new Date().toISOString(),\n });\n }\n const reply: AgentMessage = {\n id: `msg_${crypto.randomUUID()}`,\n role: \"assistant\",\n content: [],\n createdAt: new Date().toISOString(),\n };\n\n // `raceAbort` wants a signal to race, and a caller with none gets one that\n // never fires rather than a second code path.\n const signal = params.signal ?? new AbortController().signal;\n let usage = emptyUsage();\n let reason: FinishReason = \"stop\";\n let error: AgentError | undefined;\n // The HTTP status and request id of a failed provider response, as an agent\n // run records them on `result().error` (#656). Server-side only.\n let detail: { status?: number; requestId?: string } = {};\n let outputText = \"\";\n\n try {\n const stream = params.provider.stream({\n // A copy: the provider is handed the array and has no business growing\n // the one this function is about to return.\n messages: [...messages],\n systemPrompt: params.instructions?.trim() ? params.instructions : undefined,\n output: outputFormat(params.output),\n reasoning: params.reasoning,\n maxOutputTokens: params.maxOutputTokens,\n temperature: params.temperature,\n signal: params.signal,\n });\n const iterator = stream[Symbol.asyncIterator]();\n try {\n for (;;) {\n // Raced, as the agent's step is: a provider that ignores its signal\n // must not be able to hold a stopped call open.\n const next = await raceAbort(Promise.resolve(iterator.next()), signal);\n if (next.done) break;\n const event = next.value;\n switch (event.type) {\n case \"output-delta\":\n outputText += event.delta;\n break;\n // Kept on the reply for what they are worth to a retry: reasoning\n // carries its item id so a continuation echoes it back and keeps the\n // prompt cache, and prose is what a model that ignored the format\n // said instead.\n case \"text-delta\":\n appendText(reply, \"text\", event.delta);\n break;\n case \"reasoning-delta\":\n appendReasoning(reply, event.id, event.delta);\n break;\n case \"finish\":\n // Usage is taken whatever happened before it; the reason only if\n // nothing already failed. A content filter reports an error and\n // then closes the call with a finish that still bills — the same\n // rule `AgentRunImpl.runStep` follows.\n usage = addUsage(usage, event.usage);\n if (!error) reason = event.reason;\n break;\n case \"error\":\n reason = \"error\";\n error = event.error;\n detail = httpErrorDetail(event);\n break;\n // `tool-call-delta`, `tool-call` and `tool-search` cannot happen:\n // no tools were sent.\n // `file-rejected` needs nothing here: the provider already sent the\n // call again without that file, and `generate()` keeps no thread\n // to mark the part in. The caller's `messages` are its own.\n }\n }\n } finally {\n // Not awaited. On the abort path the generator may be parked inside a\n // `fetch` that ignores its signal, and waiting on it would give back\n // the hang the race above exists to prevent.\n if (signal.aborted) void Promise.resolve(iterator.return?.()).catch(() => {});\n }\n } catch (thrown) {\n if (thrown instanceof RunAborted || signal.aborted) {\n reason = \"aborted\";\n error = abortError(signal);\n } else {\n reason = \"error\";\n error = params.provider.normalizeError(thrown);\n detail = httpErrorDetail(thrown);\n }\n }\n\n // A flag rather than `output !== undefined`: the schema decides what a\n // valid answer is, and nothing says it cannot be a falsy one.\n let answered = false;\n let output: Infer<O> | undefined;\n if (!error) {\n if (reason === \"length\") {\n // Never parsed. A cut-off answer is a prefix of the JSON the model meant\n // to write, `bestEffortParse` closes its brackets, and against a loose\n // schema — `s.json()` — the repaired half passes looking finished. The\n // agent loop withholds its `output` part for the same reason.\n error = {\n code: \"invalid_output\",\n message:\n \"The model ran out of output tokens before finishing its structured answer, so it was cut off. Raise maxOutputTokens, or ask for a shorter answer.\",\n retryable: true,\n };\n } else if (!outputText.trim()) {\n error = {\n code: \"invalid_output\",\n message: \"The model finished without giving a structured answer.\",\n retryable: true,\n };\n } else {\n const parsed = parseOutput(params.output, outputText);\n if (parsed.ok === true) {\n answered = true;\n output = parsed.value as Infer<O>;\n } else {\n error = parsed.error;\n }\n }\n }\n\n if (answered) {\n reply.content.push({ type: \"output\", value: output });\n } else if (outputText) {\n // The answer that failed, as the model wrote it. A retry continues this\n // transcript, and \"your output did not parse\" means little to a model that\n // cannot see what it wrote. Text rather than an `output` part because it is\n // not a value of the schema — an `output` part promises one.\n appendText(reply, \"text\", outputText);\n }\n for (const part of reply.content) {\n if ((part.type === \"text\" || part.type === \"reasoning\") && typeof part.text === \"string\") {\n part.text = resolveRope(part.text);\n }\n }\n reply.finishReason = reason;\n // One call, one message: the reply's usage is the call's, as an agent step's\n // message carries its own (#467).\n reply.usage = usage;\n messages.push(reply);\n\n if (answered) {\n return { ok: true, output: output as Infer<O>, messages, usage, finishReason: reason };\n }\n return { ok: false, error: { ...error!, ...detail }, messages, usage, finishReason: reason };\n}\n\nfunction abortError(signal: AbortSignal): AgentError {\n // `AbortSignal.timeout()` aborts with a `TimeoutError` (and so does a tool's\n // `timeoutMs`, through `ctx.signal`), and saying so is the difference\n // between \"somebody pressed stop\" and \"try again with more time\".\n const timedOut = (signal.reason as { name?: unknown } | undefined)?.name === \"TimeoutError\";\n // The same code an agent run's deadline and a tool's `timeoutMs` report\n // (#455), so one branch on `\"timeout\"` covers all three.\n return timedOut\n ? { code: \"timeout\", message: \"The generation timed out.\", retryable: true }\n : { code: \"aborted\", message: \"The generation was stopped.\", retryable: false };\n}\n\n/** What `generate` and `ctx.generate` are given. `messages` and `prompt` are\n * alternatives, and together the prompt is appended as the next user turn —\n * the same pair `ctx.runAgent` takes, so a retry reads the same in both. */\nexport interface GenerateParams<O extends Schema<any> = Schema<any>> {\n provider: AgentProvider;\n /**\n * The answer's shape, and the type of `output`. Required: a call without one\n * is a chat completion, which is not what this is.\n *\n * `strict` is read off the schema, as it is for an agent — a schema holding\n * an `s.json()` node is sent non-strict, since strict mode cannot express it.\n */\n output: O;\n /** The system prompt. */\n instructions?: string;\n /** Prior turns. Returned again at the front of `messages`, untouched. */\n messages?: AgentMessage[];\n /** Sugar for one more user turn, appended after `messages`. */\n prompt?: string;\n /** Dropped by a provider whose model cannot reason, as for an agent. */\n reasoning?: ReasoningEffort;\n /**\n * The provider's `max_output_tokens`. An answer that reaches it is cut off,\n * and comes back `ok: false` with `finishReason: \"length\"` — never as a\n * repaired half that happens to pass the schema.\n */\n maxOutputTokens?: number;\n /** Sent whenever set; a reasoning model that rejects it answers 400. See\n * `CreateAgentParams.temperature`. */\n temperature?: number;\n /**\n * Stops the call; it then resolves `ok: false` with `code: \"aborted\"`, or\n * `code: \"timeout\"` when it aborted with a `TimeoutError`.\n * `AbortSignal.timeout(ms)` is how to bound one.\n *\n * On `ctx.generate` this is combined with the turn's signal rather than\n * replacing it, so a timeout of the tool's own cannot unhook a `stop()`.\n */\n signal?: AbortSignal;\n /**\n * Reject with an `AgentRunError` instead of resolving `ok: false`, as\n * `run.result({ throwOnError: true })` does for an agent. Its `result` holds\n * the `messages`, `usage` and `error`, and its `runId` is the call's\n * `gen_` id. Any `ok: false` rejects, a stop included, since there is no\n * output to resolve with; the return type is then the `ok: true` arm.\n * Default `false`.\n */\n throwOnError?: boolean;\n /**\n * Write a failed call to the app's log (`Log.error`), as a failed agent run\n * is. Default `true`. A stop (`code: \"aborted\"`) is not a failure and is not\n * logged. Turn it off when the caller reports `result.error` itself — a\n * retry loop that expects `invalid_output` now and then, say.\n */\n logErrors?: boolean;\n}\n\n/** The parts of a `GenerateResult` both arms have. */\ninterface GenerateOutcome {\n /**\n * The whole transcript: `messages` as given, the `prompt` as a user turn,\n * then the model's reply. On success the reply holds the value as an\n * `output` part; on a bad answer, the raw text the model wrote — so a retry\n * passes this straight back with a new `prompt` saying what was wrong.\n */\n messages: AgentMessage[];\n /** What the call cost, including when it failed — the tokens were billed. */\n usage: Usage;\n /** How the model call ended: `\"stop\"` on success, `\"length\"` for a cut-off\n * answer, `\"error\"` or `\"aborted\"` when it did not finish. */\n finishReason: FinishReason;\n}\n\n/**\n * Discriminated on `ok`. `output` and `error` are each declared on both arms —\n * as `undefined` on the one where they cannot be — so that destructuring\n * `{ ok, output, error }` compiles, and checking `ok` narrows both.\n */\nexport type GenerateResult<O> =\n | GenerateSuccess<O>\n | (GenerateOutcome & {\n ok: false;\n /** The `AgentError`, plus the provider's HTTP `status` and `requestId`\n * when the failure was a response from it — as on an agent run's\n * `result().error`. */\n error: AgentRunFailure;\n output?: undefined;\n });\n\n/** The `ok: true` arm of `GenerateResult`, and what `throwOnError` resolves. */\nexport type GenerateSuccess<O> = GenerateOutcome & { ok: true; output: O; error?: undefined };\n",
16
- "import { Storage } from \"../../facades/Storage\";\nimport { app } from \"../../foundation/app\";\nimport { Job } from \"../../services/queue/Job\";\nimport { QueueManager } from \"../../services/queue/QueueManager\";\nimport type { GeneratedAttachment, ToolGenerateImageParams, ToolEditImageParams } from \"../Agent\";\nimport { generateWithin, type GenerateParams, type GenerateResult } from \"../generate\";\nimport type { ImageInput, ImageModel } from \"../ImageModel\";\nimport { redactError, ToolError } from \"../redact\";\nimport { addUsage, emptyUsage } from \"../runtime\";\nimport type { Infer, Schema } from \"../Schema\";\nimport {\n type Attachment,\n type AttachmentStorage,\n type AttachmentStore,\n defaultAttachmentStore,\n InvalidAttachmentScopeError,\n ScopedAttachments,\n} from \"../store/Attachments\";\nimport type { AgentError, Usage } from \"../types\";\nimport {\n type AgentJobRecord,\n type AgentJobState,\n type AgentJobStore,\n MemoryAgentJobStore,\n} from \"./AgentJobStore\";\n\n// --- the handle a tool returns -------------------------------------------\n\nconst HANDLE = Symbol.for(\"gemi.ai.JobHandle\");\n\n/**\n * What `ctx.jobs.start` and `ctx.jobs.track` answer, and what a tool returns to\n * say \"this call goes on in the background\" (#461).\n *\n * Returning it is what makes the call's result `running` rather than `ok`: the\n * model reads that the job started and is told not to start it again, the turn\n * goes on and ends as usual, and when the job settles the controller renders\n * its outcome over that result the next time it loads the thread.\n *\n * `Output` is the job's settled output, and it is what the tool's output type\n * becomes, so a client's `ToolShapes` see the job's result as the tool's.\n */\nexport class JobHandle<Output = unknown> {\n /** Phantom: the settled output's type. Never set. */\n declare readonly $output: Output;\n readonly [HANDLE] = true as const;\n\n constructor(\n /** The job's id. Hand it to whatever settles a tracked job. */\n readonly id: string,\n readonly toolCallId: string,\n readonly summary: unknown,\n /** Epoch milliseconds, on the job store's clock. */\n readonly deadlineAt: number,\n ) {}\n}\n\n/** Whether a tool's return value is a `JobHandle`, across copies of the module. */\nexport function isJobHandle(value: unknown): value is JobHandle {\n return typeof value === \"object\" && value !== null && (value as any)[HANDLE] === true;\n}\n\n// --- errors ----------------------------------------------------------------\n\n/**\n * `ctx.jobs.start` or `track` from a run that has nowhere to settle a job\n * into: a stateless turn, a run started without a job store, or a sub-run.\n *\n * A `ToolError`, so the model reads why the tool could not go to the\n * background and can say so, rather than being told the tool broke.\n */\nexport class JobsRequireThreadError extends ToolError {\n readonly code = \"jobs_require_thread\" as const;\n\n constructor(message: string) {\n super(message, { retryable: false });\n this.name = \"JobsRequireThreadError\";\n }\n}\n\n// --- the process-wide registry ----------------------------------------------\n\nlet currentStore: AgentJobStore = new MemoryAgentJobStore();\n\n/** Every state, for a transition that does not change the state. */\nconst ANY_STATE: AgentJobState[] = [\"running\", \"ok\", \"error\"];\n\n/** What a job settles with. */\nexport type AgentJobOutcome =\n | { output: unknown; usage?: Usage }\n | { error: string | Error | (Pick<AgentError, \"message\"> & Partial<AgentError>); usage?: Usage };\n\n/**\n * Background jobs, from anywhere in the app: settle one, fail one, look one up.\n *\n * PROCESS-WIDE, and that is forced. A job is started by a tool inside a run,\n * and settled by a queue worker, a provider's webhook, a poller or the deadline\n * sweep, none of which has a controller to read a store from. So the store is\n * set once, at boot, for every one of them:\n *\n * AgentJobs.use(new DatabaseAgentJobStore(app(DatabaseManager).connection()));\n *\n * Until then it is a `MemoryAgentJobStore`, which works in one process and\n * forgets on restart.\n */\nexport const AgentJobs = {\n /** The store every part of the feature reads and writes. */\n get store(): AgentJobStore {\n return currentStore;\n },\n\n /** Sets the store. Call it once, at boot, in every process that starts or runs jobs. */\n use(store: AgentJobStore): void {\n currentStore = store;\n },\n\n get(id: string): Promise<AgentJobRecord | null> {\n return currentStore.get(id);\n },\n\n /**\n * Settles a running job with its output or its error, and answers whether\n * this call did it.\n *\n * COMPARE-AND-SET FROM `running`. The first settle wins and every later one\n * answers `false` and changes nothing, so a webhook, a poller and the\n * deadline sweep can all race on one job. A job the deadline sweep has\n * already failed stays failed: a late result is refused, so the model never\n * sees a job flip from failed to done.\n *\n * An error given as a `ToolError`, a string or an `AgentError`-like object is\n * shown to the model as it is. Any other `Error` is logged in full and the\n * model is told only that the job failed, as for a tool that throws (#446).\n */\n async settle(id: string, outcome: AgentJobOutcome): Promise<boolean> {\n return settleOn(currentStore, id, outcome);\n },\n\n /** `settle(id, { error })`. */\n async fail(id: string, error: string | Error | AgentError): Promise<boolean> {\n return settleOn(currentStore, id, { error });\n },\n\n /**\n * The deadline sweep: fails every running job whose deadline has passed\n * with code `\"timeout\"`, and answers how many it failed.\n *\n * Compare-and-set like every settle, so it is safe to run on every\n * instance at once, and a result that arrives after it is refused. Run it\n * every minute with `AgentJobDeadlineSweep`; the controller also checks a\n * thread's jobs when it loads the thread, so an app without cron still sees\n * overdue jobs fail, just later. The job's queue worker is not stopped: what\n * it returns afterwards is dropped.\n */\n async sweep(options: { limit?: number } = {}): Promise<number> {\n const store = currentStore;\n const limit = options.limit ?? 100;\n const now = await clockOf(store);\n let failed = 0;\n for (const record of await store.overdue(now, limit)) {\n if (await expire(store, record)) failed++;\n }\n return failed;\n },\n};\n\n/** The store's clock, or this process's for a store without one. */\nexport async function clockOf(store: AgentJobStore): Promise<number> {\n return store.now ? await store.now() : Date.now();\n}\n\n/** Fails a running job for its deadline. Compare-and-set: false when it had settled. */\nexport function expire(store: AgentJobStore, record: AgentJobRecord): Promise<boolean> {\n return store.transition(record.id, [\"running\"], {\n state: \"error\",\n error: {\n code: \"timeout\",\n message: `The background job for \"${record.toolName}\" did not finish before its deadline, so it was given up on. Its result, if it ever arrives, is ignored.`,\n toolCallId: record.toolCallId,\n retryable: true,\n },\n });\n}\n\nasync function settleOn(\n store: AgentJobStore,\n id: string,\n outcome: AgentJobOutcome,\n): Promise<boolean> {\n const record = await store.get(id);\n if (!record || record.state !== \"running\") return false;\n const usage = outcome.usage ? addUsage(record.usage ?? emptyUsage(), outcome.usage) : undefined;\n if (\"error\" in outcome) {\n return store.transition(id, [\"running\"], {\n state: \"error\",\n error: jobError(record, outcome.error),\n ...(usage ? { usage } : {}),\n });\n }\n return store.transition(id, [\"running\"], {\n state: \"ok\",\n output: plainData(outcome.output, record),\n ...(usage ? { usage } : {}),\n });\n}\n\n/** The error the model reads. See `AgentJobs.settle`. */\nfunction jobError(\n record: Pick<AgentJobRecord, \"toolCallId\" | \"toolName\" | \"job\">,\n error: AgentJobOutcome extends infer O ? (O extends { error: infer E } ? E : never) : never,\n): AgentError {\n if (typeof error === \"string\") {\n return { code: \"tool_error\", message: error, toolCallId: record.toolCallId, retryable: true };\n }\n if (error instanceof Error) {\n const raw: AgentError = {\n code: \"tool_error\",\n message: error.message,\n toolCallId: record.toolCallId,\n retryable: error instanceof ToolError ? error.retryable : true,\n };\n if (!(error instanceof ToolError)) {\n console.error(\n `The background job ${record.job ?? \"(tracked)\"} for \"${record.toolName}\" failed.`,\n error,\n );\n }\n return redactError(raw, { source: \"tool\", toolName: record.toolName, cause: error });\n }\n return {\n code: error.code ?? \"tool_error\",\n message: String(error.message),\n toolCallId: record.toolCallId,\n retryable: error.retryable ?? true,\n };\n}\n\n/** A copy of the output that any store can keep, or a throw that says why not. */\nfunction plainData(output: unknown, record: Pick<AgentJobRecord, \"toolName\">): unknown {\n if (output === undefined) return null;\n try {\n return JSON.parse(JSON.stringify(output));\n } catch (error) {\n throw new Error(\n `The output of the background job for \"${record.toolName}\" is not JSON: ${String(error)}`,\n );\n }\n}\n\n// --- the tool side ---------------------------------------------------------\n\n/** Options for `ctx.jobs.start` and `ctx.jobs.track`. */\nexport type StartJobOptions = {\n /**\n * What the model and the UI see while the job runs, in place of a result:\n * which images, which pages. Plain data, and keep it small, since it is in\n * the history on every later turn.\n */\n summary?: unknown;\n /**\n * How long the job may run, in milliseconds. Defaults to the tool's\n * `async.deadlineMs`, else an hour. A job still running then is failed with\n * code `\"timeout\"` by the deadline sweep, and a later result is refused.\n */\n deadlineMs?: number;\n};\n\n/** A tool's `ctx.jobs`. See `ToolContext.jobs`. */\nexport interface ToolJobs {\n /**\n * Records a background job for this tool call and queues `job` to do it.\n * Return the handle from `execute` to make the call's result `running`.\n *\n * At least once, like every queued job: `job.run` may run again after a\n * crash, so make it idempotent. Only on a threaded run (a turn with a\n * `threadId` through `AgentController`), and only from a top-level tool.\n */\n start<A, O>(job: AgentJobClass<A, O>, args: A, options?: StartJobOptions): Promise<JobHandle<O>>;\n /**\n * Records a background job that something else settles: a provider's\n * webhook, a poller. Pass `handle.id` to it, and call\n * `AgentJobs.settle(id, { output })` when the work is done.\n */\n track<O = unknown>(options?: StartJobOptions): Promise<JobHandle<O>>;\n}\n\n/** What a run that may start jobs is given. `AgentController` passes it on a threaded turn. */\nexport type RunJobs = {\n /** The run's owner (`runOwner`), recorded on each job. */\n owner: string | null;\n};\n\n/** The longest a job runs when nothing says otherwise. */\nexport const DEFAULT_JOB_DEADLINE_MS = 60 * 60_000;\n\n/** @internal `ctx.jobs` for one tool call. Built by the run, per call. */\nexport function toolJobs(params: {\n jobs: RunJobs | undefined;\n threadId: string | undefined;\n runId: string;\n toolCallId: string;\n toolName: string;\n depth: number;\n /** The tool's `async` declaration; `undefined` for a tool without one. */\n async: { deadlineMs?: number } | undefined;\n attachments: ScopedAttachments | null;\n}): ToolJobs {\n /** One job per tool call: the handle the first `start`/`track` answered. */\n let started: Promise<JobHandle<any>> | null = null;\n\n const begin = (\n job: (new () => AgentJob<any, any>) | null,\n args: unknown,\n options: StartJobOptions = {},\n ) => {\n if (params.async === undefined) {\n throw new ToolError(\n `\"${params.toolName}\" called ctx.jobs, but the tool does not declare \\`async\\`. Add \\`async: { deadlineMs }\\` to its definition.`,\n { retryable: false },\n );\n }\n if (!params.jobs || !params.threadId) {\n throw new JobsRequireThreadError(\n `\"${params.toolName}\" can only run in the background on a conversation the server keeps (a turn with a threadId), and this one has none.`,\n );\n }\n if (params.depth > 0) {\n throw new JobsRequireThreadError(\n `\"${params.toolName}\" can only run in the background from the top-level agent, not from a sub-agent.`,\n );\n }\n if (started) {\n throw new ToolError(\n `\"${params.toolName}\" started a background job already: a tool call has at most one.`,\n { retryable: false },\n );\n }\n const deadlineMs = options.deadlineMs ?? params.async.deadlineMs ?? DEFAULT_JOB_DEADLINE_MS;\n if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) {\n throw new ToolError(`A job's deadlineMs must be a positive number; got ${deadlineMs}.`);\n }\n const jobs = params.jobs;\n const threadId = params.threadId;\n started = (async () => {\n const store = AgentJobs.store;\n // A tool re-entered after an escalation runs from the top again. The job\n // it started the first time is the one it gets.\n const existing = (await store.listForThread(threadId, { limit: 50 })).find(\n (record) => record.toolCallId === params.toolCallId,\n );\n if (existing) return handleOf(existing);\n\n const write = async () => {\n const record = await store.create({\n id: `ajob_${crypto.randomUUID()}`,\n threadId,\n runId: params.runId,\n toolCallId: params.toolCallId,\n toolName: params.toolName,\n owner: jobs.owner,\n job: job ? job.name : null,\n ...(options.summary !== undefined ? { summary: plainData(options.summary, params) } : {}),\n attachmentScope: params.attachments?.scopeKey ?? null,\n deadlineMs,\n });\n if (job) {\n try {\n await dispatchJob(job, { jobId: record.id, args });\n } catch (error) {\n // In a store transaction the record goes with the rollback.\n if (store.transaction) throw error;\n // Nothing will ever run it, so it is failed now rather than left to\n // reach its deadline, and the tool call reports the failure.\n await store\n .transition(record.id, [\"running\"], {\n state: \"error\",\n error: {\n code: \"tool_error\",\n message: `The background job for \"${params.toolName}\" could not be queued.`,\n toolCallId: params.toolCallId,\n retryable: true,\n },\n })\n .catch(() => {});\n throw error;\n }\n }\n return record;\n };\n // Both or neither when the store can: see `AgentJobStore.transaction`.\n const record = store.transaction ? await store.transaction(write) : await write();\n return handleOf(record);\n })();\n return started;\n };\n\n return {\n start: (job, args, options) => begin(job as new () => AgentJob<any, any>, args, options),\n track: (options) => begin(null, undefined, options),\n };\n}\n\nfunction handleOf(record: AgentJobRecord): JobHandle<any> {\n return new JobHandle(record.id, record.toolCallId, record.summary, record.deadlineAt);\n}\n\n/** What the queue carries for an `AgentJob`: the record's id and the job's own arguments. */\ntype JobEnvelope = { jobId: string; args: unknown };\n\nfunction dispatchJob(job: new () => AgentJob<any, any>, envelope: JobEnvelope): Promise<string> {\n if (job.name === \"unset\" || !job.name) {\n throw new Error(\"Cannot start an AgentJob with no `static name`.\");\n }\n return app(QueueManager).push(job, JSON.stringify([envelope]));\n}\n\n// --- the job side ------------------------------------------------------------\n\n/** An `AgentJob` subclass, as `ctx.jobs.start` takes it. */\nexport type AgentJobClass<A, O> = new () => AgentJob<A, O>;\n\n/** `generateImage`'s params inside a job: as in a tool, without `showModel` (there is no run to show). */\nexport type JobGenerateImageParams = Omit<ToolGenerateImageParams, \"showModel\">;\nexport type JobEditImageParams = Omit<ToolEditImageParams, \"showModel\">;\n\n/** Attachments inside a job: the scope of the run that started it. */\nexport interface JobAttachments {\n put(blob: Blob, params?: { name?: string; mimeType?: string }): Promise<Attachment>;\n get(id: string): Promise<Attachment>;\n read: ScopedAttachments[\"read\"];\n file(id: string): Promise<File>;\n}\n\n/**\n * What `AgentJob.run` is handed beside its arguments: the parts of a tool's\n * `ToolContext` that still mean something with no run around them.\n */\nexport interface AgentJobContext {\n /** The job's id (`ajob_…`). */\n readonly id: string;\n readonly threadId: string;\n readonly toolCallId: string;\n readonly toolName: string;\n /** The `runOwner` of the run that started it. */\n readonly owner: string | null;\n readonly summary: unknown;\n /** Not aborted yet: cancellation comes with a later release (#461, phase 4). */\n readonly signal: AbortSignal;\n /**\n * The attachments of the run that started the job: what the tool's\n * `ctx.attachments` was. Throws when that run had no attachment scope.\n */\n readonly attachments: JobAttachments;\n /** `generate`, with its usage counted on the job. See `ToolContext.generate`. */\n generate<O extends Schema<any>>(params: GenerateParams<O>): Promise<GenerateResult<Infer<O>>>;\n /** Renders an image and stores it under the run's attachments. Usage is counted on the job. */\n generateImage(model: ImageModel, params: JobGenerateImageParams): Promise<GeneratedAttachment>;\n /** Edits images (bytes or attachment ids) and stores the result. Usage is counted on the job. */\n editImage(model: ImageModel, params: JobEditImageParams): Promise<GeneratedAttachment>;\n /** What this attempt has spent so far. */\n readonly usage: Usage;\n}\n\n/**\n * A queued job that settles a tool call (#461).\n *\n * class RenderImagesJob extends AgentJob<{ pageId: number; prompts: string[] }, { made: number }> {\n * static name = \"RenderImagesJob\";\n * async run({ pageId, prompts }, job) {\n * for (const prompt of prompts) await job.generateImage(model, { prompt });\n * return { made: prompts.length };\n * }\n * }\n *\n * A gemi `Job`, so it gets the queue's leases, retries, backoff and dead\n * letters. Register it with the queue like any other job. What `run` returns\n * settles the tool call `ok`; a throw on the last attempt settles it `error`.\n * At least once: make `run` idempotent.\n *\n * Declare `run` as a method, not as an arrow-function field. Override\n * `onDeadletter` only with a call to `super.onDeadletter`, which is what fails\n * the job. `worker = true` is not supported. The queue hands `uniqueId`,\n * `throttle`, `concurrency`, `onFail` and `onDeadletter` the envelope\n * `{ jobId, args }`, not `args`.\n */\nexport abstract class AgentJob<Args = unknown, Output = unknown> extends Job {\n /** Phantom: the arguments' type. Never set. */\n declare readonly $args: Args;\n /** Phantom: the output's type. Never set. */\n declare readonly $output: Output;\n\n /**\n * Where the job's `attachments` records live. Set it to what the\n * controller's `attachments` is, as for the controller itself.\n */\n attachments: AttachmentStore = defaultAttachmentStore;\n /** Where the attachments' bytes live. Defaults to the app's `Storage`. */\n attachmentStorage: AttachmentStorage = Storage;\n\n abstract run(args: Args, job: AgentJobContext): Promise<Output> | Output;\n\n constructor() {\n super();\n // The queue calls `run(...payload)`, and the payload is the envelope. The\n // subclass's `run` is the job's body, so it is wrapped here, on the\n // instance: the queue sees a `run` that loads the record, runs the body\n // and settles the job, and the subclass writes only its work.\n const body = (this as any).run as (args: Args, job: AgentJobContext) => Promise<Output>;\n (this as any).run = (envelope: JobEnvelope) => this.$runEnvelope(envelope, body);\n }\n\n /**\n * Fails the job once the queue has given up on it: its last attempt threw,\n * it called `this.fail(error, { retry: false })`, or its process died on the\n * last attempt.\n */\n onDeadletter(error: Error, ..._args: any[]): void {\n const envelope = _args[0] as JobEnvelope | undefined;\n if (!envelope?.jobId) return;\n void settleOn(AgentJobs.store, envelope.jobId, { error }).catch((err) => {\n console.error(`Could not record the failure of background job ${envelope.jobId}.`, err);\n });\n }\n\n /** @internal The queue-facing `run`: see the constructor. */\n private async $runEnvelope(\n envelope: JobEnvelope,\n body: (args: Args, job: AgentJobContext) => Promise<Output>,\n ): Promise<Output | undefined> {\n const store = AgentJobs.store;\n const record = await store.get(envelope.jobId);\n // Settled already (the deadline passed, or another attempt finished it):\n // nothing it produced would be kept, so the work is not done again.\n if (!record || record.state !== \"running\") return undefined;\n\n const context = new JobContext(record, this);\n let output: Output;\n try {\n output = await body.call(this, envelope.args as Args, context);\n } catch (error) {\n await keepUsage(store, record.id, context.usage);\n throw error;\n }\n if (this.$outcome) {\n // `this.release()` or `this.fail()`: the queue decides what happens next.\n await keepUsage(store, record.id, context.usage);\n return output;\n }\n await settleOn(store, record.id, { output, usage: context.usage });\n return output;\n }\n}\n\n/** Adds an attempt's spend to a job still running, so a retry does not lose it. */\nasync function keepUsage(store: AgentJobStore, id: string, usage: Usage): Promise<void> {\n if (usage.totalTokens === 0 && usage.inputTokens === 0 && usage.outputTokens === 0) return;\n const record = await store.get(id);\n if (!record) return;\n await store\n .transition(id, ANY_STATE, { usage: addUsage(record.usage ?? emptyUsage(), usage) })\n .catch(() => {});\n}\n\nclass JobContext implements AgentJobContext {\n readonly id: string;\n readonly threadId: string;\n readonly toolCallId: string;\n readonly toolName: string;\n readonly owner: string | null;\n readonly summary: unknown;\n readonly signal = new AbortController().signal;\n usage: Usage = emptyUsage();\n readonly attachments: JobAttachments;\n\n constructor(record: AgentJobRecord, job: AgentJob<any, any>) {\n this.id = record.id;\n this.threadId = record.threadId;\n this.toolCallId = record.toolCallId;\n this.toolName = record.toolName;\n this.owner = record.owner;\n this.summary = record.summary;\n const scoped = record.attachmentScope\n ? new ScopedAttachments(job.attachments, job.attachmentStorage, {\n key: record.attachmentScope,\n })\n : null;\n const scope = (): ScopedAttachments => {\n if (!scoped) {\n throw new InvalidAttachmentScopeError(\n \"The run that started this job had no attachment scope, so the job cannot store or read files. See `attachmentScope()` on the controller.\",\n );\n }\n return scoped;\n };\n this.attachments = {\n put: (blob, params = {}) => scope().put(blob, params),\n get: (id) => scope().get(id),\n read: (id) => scope().read(id),\n file: (id) => scope().file(id),\n };\n }\n\n generate(params: GenerateParams<any>): Promise<any> {\n return generateWithin(params, {\n origin: { threadId: this.threadId, toolCallId: this.toolCallId, jobId: this.id },\n settled: (result) => {\n this.usage = addUsage(this.usage, result.usage);\n },\n });\n }\n\n async generateImage(\n model: ImageModel,\n params: JobGenerateImageParams,\n ): Promise<GeneratedAttachment> {\n const { name, ...settings } = params as JobGenerateImageParams & { name?: string };\n const image = await model.generate({ ...settings, signal: this.signal });\n return this.park(model, image, name);\n }\n\n async editImage(model: ImageModel, params: JobEditImageParams): Promise<GeneratedAttachment> {\n const { name, images, mask, ...settings } = params as JobEditImageParams & { name?: string };\n const asInput = async (input: ImageInput | string): Promise<ImageInput> =>\n typeof input === \"string\" ? await this.attachments.file(input) : input;\n const image = await model.edit({\n ...settings,\n images: (await Promise.all(images.map(asInput))) as [ImageInput, ...ImageInput[]],\n ...(mask ? { mask: await asInput(mask) } : {}),\n signal: this.signal,\n });\n return this.park(model, image, name);\n }\n\n private async park(\n model: ImageModel,\n image: { image: Blob; mimeType: string; size: string; usage: Usage },\n name: string | undefined,\n ): Promise<GeneratedAttachment> {\n // Counted before the store write, which may fail: the render was billed.\n this.usage = addUsage(this.usage, image.usage);\n const extension = image.mimeType === \"image/jpeg\" ? \"jpg\" : \"png\";\n const attachment = await this.attachments.put(image.image, {\n name: name ?? `${model.name}.${extension}`,\n mimeType: image.mimeType,\n });\n return { attachment, size: image.size, mimeType: image.mimeType, usage: image.usage };\n }\n}\n"
17
- ],
18
- "mappings": ";6OA0DO,AAAM,JAAuC,LACjC,MAAQ,IAAI,IAGrB,QAAU,UAEZ,QAAO,CAAC,EAAe,EAAqC,CAChE,OAAO,KAAK,YAAY,EAAO,CAAS,EAO1C,WAAW,CAAC,EAAe,EAAmB,EAAM,KAAK,IAAI,EAAY,CACvE,GAAI,KAAK,MAAM,MAAQ,KAAK,QAAS,KAAK,MAAM,CAAG,EACnD,IAAM,EAAa,KAAK,MAAM,IAAI,CAAK,EAGvC,GAAI,IAAe,QAAa,EAAa,EAAK,MAAO,GAEzD,OADA,KAAK,MAAM,IAAI,EAAO,CAAS,EACxB,MAGL,KAAI,EAAW,CACjB,OAAO,KAAK,MAAM,KAGZ,KAAK,CAAC,EAAa,CACzB,QAAY,EAAO,KAAc,KAAK,MACpC,GAAI,GAAa,EAAK,KAAK,MAAM,OAAO,CAAK,EAE/C,KAAK,QAAU,KAAK,IAAI,KAAM,KAAK,MAAM,KAAO,CAAC,EAErD,CAmCO,MAAM,EAAsC,CAChC,eACA,OAEjB,WAAW,CAAC,EAAkC,CAAC,EAAG,CAChD,KAAK,eAAiB,EAAQ,OAC9B,KAAK,OAAS,EAAQ,QAAU,qBAG5B,QAAO,CAAC,EAAe,EAAqC,CAGhE,IAAM,EAAM,KAAK,IAAI,EAAG,KAAK,KAAK,EAAY,KAAK,IAAI,CAAC,CAAC,EASzD,OARc,MAAM,KAAK,OAAO,KAAK,MAAO,CAC1C,GAAG,KAAK,UA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