@code-yeongyu/senpi 2026.9.23-5 → 2026.9.24-2

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 (315) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/dist/bundle/chunks/{anthropic-messages-77YBORJ5.js → anthropic-messages-UPLQFNTT.js} +2 -2
  3. package/dist/bundle/chunks/{app-server-command-BGT65PGC.js → app-server-command-UHPJ2C4D.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-PSESFNHN.js → azure-openai-responses-XAR2E66I.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-WXIRFRXY.js → chunk-2PLPSKHD.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-7PANH3NB.js → chunk-3WBSBDBX.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-BBOQ5H4W.js → chunk-6WBYI25N.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-RG3UEFSF.js → chunk-7DY7UYLL.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-VKBY4F76.js → chunk-BSOJHK4W.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-3XHWW7SQ.js → chunk-CLZVNQW3.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-ORCF262V.js → chunk-EJKCBRYK.js} +3 -3
  12. package/dist/bundle/chunks/chunk-J7IUURQ6.js +8 -0
  13. package/dist/bundle/chunks/{chunk-PSMTQDII.js → chunk-JRQSHZPP.js} +15 -9
  14. package/dist/bundle/chunks/{chunk-DUV3UFKX.js → chunk-MKAM7IRH.js} +1 -1
  15. package/dist/bundle/chunks/chunk-MO2U7YRX.js +11 -0
  16. package/dist/bundle/chunks/{chunk-ZEFQYQOU.js → chunk-NGHOUIPR.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-XDSQYM4F.js → chunk-NKVUDCGZ.js} +2 -2
  18. package/dist/bundle/chunks/{chunk-J3QXPP4T.js → chunk-ONR57UMO.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-TQDWU3ZQ.js → chunk-SYQVC7UM.js} +1 -1
  20. package/dist/bundle/chunks/chunk-TTHMOL5G.js +2 -0
  21. package/dist/bundle/chunks/{chunk-NNHFMZD5.js → chunk-UBPMXBOJ.js} +1 -1
  22. package/dist/bundle/chunks/chunk-WASCMT6Y.js +2 -0
  23. package/dist/bundle/chunks/{chunk-EN6KDFY2.js → chunk-WISJJQ4K.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-IVYZMSFY.js → chunk-WL5EQYNL.js} +1 -1
  25. package/dist/bundle/chunks/{chunk-LC6SZTVE.js → chunk-WTSAB6AE.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-HKE42SWX.js → chunk-Y54V65MS.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-3RN6BFG2.js → chunk-YBC274GY.js} +4 -4
  28. package/dist/bundle/chunks/{chunk-RRSND33J.js → chunk-YKU45B65.js} +54 -54
  29. package/dist/bundle/chunks/{chunk-WUYBEF7C.js → chunk-YWO3OBYK.js} +1 -1
  30. package/dist/bundle/chunks/cli-main-O5Y3TBID.js +3 -0
  31. package/dist/bundle/chunks/{google-generative-ai-YJHSZAY5.js → google-generative-ai-B5QMFONL.js} +1 -1
  32. package/dist/bundle/chunks/{google-vertex-JTFWEDNJ.js → google-vertex-O2TGMVWF.js} +1 -1
  33. package/dist/bundle/chunks/{help-fast-path-QXVCHTP3.js → help-fast-path-Y33OIZBU.js} +1 -1
  34. package/dist/bundle/chunks/{host-command-3PUZYQOK.js → host-command-WJOL27Q7.js} +1 -1
  35. package/dist/bundle/chunks/{host-lifecycle-OHPSU5VU.js → host-lifecycle-YBFXYFZP.js} +1 -1
  36. package/dist/bundle/chunks/{interactive-host-runtime-57LEAJPU.js → interactive-host-runtime-XVTF3NUD.js} +1 -1
  37. package/dist/bundle/chunks/interactive-mode-OO3NGM4G.js +2 -0
  38. package/dist/bundle/chunks/{list-tips-Z62FXPOJ.js → list-tips-EBRNBPBM.js} +1 -1
  39. package/dist/bundle/chunks/{mistral-conversations-VJPMPQ5T.js → mistral-conversations-AS3SAWPA.js} +1 -1
  40. package/dist/bundle/chunks/{multi-session-host-GFSDQQUJ.js → multi-session-host-6MKBBOKF.js} +1 -1
  41. package/dist/bundle/chunks/{openai-codex-responses-IQ35QACK.js → openai-codex-responses-CK7T4WNM.js} +1 -1
  42. package/dist/bundle/chunks/{openai-completions-74OLE55U.js → openai-completions-OPQKN7FH.js} +3 -3
  43. package/dist/bundle/chunks/openai-responses-QHWM3KPO.js +2 -0
  44. package/dist/bundle/chunks/{openrouter-images-T4GY3JYM.js → openrouter-images-MW5TXV7L.js} +1 -1
  45. package/dist/bundle/chunks/{package-manager-cli-J7244EJE.js → package-manager-cli-BMEWLAI2.js} +1 -1
  46. package/dist/bundle/chunks/{rotation-stream-CZT4TRPD.js → rotation-stream-ZFA6ELXJ.js} +1 -1
  47. package/dist/bundle/chunks/{rpc-mode-75CRTY24.js → rpc-mode-5653CV65.js} +1 -1
  48. package/dist/bundle/chunks/{session-picker-ZIBANFBQ.js → session-picker-PPYK56TA.js} +1 -1
  49. package/dist/bundle/chunks/session-worker.js +265 -259
  50. package/dist/bundle/cli.js +1 -1
  51. package/dist/bundle/index.js +1 -1
  52. package/dist/bundle/rpc-entry.js +1 -1
  53. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  54. package/dist/core/agent-session-runtime.js +13 -0
  55. package/dist/core/agent-session-runtime.js.map +1 -1
  56. package/dist/core/agent-session.d.ts +28 -0
  57. package/dist/core/agent-session.d.ts.map +1 -1
  58. package/dist/core/agent-session.js +75 -12
  59. package/dist/core/agent-session.js.map +1 -1
  60. package/dist/core/dynamic-prompt/build.d.ts +6 -1
  61. package/dist/core/dynamic-prompt/build.d.ts.map +1 -1
  62. package/dist/core/dynamic-prompt/build.js +0 -7
  63. package/dist/core/dynamic-prompt/build.js.map +1 -1
  64. package/dist/core/environment-context.d.ts +32 -0
  65. package/dist/core/environment-context.d.ts.map +1 -0
  66. package/dist/core/environment-context.js +63 -0
  67. package/dist/core/environment-context.js.map +1 -0
  68. package/dist/core/extensions/builtin/anthropic-subscription/session-sync.d.ts.map +1 -1
  69. package/dist/core/extensions/builtin/anthropic-subscription/session-sync.js +1 -15
  70. package/dist/core/extensions/builtin/anthropic-subscription/session-sync.js.map +1 -1
  71. package/dist/core/extensions/builtin/goal/cache-warm-renderer.js +3 -0
  72. package/dist/core/extensions/builtin/goal/cache-warm-renderer.js.map +1 -1
  73. package/dist/core/extensions/builtin/goal/cache-warm.d.ts +19 -2
  74. package/dist/core/extensions/builtin/goal/cache-warm.d.ts.map +1 -1
  75. package/dist/core/extensions/builtin/goal/cache-warm.js +28 -2
  76. package/dist/core/extensions/builtin/goal/cache-warm.js.map +1 -1
  77. package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts.map +1 -1
  78. package/dist/core/extensions/builtin/goal/monitor-continuation.js +4 -2
  79. package/dist/core/extensions/builtin/goal/monitor-continuation.js.map +1 -1
  80. package/dist/core/extensions/builtin/goal/parked-wait.js +2 -0
  81. package/dist/core/extensions/builtin/goal/parked-wait.js.map +1 -1
  82. package/dist/core/extensions/builtin/goal/prompt.js +1 -1
  83. package/dist/core/extensions/builtin/goal/prompt.js.map +1 -1
  84. package/dist/core/extensions/builtin/herdr/herdr-state.d.ts +5 -0
  85. package/dist/core/extensions/builtin/herdr/herdr-state.d.ts.map +1 -1
  86. package/dist/core/extensions/builtin/herdr/herdr-state.js +28 -3
  87. package/dist/core/extensions/builtin/herdr/herdr-state.js.map +1 -1
  88. package/dist/core/extensions/builtin/herdr/index.d.ts.map +1 -1
  89. package/dist/core/extensions/builtin/herdr/index.js +7 -1
  90. package/dist/core/extensions/builtin/herdr/index.js.map +1 -1
  91. package/dist/core/extensions/builtin/hooks/index.d.ts.map +1 -1
  92. package/dist/core/extensions/builtin/hooks/index.js +3 -15
  93. package/dist/core/extensions/builtin/hooks/index.js.map +1 -1
  94. package/dist/core/extensions/builtin/hooks/stop-lifecycle.d.ts +26 -0
  95. package/dist/core/extensions/builtin/hooks/stop-lifecycle.d.ts.map +1 -0
  96. package/dist/core/extensions/builtin/hooks/stop-lifecycle.js +88 -0
  97. package/dist/core/extensions/builtin/hooks/stop-lifecycle.js.map +1 -0
  98. package/dist/core/extensions/builtin/recommended-models/index.d.ts +1 -1
  99. package/dist/core/extensions/builtin/recommended-models/index.d.ts.map +1 -1
  100. package/dist/core/extensions/builtin/recommended-models/index.js +28 -10
  101. package/dist/core/extensions/builtin/recommended-models/index.js.map +1 -1
  102. package/dist/core/extensions/builtin/rules/commands.d.ts.map +1 -1
  103. package/dist/core/extensions/builtin/rules/commands.js +5 -1
  104. package/dist/core/extensions/builtin/rules/commands.js.map +1 -1
  105. package/dist/core/extensions/builtin/rules/index.d.ts.map +1 -1
  106. package/dist/core/extensions/builtin/rules/index.js +25 -3
  107. package/dist/core/extensions/builtin/rules/index.js.map +1 -1
  108. package/dist/core/extensions/builtin/rules/rules/constants.d.ts.map +1 -1
  109. package/dist/core/extensions/builtin/rules/rules/constants.js +22 -14
  110. package/dist/core/extensions/builtin/rules/rules/constants.js.map +1 -1
  111. package/dist/core/extensions/builtin/rules/rules/engine.d.ts.map +1 -1
  112. package/dist/core/extensions/builtin/rules/rules/engine.js +39 -9
  113. package/dist/core/extensions/builtin/rules/rules/engine.js.map +1 -1
  114. package/dist/core/extensions/builtin/rules/rules/finder.js +3 -0
  115. package/dist/core/extensions/builtin/rules/rules/finder.js.map +1 -1
  116. package/dist/core/extensions/builtin/rules/rules/project-root.d.ts +17 -0
  117. package/dist/core/extensions/builtin/rules/rules/project-root.d.ts.map +1 -1
  118. package/dist/core/extensions/builtin/rules/rules/project-root.js +67 -5
  119. package/dist/core/extensions/builtin/rules/rules/project-root.js.map +1 -1
  120. package/dist/core/extensions/builtin/rules/rules/types.d.ts +2 -2
  121. package/dist/core/extensions/builtin/rules/rules/types.d.ts.map +1 -1
  122. package/dist/core/extensions/builtin/rules/rules/types.js.map +1 -1
  123. package/dist/core/extensions/builtin/rules/ui/rules-banner.d.ts +3 -1
  124. package/dist/core/extensions/builtin/rules/ui/rules-banner.d.ts.map +1 -1
  125. package/dist/core/extensions/builtin/rules/ui/rules-banner.js +1 -1
  126. package/dist/core/extensions/builtin/rules/ui/rules-banner.js.map +1 -1
  127. package/dist/core/extensions/builtin/todotools/todo-storage.d.ts.map +1 -1
  128. package/dist/core/extensions/builtin/todotools/todo-storage.js +10 -2
  129. package/dist/core/extensions/builtin/todotools/todo-storage.js.map +1 -1
  130. package/dist/core/extensions/builtin/todotools/tools/todo.d.ts.map +1 -1
  131. package/dist/core/extensions/builtin/todotools/tools/todo.js +2 -1
  132. package/dist/core/extensions/builtin/todotools/tools/todo.js.map +1 -1
  133. package/dist/core/extensions/builtin/websearch/websearch/config.d.ts.map +1 -1
  134. package/dist/core/extensions/builtin/websearch/websearch/config.js +2 -0
  135. package/dist/core/extensions/builtin/websearch/websearch/config.js.map +1 -1
  136. package/dist/core/extensions/builtin/websearch/websearch/provider-endpoints.d.ts.map +1 -1
  137. package/dist/core/extensions/builtin/websearch/websearch/provider-endpoints.js +2 -0
  138. package/dist/core/extensions/builtin/websearch/websearch/provider-endpoints.js.map +1 -1
  139. package/dist/core/extensions/builtin/websearch/websearch/providers/kagi.d.ts +3 -0
  140. package/dist/core/extensions/builtin/websearch/websearch/providers/kagi.d.ts.map +1 -0
  141. package/dist/core/extensions/builtin/websearch/websearch/providers/kagi.js +34 -0
  142. package/dist/core/extensions/builtin/websearch/websearch/providers/kagi.js.map +1 -0
  143. package/dist/core/extensions/builtin/websearch/websearch/providers/serpdive.d.ts +3 -0
  144. package/dist/core/extensions/builtin/websearch/websearch/providers/serpdive.d.ts.map +1 -0
  145. package/dist/core/extensions/builtin/websearch/websearch/providers/serpdive.js +22 -0
  146. package/dist/core/extensions/builtin/websearch/websearch/providers/serpdive.js.map +1 -0
  147. package/dist/core/extensions/builtin/websearch/websearch/providers.d.ts.map +1 -1
  148. package/dist/core/extensions/builtin/websearch/websearch/providers.js +4 -0
  149. package/dist/core/extensions/builtin/websearch/websearch/providers.js.map +1 -1
  150. package/dist/core/extensions/builtin/websearch/websearch/types.d.ts +1 -1
  151. package/dist/core/extensions/builtin/websearch/websearch/types.d.ts.map +1 -1
  152. package/dist/core/extensions/builtin/websearch/websearch/types.js.map +1 -1
  153. package/dist/core/session-discovery.d.ts +9 -3
  154. package/dist/core/session-discovery.d.ts.map +1 -1
  155. package/dist/core/session-discovery.js +19 -8
  156. package/dist/core/session-discovery.js.map +1 -1
  157. package/dist/core/session-manager.d.ts.map +1 -1
  158. package/dist/core/session-manager.js +8 -4
  159. package/dist/core/session-manager.js.map +1 -1
  160. package/dist/core/session-summary-cache.d.ts +16 -3
  161. package/dist/core/session-summary-cache.d.ts.map +1 -1
  162. package/dist/core/session-summary-cache.js +19 -3
  163. package/dist/core/session-summary-cache.js.map +1 -1
  164. package/dist/core/session-summary-index-file.d.ts +38 -0
  165. package/dist/core/session-summary-index-file.d.ts.map +1 -0
  166. package/dist/core/session-summary-index-file.js +119 -0
  167. package/dist/core/session-summary-index-file.js.map +1 -0
  168. package/dist/core/session-summary-index.d.ts +52 -0
  169. package/dist/core/session-summary-index.d.ts.map +1 -0
  170. package/dist/core/session-summary-index.js +157 -0
  171. package/dist/core/session-summary-index.js.map +1 -0
  172. package/dist/core/session-summary.d.ts +21 -2
  173. package/dist/core/session-summary.d.ts.map +1 -1
  174. package/dist/core/session-summary.js +53 -14
  175. package/dist/core/session-summary.js.map +1 -1
  176. package/dist/core/timings.d.ts +1 -1
  177. package/dist/core/timings.d.ts.map +1 -1
  178. package/dist/core/timings.js.map +1 -1
  179. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  180. package/dist/core/tools/renderers/read.js +7 -2
  181. package/dist/core/tools/renderers/read.js.map +1 -1
  182. package/dist/core/tools/renderers/skill-read-path.d.ts +9 -0
  183. package/dist/core/tools/renderers/skill-read-path.d.ts.map +1 -0
  184. package/dist/core/tools/renderers/skill-read-path.js +49 -0
  185. package/dist/core/tools/renderers/skill-read-path.js.map +1 -0
  186. package/dist/main.d.ts.map +1 -1
  187. package/dist/main.js +7 -0
  188. package/dist/main.js.map +1 -1
  189. package/dist/modes/interactive/components/exploration-call.d.ts +1 -1
  190. package/dist/modes/interactive/components/exploration-call.d.ts.map +1 -1
  191. package/dist/modes/interactive/components/exploration-call.js +3 -1
  192. package/dist/modes/interactive/components/exploration-call.js.map +1 -1
  193. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  194. package/dist/modes/interactive/components/session-selector-search.js +32 -16
  195. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  196. package/dist/modes/interactive/components/session-selector-tree.d.ts +32 -0
  197. package/dist/modes/interactive/components/session-selector-tree.d.ts.map +1 -0
  198. package/dist/modes/interactive/components/session-selector-tree.js +82 -0
  199. package/dist/modes/interactive/components/session-selector-tree.js.map +1 -0
  200. package/dist/modes/interactive/components/session-selector.d.ts +1 -0
  201. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  202. package/dist/modes/interactive/components/session-selector.js +6 -71
  203. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  204. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  205. package/dist/modes/interactive/interactive-mode.js +4 -1
  206. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  207. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +32 -0
  208. package/node_modules/@code-yeongyu/senpi-codemode/README.md +8 -4
  209. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  210. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/AGENTS.md +1 -0
  211. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/code-preview.ts +31 -0
  212. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/display-code.ts +34 -131
  213. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/display-js-ast.ts +65 -0
  214. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/display-js-layout.ts +90 -0
  215. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/display-js-mask.ts +178 -0
  216. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/display-js.ts +100 -0
  217. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/display-python-script.ts +127 -0
  218. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/display-python.ts +150 -0
  219. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-request.ts +18 -4
  220. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool.ts +1 -1
  221. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/render.ts +9 -25
  222. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/types.ts +16 -9
  223. package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts +1 -1
  224. package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts.map +1 -1
  225. package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +22 -2
  226. package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js.map +1 -1
  227. package/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts.map +1 -1
  228. package/node_modules/@earendil-works/pi-agent-core/dist/agent.js +3 -1
  229. package/node_modules/@earendil-works/pi-agent-core/dist/agent.js.map +1 -1
  230. package/node_modules/@earendil-works/pi-agent-core/dist/tool-name-alias.d.ts +6 -0
  231. package/node_modules/@earendil-works/pi-agent-core/dist/tool-name-alias.d.ts.map +1 -1
  232. package/node_modules/@earendil-works/pi-agent-core/dist/tool-name-alias.js +6 -19
  233. package/node_modules/@earendil-works/pi-agent-core/dist/tool-name-alias.js.map +1 -1
  234. package/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +8 -0
  235. package/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts.map +1 -1
  236. package/node_modules/@earendil-works/pi-agent-core/dist/types.js.map +1 -1
  237. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  238. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-references.d.ts.map +1 -1
  239. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-references.js +8 -35
  240. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-references.js.map +1 -1
  241. package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.d.ts.map +1 -1
  242. package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +10 -6
  243. package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js.map +1 -1
  244. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.d.ts.map +1 -1
  245. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +4 -3
  246. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js.map +1 -1
  247. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts.map +1 -1
  248. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +53 -1
  249. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js.map +1 -1
  250. package/node_modules/@earendil-works/pi-ai/dist/api/openrouter-images.js +1 -1
  251. package/node_modules/@earendil-works/pi-ai/dist/api/openrouter-images.js.map +1 -1
  252. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts +30 -0
  253. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts.map +1 -1
  254. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +30 -0
  255. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js.map +1 -1
  256. package/node_modules/@earendil-works/pi-ai/dist/index.d.ts +2 -1
  257. package/node_modules/@earendil-works/pi-ai/dist/index.d.ts.map +1 -1
  258. package/node_modules/@earendil-works/pi-ai/dist/index.js +2 -1
  259. package/node_modules/@earendil-works/pi-ai/dist/index.js.map +1 -1
  260. package/node_modules/@earendil-works/pi-ai/dist/models.d.ts +6 -0
  261. package/node_modules/@earendil-works/pi-ai/dist/models.d.ts.map +1 -1
  262. package/node_modules/@earendil-works/pi-ai/dist/models.js +15 -0
  263. package/node_modules/@earendil-works/pi-ai/dist/models.js.map +1 -1
  264. package/node_modules/@earendil-works/pi-ai/dist/openai-responses-compat.d.ts +17 -0
  265. package/node_modules/@earendil-works/pi-ai/dist/openai-responses-compat.d.ts.map +1 -1
  266. package/node_modules/@earendil-works/pi-ai/dist/openai-responses-compat.js +4 -1
  267. package/node_modules/@earendil-works/pi-ai/dist/openai-responses-compat.js.map +1 -1
  268. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  269. package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  270. package/node_modules/@earendil-works/pi-ai/dist/providers/data/chatgpt-subscription.json +1 -1
  271. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  272. package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  273. package/node_modules/@earendil-works/pi-ai/dist/providers/data/google.json +1 -1
  274. package/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax-cn.json +1 -1
  275. package/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax.json +1 -1
  276. package/node_modules/@earendil-works/pi-ai/dist/providers/data/moonshotai-cn.json +1 -1
  277. package/node_modules/@earendil-works/pi-ai/dist/providers/data/moonshotai.json +1 -1
  278. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
  279. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  280. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  281. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
  282. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  283. package/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  284. package/node_modules/@earendil-works/pi-ai/dist/providers/data/venice.json +1 -1
  285. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  286. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +6 -0
  287. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts.map +1 -1
  288. package/node_modules/@earendil-works/pi-ai/dist/types.js.map +1 -1
  289. package/node_modules/@earendil-works/pi-ai/dist/utils/prompt-cache-ttl.d.ts +30 -0
  290. package/node_modules/@earendil-works/pi-ai/dist/utils/prompt-cache-ttl.d.ts.map +1 -1
  291. package/node_modules/@earendil-works/pi-ai/dist/utils/prompt-cache-ttl.js +71 -14
  292. package/node_modules/@earendil-works/pi-ai/dist/utils/prompt-cache-ttl.js.map +1 -1
  293. package/node_modules/@earendil-works/pi-ai/dist/utils/tool-name-match.d.ts +30 -0
  294. package/node_modules/@earendil-works/pi-ai/dist/utils/tool-name-match.d.ts.map +1 -0
  295. package/node_modules/@earendil-works/pi-ai/dist/utils/tool-name-match.js +71 -0
  296. package/node_modules/@earendil-works/pi-ai/dist/utils/tool-name-match.js.map +1 -0
  297. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  298. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  299. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  300. package/node_modules/@earendil-works/pi-tui/dist/fuzzy.d.ts +5 -0
  301. package/node_modules/@earendil-works/pi-tui/dist/fuzzy.d.ts.map +1 -1
  302. package/node_modules/@earendil-works/pi-tui/dist/fuzzy.js +7 -2
  303. package/node_modules/@earendil-works/pi-tui/dist/fuzzy.js.map +1 -1
  304. package/node_modules/@earendil-works/pi-tui/dist/index.d.ts +1 -1
  305. package/node_modules/@earendil-works/pi-tui/dist/index.d.ts.map +1 -1
  306. package/node_modules/@earendil-works/pi-tui/dist/index.js +1 -1
  307. package/node_modules/@earendil-works/pi-tui/dist/index.js.map +1 -1
  308. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  309. package/package.json +7 -7
  310. package/dist/bundle/chunks/chunk-KLDLZHHS.js +0 -11
  311. package/dist/bundle/chunks/chunk-LTIMMSDM.js +0 -8
  312. package/dist/bundle/chunks/chunk-XYM54ZWK.js +0 -2
  313. package/dist/bundle/chunks/cli-main-W55CWPEI.js +0 -3
  314. package/dist/bundle/chunks/interactive-mode-EDJZ4CSY.js +0 -2
  315. package/dist/bundle/chunks/openai-responses-7IGZSW33.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAUA,OAAO,EACN,oBAAoB,IAAI,oCAAoC,EAC5D,YAAY,EACZ,oBAAoB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAuBpD,SAAS,mBAAmB,CAAC,QAAwB;IACpD,OAAO,QAAQ,CAAC,MAAM,CACrB,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,CACrG,CAAC;AACH,CAAC;AAED,MAAM,WAAW,GAAG;IACnB,KAAK,EAAE,CAAC;IACR,MAAM,EAAE,CAAC;IACT,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,CAAC;IACb,WAAW,EAAE,CAAC;IACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;CACpE,CAAC;AAEF,MAAM,aAAa,GAAG;IACrB,EAAE,EAAE,SAAS;IACb,IAAI,EAAE,SAAS;IACf,GAAG,EAAE,SAAS;IACd,QAAQ,EAAE,SAAS;IACnB,OAAO,EAAE,EAAE;IACX,SAAS,EAAE,KAAK;IAChB,KAAK,EAAE,EAAE;IACT,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CA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K,CAAC,OAAO,CAAC,YAAY,CAAC;gBACvD,CAAC;gBACD,MAAM;YAEP,KAAK,WAAW;gBACf,IAAI,CAAC,MAAM,CAAC,gBAAgB,GAAG,SAAS,CAAC;gBACzC,MAAM;QACR,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC;QACtD,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;IACF,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,iBAAiB,CAAC,KAAiB,EAAE,SAAuB;QACjE,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC;QAC5D,IAAI,CAAC,YAAY,IAAI,CAAC,SAAS,IAAI,SAAS,KAAK,YAAY,CAAC;YAAE,OAAO;QACvE,MAAM,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;CACD","sourcesContent":["import type {\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tTransport,\n} from \"@earendil-works/pi-ai\";\nimport {\n\tbuildProviderContext as buildProviderContextFromAgentContext,\n\trunAgentLoop,\n\trunAgentLoopContinue,\n} from \"./agent-loop.ts\";\nimport { ProviderRetryWatchdogAbortError } from \"./assistant-terminal-state.ts\";\nimport { getDefaultStreamFn } from \"./stream-fn.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tPrepareNextTurnContext,\n\tQueueMode,\n\tShouldStopAfterTurnContext,\n\tStreamFn,\n\tThinkingLevel,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\treasoningBaseline: initialState?.reasoningBaseline,\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext, signal?: AbortSignal) => boolean | Promise<boolean>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprepareNextTurnWithContext?: (\n\t\tcontext: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\ttimeoutMs?: number;\n\tstreamStartTimeoutMs?: number;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n\tremovedToolHints?: Record<string, string>;\n\tresolveUnknownToolCall?: AgentLoopConfig[\"resolveUnknownToolCall\"];\n\tabortServerSideFallback?: boolean;\n\t/** Cursor exec-channel tool handlers; see {@link AgentLoopConfig.cursorExecHandlers}. */\n\tcursorExecHandlers?: AgentLoopConfig[\"cursorExecHandlers\"];\n}\n\nexport interface AgentContinuationOptions {\n\t/** Keep queued steering and follow-up input out of the continuation's first provider request only. */\n\tdeferQueuedMessages?: boolean;\n\t/** Override the provider stream idle timeout for the continuation's first provider request only. */\n\ttimeoutMs?: number;\n\t/** Override the provider stream-start timeout for the continuation's first provider request only. */\n\tstreamStartTimeoutMs?: number;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tprivate clearGeneration = 0;\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tgetClearGeneration(): number {\n\t\treturn this.clearGeneration;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tprepend(messages: AgentMessage[]): void {\n\t\tthis.messages = [...messages, ...this.messages];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t\tthis.clearGeneration++;\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n\tsuppressQueuedMessageDrain: boolean;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFunction: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic shouldStopAfterTurn?: (\n\t\tcontext: ShouldStopAfterTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => boolean | Promise<boolean>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tpublic prepareNextTurnWithContext?: (\n\t\tcontext: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\tpublic timeoutMs?: number;\n\t/** Optional bound on the wait for the first provider stream event. */\n\tpublic streamStartTimeoutMs?: number;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\t/** Migration guidance returned when a removed tool name is called. */\n\tpublic removedToolHints: Record<string, string>;\n\t/** Optional call-time resolver for tools absent from the request context. */\n\tpublic resolveUnknownToolCall?: AgentLoopConfig[\"resolveUnknownToolCall\"];\n\t/** Forwarded to the stream function; providers without server-side fallback ignore it. */\n\tpublic abortServerSideFallback?: boolean;\n\t/** Cursor exec-channel tool handlers; see {@link AgentLoopConfig.cursorExecHandlers}. */\n\tpublic cursorExecHandlers?: AgentLoopConfig[\"cursorExecHandlers\"];\n\n\tasync buildProviderContext(context: AgentContext, signal?: AbortSignal): Promise<Context> {\n\t\treturn buildProviderContextFromAgentContext(\n\t\t\tcontext,\n\t\t\t{ convertToLlm: this.convertToLlm, transformContext: this.transformContext },\n\t\t\tsignal,\n\t\t);\n\t}\n\n\tconstructor(options: AgentOptions) {\n\t\t// Older compiled consumers may omit options or streamFn even though the current API requires them.\n\t\tconst runtimeOptions: Partial<AgentOptions> = options ?? {};\n\t\tthis._state = createMutableAgentState(runtimeOptions.initialState);\n\t\tthis.convertToLlm = runtimeOptions.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = runtimeOptions.transformContext;\n\t\tthis.streamFunction = runtimeOptions.streamFn ?? getDefaultStreamFn();\n\t\tthis.getApiKey = runtimeOptions.getApiKey;\n\t\tthis.onPayload = runtimeOptions.onPayload;\n\t\tthis.onResponse = runtimeOptions.onResponse;\n\t\tthis.beforeToolCall = runtimeOptions.beforeToolCall;\n\t\tthis.afterToolCall = runtimeOptions.afterToolCall;\n\t\tthis.shouldStopAfterTurn = runtimeOptions.shouldStopAfterTurn;\n\t\tthis.prepareNextTurn = runtimeOptions.prepareNextTurn;\n\t\tthis.prepareNextTurnWithContext = runtimeOptions.prepareNextTurnWithContext;\n\t\tthis.steeringQueue = new PendingMessageQueue(runtimeOptions.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(runtimeOptions.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = runtimeOptions.sessionId;\n\t\tthis.thinkingBudgets = runtimeOptions.thinkingBudgets;\n\t\tthis.transport = runtimeOptions.transport ?? \"auto\";\n\t\tthis.timeoutMs = runtimeOptions.timeoutMs;\n\t\tthis.streamStartTimeoutMs = runtimeOptions.streamStartTimeoutMs;\n\t\tthis.maxRetryDelayMs = runtimeOptions.maxRetryDelayMs;\n\t\tthis.toolExecution = runtimeOptions.toolExecution ?? \"parallel\";\n\t\tthis.removedToolHints = runtimeOptions.removedToolHints ?? {};\n\t\tthis.resolveUnknownToolCall = runtimeOptions.resolveUnknownToolCall;\n\t\tthis.abortServerSideFallback = runtimeOptions.abortServerSideFallback;\n\t\tthis.cursorExecHandlers = runtimeOptions.cursorExecHandlers;\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(reason?: unknown): void {\n\t\tthis.activeRun?.abortController.abort(reason);\n\t}\n\n\t/**\n\t * Keep queued steering and follow-up messages for an external owner after\n\t * this run reaches agent_end, without changing the active abort signal.\n\t * This is ownership suppression for one active run; terminal error/abort\n\t * parking is a separate stop-reason policy enforced by the run lifecycle.\n\t */\n\tsuppressQueuedMessageDrain(): void {\n\t\tif (this.activeRun) {\n\t\t\tthis.activeRun.suppressQueuedMessageDrain = true;\n\t\t}\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before resetting.\");\n\t\t}\n\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/**\n\t * Continue by delivering queued input first when a compaction leaves custom context at the tail.\n\t * Queue-first recovery takes precedence over `deferQueuedMessages`: the selected queued message is\n\t * the continuation input, while timeout overrides still apply to its first provider request.\n\t */\n\tasync continueWithQueuedMessages(options: AgentContinuationOptions = {}): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tif (this._state.messages[this._state.messages.length - 1]?.role === \"assistant\") {\n\t\t\tawait this.continue(options);\n\t\t\treturn;\n\t\t}\n\n\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\tif (queuedSteering.length > 0) {\n\t\t\tawait this.runPromptMessages(queuedSteering, {\n\t\t\t\tskipInitialSteeringPoll: true,\n\t\t\t\tinitialRequestTimeoutMs: options.timeoutMs,\n\t\t\t\tinitialRequestStreamStartTimeoutMs: options.streamStartTimeoutMs,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\tif (queuedFollowUps.length > 0) {\n\t\t\tawait this.runPromptMessages(queuedFollowUps, {\n\t\t\t\tinitialRequestTimeoutMs: options.timeoutMs,\n\t\t\t\tinitialRequestStreamStartTimeoutMs: options.streamStartTimeoutMs,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.continue(options);\n\t}\n\n\t/**\n\t * Continue from the current transcript. The last message must be a user or tool-result message.\n\t * Queue deferral and timeout overrides apply only to the first provider request; later requests in\n\t * the same run and later runs use the configured Agent defaults.\n\t */\n\tasync continue(options: AgentContinuationOptions = {}): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, {\n\t\t\t\t\tskipInitialSteeringPoll: true,\n\t\t\t\t\tinitialRequestTimeoutMs: options.timeoutMs,\n\t\t\t\t\tinitialRequestStreamStartTimeoutMs: options.streamStartTimeoutMs,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps, {\n\t\t\t\t\tinitialRequestTimeoutMs: options.timeoutMs,\n\t\t\t\t\tinitialRequestStreamStartTimeoutMs: options.streamStartTimeoutMs,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this.runContinuation(options);\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: {\n\t\t\tskipInitialSteeringPoll?: boolean;\n\t\t\tinitialRequestTimeoutMs?: number;\n\t\t\tinitialRequestStreamStartTimeoutMs?: number;\n\t\t} = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(options: AgentContinuationOptions = {}): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig({\n\t\t\t\t\tskipInitialSteeringPoll: options.deferQueuedMessages,\n\t\t\t\t\tinitialRequestTimeoutMs: options.timeoutMs,\n\t\t\t\t\tinitialRequestStreamStartTimeoutMs: options.streamStartTimeoutMs,\n\t\t\t\t}),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(\n\t\toptions: {\n\t\t\tskipInitialSteeringPoll?: boolean;\n\t\t\tinitialRequestTimeoutMs?: number;\n\t\t\tinitialRequestStreamStartTimeoutMs?: number;\n\t\t} = {},\n\t): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\tlet steeringQueueGeneration = this.steeringQueue.getClearGeneration();\n\t\tlet followUpQueueGeneration = this.followUpQueue.getClearGeneration();\n\t\tconst shouldStopAfterTurn = this.shouldStopAfterTurn;\n\t\tconst reasoning = (this._state.reasoningBaseline as ThinkingLevel | undefined) ?? this._state.thinkingLevel;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: reasoning === \"off\" ? undefined : reasoning,\n\t\t\tthinkingSelection: this._state.thinkingSelection,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\ttimeoutMs: this.timeoutMs,\n\t\t\tstreamStartTimeoutMs: this.streamStartTimeoutMs,\n\t\t\tinitialRequestTimeoutMs: options.initialRequestTimeoutMs,\n\t\t\tinitialRequestStreamStartTimeoutMs: options.initialRequestStreamStartTimeoutMs,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\tabortServerSideFallback: this.abortServerSideFallback,\n\t\t\tcursorExecHandlers: this.cursorExecHandlers,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tremovedToolHints: this.removedToolHints,\n\t\t\tresolveUnknownToolCall: this.resolveUnknownToolCall,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tshouldStopAfterTurn: shouldStopAfterTurn\n\t\t\t\t? async (context) => await shouldStopAfterTurn(context, this.signal)\n\t\t\t\t: undefined,\n\t\t\tprepareNextTurn:\n\t\t\t\tthis.prepareNextTurnWithContext || this.prepareNextTurn\n\t\t\t\t\t? async (context) => {\n\t\t\t\t\t\t\tif (this.prepareNextTurnWithContext) {\n\t\t\t\t\t\t\t\treturn await this.prepareNextTurnWithContext(context, this.signal);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn await this.prepareNextTurn?.(this.signal);\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\tsteeringQueueGeneration = this.steeringQueue.getClearGeneration();\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => {\n\t\t\t\tfollowUpQueueGeneration = this.followUpQueue.getClearGeneration();\n\t\t\t\treturn this.followUpQueue.drain();\n\t\t\t},\n\t\t\trestorePendingMessages: (queue, messages) => {\n\t\t\t\tif (queue === \"steering\") {\n\t\t\t\t\tif (this.steeringQueue.getClearGeneration() !== steeringQueueGeneration) return;\n\t\t\t\t\tthis.steeringQueue.prepend(messages);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (this.followUpQueue.getClearGeneration() !== followUpQueueGeneration) return;\n\t\t\t\tthis.followUpQueue.prepend(messages);\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController, suppressQueuedMessageDrain: false };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t\t// A provider-returned terminal error/abort has no safe implicit owner for\n\t\t\t// queued work. Park it until an external retry/compaction owner continues,\n\t\t\t// or until a later admitted prompt drains it through the normal queue poll.\n\t\t\twhile (\n\t\t\t\t!abortController.signal.aborted &&\n\t\t\t\t!this.activeRun?.suppressQueuedMessageDrain &&\n\t\t\t\tthis.canDrainQueuedMessagesAfterRun() &&\n\t\t\t\tthis.hasQueuedMessages()\n\t\t\t) {\n\t\t\t\tawait this.runQueuedMessagesAfterAgentEnd(abortController.signal);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate canDrainQueuedMessagesAfterRun(): boolean {\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\treturn (\n\t\t\tlastMessage?.role !== \"assistant\" ||\n\t\t\t(lastMessage.stopReason !== \"error\" && lastMessage.stopReason !== \"aborted\")\n\t\t);\n\t}\n\n\tprivate async runQueuedMessagesAfterAgentEnd(signal: AbortSignal): Promise<void> {\n\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\tif (queuedSteering.length > 0) {\n\t\t\tawait runAgentLoop(\n\t\t\t\tqueuedSteering,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig({ skipInitialSteeringPoll: true }),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\tif (queuedFollowUps.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait runAgentLoop(\n\t\t\tqueuedFollowUps,\n\t\t\tthis.createContextSnapshot(),\n\t\t\tthis.createLoopConfig(),\n\t\t\t(event) => this.processEvents(event),\n\t\t\tsignal,\n\t\t\tthis.streamFunction,\n\t\t);\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t...(error instanceof ProviderRetryWatchdogAbortError ? { abortSource: \"provider\" as const } : {}),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n\n\t/**\n\t * Emit a host-generated event through the normal listener pipeline.\n\t *\n\t * Used by the Cursor exec bridge: bridge-run tools execute inside the\n\t * provider stream, outside the loop's executor, so their\n\t * `tool_execution_start`/`tool_execution_end` lifecycle must be injected\n\t * here or the live tool card for a synthesized call never resolves.\n\t * A bridge execution may settle after an aborted run has already ended; its\n\t * late lifecycle event belongs to that finished run and must be discarded.\n\t */\n\tasync emitExternalEvent(event: AgentEvent, runSignal?: AbortSignal): Promise<void> {\n\t\tconst activeSignal = this.activeRun?.abortController.signal;\n\t\tif (!activeSignal || (runSignal && runSignal !== activeSignal)) return;\n\t\tawait this.processEvents(event);\n\t}\n}\n"]}
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAUA,OAAO,EACN,oBAAoB,IAAI,oCAAoC,EAC5D,YAAY,EACZ,oBAAoB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,+BAA+B,EA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,CAAC,MAAM,CAAC,gBAAgB,GAAG,SAAS,CAAC;gBACzC,MAAM;QACR,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC;QACtD,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;IACF,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,iBAAiB,CAAC,KAAiB,EAAE,SAAuB;QACjE,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC;QAC5D,IAAI,CAAC,YAAY,IAAI,CAAC,SAAS,IAAI,SAAS,KAAK,YAAY,CAAC;YAAE,OAAO;QACvE,MAAM,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;CACD","sourcesContent":["import type {\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tTransport,\n} from \"@earendil-works/pi-ai\";\nimport {\n\tbuildProviderContext as buildProviderContextFromAgentContext,\n\trunAgentLoop,\n\trunAgentLoopContinue,\n} from \"./agent-loop.ts\";\nimport { ProviderRetryWatchdogAbortError } from \"./assistant-terminal-state.ts\";\nimport { getDefaultStreamFn } from \"./stream-fn.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tPrepareNextTurnContext,\n\tQueueMode,\n\tShouldStopAfterTurnContext,\n\tStreamFn,\n\tThinkingLevel,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\treasoningBaseline: initialState?.reasoningBaseline,\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tdeclaredTools: initialState?.declaredTools?.slice(),\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext, signal?: AbortSignal) => boolean | Promise<boolean>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprepareNextTurnWithContext?: (\n\t\tcontext: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\ttimeoutMs?: number;\n\tstreamStartTimeoutMs?: number;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n\tremovedToolHints?: Record<string, string>;\n\tresolveUnknownToolCall?: AgentLoopConfig[\"resolveUnknownToolCall\"];\n\tabortServerSideFallback?: boolean;\n\t/** Cursor exec-channel tool handlers; see {@link AgentLoopConfig.cursorExecHandlers}. */\n\tcursorExecHandlers?: AgentLoopConfig[\"cursorExecHandlers\"];\n}\n\nexport interface AgentContinuationOptions {\n\t/** Keep queued steering and follow-up input out of the continuation's first provider request only. */\n\tdeferQueuedMessages?: boolean;\n\t/** Override the provider stream idle timeout for the continuation's first provider request only. */\n\ttimeoutMs?: number;\n\t/** Override the provider stream-start timeout for the continuation's first provider request only. */\n\tstreamStartTimeoutMs?: number;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tprivate clearGeneration = 0;\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tgetClearGeneration(): number {\n\t\treturn this.clearGeneration;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tprepend(messages: AgentMessage[]): void {\n\t\tthis.messages = [...messages, ...this.messages];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t\tthis.clearGeneration++;\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n\tsuppressQueuedMessageDrain: boolean;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFunction: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic shouldStopAfterTurn?: (\n\t\tcontext: ShouldStopAfterTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => boolean | Promise<boolean>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tpublic prepareNextTurnWithContext?: (\n\t\tcontext: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\tpublic timeoutMs?: number;\n\t/** Optional bound on the wait for the first provider stream event. */\n\tpublic streamStartTimeoutMs?: number;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\t/** Migration guidance returned when a removed tool name is called. */\n\tpublic removedToolHints: Record<string, string>;\n\t/** Optional call-time resolver for tools absent from the request context. */\n\tpublic resolveUnknownToolCall?: AgentLoopConfig[\"resolveUnknownToolCall\"];\n\t/** Forwarded to the stream function; providers without server-side fallback ignore it. */\n\tpublic abortServerSideFallback?: boolean;\n\t/** Cursor exec-channel tool handlers; see {@link AgentLoopConfig.cursorExecHandlers}. */\n\tpublic cursorExecHandlers?: AgentLoopConfig[\"cursorExecHandlers\"];\n\n\tasync buildProviderContext(context: AgentContext, signal?: AbortSignal): Promise<Context> {\n\t\treturn buildProviderContextFromAgentContext(\n\t\t\tcontext,\n\t\t\t{ convertToLlm: this.convertToLlm, transformContext: this.transformContext, model: this._state.model },\n\t\t\tsignal,\n\t\t);\n\t}\n\n\tconstructor(options: AgentOptions) {\n\t\t// Older compiled consumers may omit options or streamFn even though the current API requires them.\n\t\tconst runtimeOptions: Partial<AgentOptions> = options ?? {};\n\t\tthis._state = createMutableAgentState(runtimeOptions.initialState);\n\t\tthis.convertToLlm = runtimeOptions.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = runtimeOptions.transformContext;\n\t\tthis.streamFunction = runtimeOptions.streamFn ?? getDefaultStreamFn();\n\t\tthis.getApiKey = runtimeOptions.getApiKey;\n\t\tthis.onPayload = runtimeOptions.onPayload;\n\t\tthis.onResponse = runtimeOptions.onResponse;\n\t\tthis.beforeToolCall = runtimeOptions.beforeToolCall;\n\t\tthis.afterToolCall = runtimeOptions.afterToolCall;\n\t\tthis.shouldStopAfterTurn = runtimeOptions.shouldStopAfterTurn;\n\t\tthis.prepareNextTurn = runtimeOptions.prepareNextTurn;\n\t\tthis.prepareNextTurnWithContext = runtimeOptions.prepareNextTurnWithContext;\n\t\tthis.steeringQueue = new PendingMessageQueue(runtimeOptions.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(runtimeOptions.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = runtimeOptions.sessionId;\n\t\tthis.thinkingBudgets = runtimeOptions.thinkingBudgets;\n\t\tthis.transport = runtimeOptions.transport ?? \"auto\";\n\t\tthis.timeoutMs = runtimeOptions.timeoutMs;\n\t\tthis.streamStartTimeoutMs = runtimeOptions.streamStartTimeoutMs;\n\t\tthis.maxRetryDelayMs = runtimeOptions.maxRetryDelayMs;\n\t\tthis.toolExecution = runtimeOptions.toolExecution ?? \"parallel\";\n\t\tthis.removedToolHints = runtimeOptions.removedToolHints ?? {};\n\t\tthis.resolveUnknownToolCall = runtimeOptions.resolveUnknownToolCall;\n\t\tthis.abortServerSideFallback = runtimeOptions.abortServerSideFallback;\n\t\tthis.cursorExecHandlers = runtimeOptions.cursorExecHandlers;\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(reason?: unknown): void {\n\t\tthis.activeRun?.abortController.abort(reason);\n\t}\n\n\t/**\n\t * Keep queued steering and follow-up messages for an external owner after\n\t * this run reaches agent_end, without changing the active abort signal.\n\t * This is ownership suppression for one active run; terminal error/abort\n\t * parking is a separate stop-reason policy enforced by the run lifecycle.\n\t */\n\tsuppressQueuedMessageDrain(): void {\n\t\tif (this.activeRun) {\n\t\t\tthis.activeRun.suppressQueuedMessageDrain = true;\n\t\t}\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before resetting.\");\n\t\t}\n\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/**\n\t * Continue by delivering queued input first when a compaction leaves custom context at the tail.\n\t * Queue-first recovery takes precedence over `deferQueuedMessages`: the selected queued message is\n\t * the continuation input, while timeout overrides still apply to its first provider request.\n\t */\n\tasync continueWithQueuedMessages(options: AgentContinuationOptions = {}): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tif (this._state.messages[this._state.messages.length - 1]?.role === \"assistant\") {\n\t\t\tawait this.continue(options);\n\t\t\treturn;\n\t\t}\n\n\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\tif (queuedSteering.length > 0) {\n\t\t\tawait this.runPromptMessages(queuedSteering, {\n\t\t\t\tskipInitialSteeringPoll: true,\n\t\t\t\tinitialRequestTimeoutMs: options.timeoutMs,\n\t\t\t\tinitialRequestStreamStartTimeoutMs: options.streamStartTimeoutMs,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\tif (queuedFollowUps.length > 0) {\n\t\t\tawait this.runPromptMessages(queuedFollowUps, {\n\t\t\t\tinitialRequestTimeoutMs: options.timeoutMs,\n\t\t\t\tinitialRequestStreamStartTimeoutMs: options.streamStartTimeoutMs,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.continue(options);\n\t}\n\n\t/**\n\t * Continue from the current transcript. The last message must be a user or tool-result message.\n\t * Queue deferral and timeout overrides apply only to the first provider request; later requests in\n\t * the same run and later runs use the configured Agent defaults.\n\t */\n\tasync continue(options: AgentContinuationOptions = {}): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, {\n\t\t\t\t\tskipInitialSteeringPoll: true,\n\t\t\t\t\tinitialRequestTimeoutMs: options.timeoutMs,\n\t\t\t\t\tinitialRequestStreamStartTimeoutMs: options.streamStartTimeoutMs,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps, {\n\t\t\t\t\tinitialRequestTimeoutMs: options.timeoutMs,\n\t\t\t\t\tinitialRequestStreamStartTimeoutMs: options.streamStartTimeoutMs,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this.runContinuation(options);\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: {\n\t\t\tskipInitialSteeringPoll?: boolean;\n\t\t\tinitialRequestTimeoutMs?: number;\n\t\t\tinitialRequestStreamStartTimeoutMs?: number;\n\t\t} = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(options: AgentContinuationOptions = {}): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig({\n\t\t\t\t\tskipInitialSteeringPoll: options.deferQueuedMessages,\n\t\t\t\t\tinitialRequestTimeoutMs: options.timeoutMs,\n\t\t\t\t\tinitialRequestStreamStartTimeoutMs: options.streamStartTimeoutMs,\n\t\t\t\t}),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t\t...(this._state.declaredTools ? { declaredTools: this._state.declaredTools.slice() } : {}),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(\n\t\toptions: {\n\t\t\tskipInitialSteeringPoll?: boolean;\n\t\t\tinitialRequestTimeoutMs?: number;\n\t\t\tinitialRequestStreamStartTimeoutMs?: number;\n\t\t} = {},\n\t): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\tlet steeringQueueGeneration = this.steeringQueue.getClearGeneration();\n\t\tlet followUpQueueGeneration = this.followUpQueue.getClearGeneration();\n\t\tconst shouldStopAfterTurn = this.shouldStopAfterTurn;\n\t\tconst reasoning = (this._state.reasoningBaseline as ThinkingLevel | undefined) ?? this._state.thinkingLevel;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: reasoning === \"off\" ? undefined : reasoning,\n\t\t\tthinkingSelection: this._state.thinkingSelection,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\ttimeoutMs: this.timeoutMs,\n\t\t\tstreamStartTimeoutMs: this.streamStartTimeoutMs,\n\t\t\tinitialRequestTimeoutMs: options.initialRequestTimeoutMs,\n\t\t\tinitialRequestStreamStartTimeoutMs: options.initialRequestStreamStartTimeoutMs,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\tabortServerSideFallback: this.abortServerSideFallback,\n\t\t\tcursorExecHandlers: this.cursorExecHandlers,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tremovedToolHints: this.removedToolHints,\n\t\t\tresolveUnknownToolCall: this.resolveUnknownToolCall,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tshouldStopAfterTurn: shouldStopAfterTurn\n\t\t\t\t? async (context) => await shouldStopAfterTurn(context, this.signal)\n\t\t\t\t: undefined,\n\t\t\tprepareNextTurn:\n\t\t\t\tthis.prepareNextTurnWithContext || this.prepareNextTurn\n\t\t\t\t\t? async (context) => {\n\t\t\t\t\t\t\tif (this.prepareNextTurnWithContext) {\n\t\t\t\t\t\t\t\treturn await this.prepareNextTurnWithContext(context, this.signal);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn await this.prepareNextTurn?.(this.signal);\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\tsteeringQueueGeneration = this.steeringQueue.getClearGeneration();\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => {\n\t\t\t\tfollowUpQueueGeneration = this.followUpQueue.getClearGeneration();\n\t\t\t\treturn this.followUpQueue.drain();\n\t\t\t},\n\t\t\trestorePendingMessages: (queue, messages) => {\n\t\t\t\tif (queue === \"steering\") {\n\t\t\t\t\tif (this.steeringQueue.getClearGeneration() !== steeringQueueGeneration) return;\n\t\t\t\t\tthis.steeringQueue.prepend(messages);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (this.followUpQueue.getClearGeneration() !== followUpQueueGeneration) return;\n\t\t\t\tthis.followUpQueue.prepend(messages);\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController, suppressQueuedMessageDrain: false };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t\t// A provider-returned terminal error/abort has no safe implicit owner for\n\t\t\t// queued work. Park it until an external retry/compaction owner continues,\n\t\t\t// or until a later admitted prompt drains it through the normal queue poll.\n\t\t\twhile (\n\t\t\t\t!abortController.signal.aborted &&\n\t\t\t\t!this.activeRun?.suppressQueuedMessageDrain &&\n\t\t\t\tthis.canDrainQueuedMessagesAfterRun() &&\n\t\t\t\tthis.hasQueuedMessages()\n\t\t\t) {\n\t\t\t\tawait this.runQueuedMessagesAfterAgentEnd(abortController.signal);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate canDrainQueuedMessagesAfterRun(): boolean {\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\treturn (\n\t\t\tlastMessage?.role !== \"assistant\" ||\n\t\t\t(lastMessage.stopReason !== \"error\" && lastMessage.stopReason !== \"aborted\")\n\t\t);\n\t}\n\n\tprivate async runQueuedMessagesAfterAgentEnd(signal: AbortSignal): Promise<void> {\n\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\tif (queuedSteering.length > 0) {\n\t\t\tawait runAgentLoop(\n\t\t\t\tqueuedSteering,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig({ skipInitialSteeringPoll: true }),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\tif (queuedFollowUps.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait runAgentLoop(\n\t\t\tqueuedFollowUps,\n\t\t\tthis.createContextSnapshot(),\n\t\t\tthis.createLoopConfig(),\n\t\t\t(event) => this.processEvents(event),\n\t\t\tsignal,\n\t\t\tthis.streamFunction,\n\t\t);\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t...(error instanceof ProviderRetryWatchdogAbortError ? { abortSource: \"provider\" as const } : {}),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n\n\t/**\n\t * Emit a host-generated event through the normal listener pipeline.\n\t *\n\t * Used by the Cursor exec bridge: bridge-run tools execute inside the\n\t * provider stream, outside the loop's executor, so their\n\t * `tool_execution_start`/`tool_execution_end` lifecycle must be injected\n\t * here or the live tool card for a synthesized call never resolves.\n\t * A bridge execution may settle after an aborted run has already ended; its\n\t * late lifecycle event belongs to that finished run and must be discarded.\n\t */\n\tasync emitExternalEvent(event: AgentEvent, runSignal?: AbortSignal): Promise<void> {\n\t\tconst activeSignal = this.activeRun?.abortController.signal;\n\t\tif (!activeSignal || (runSignal && runSignal !== activeSignal)) return;\n\t\tawait this.processEvents(event);\n\t}\n}\n"]}
@@ -1,4 +1,10 @@
1
1
  import type { AgentContext, AgentLoopConfig, AgentTool, AgentToolCall, AgentToolResult } from "./types.ts";
2
+ /**
3
+ * A model can call a tool by a name it was never registered under: recased,
4
+ * under a gateway namespace (`mcp__<id>__<Name>`, any case), or without the
5
+ * namespace a registered tool carries. The shared matcher resolves such a name
6
+ * only when exactly one available tool matches; it never guesses.
7
+ */
2
8
  export declare function resolveToolNameAlias(requested: string, available: Iterable<string>): string | undefined;
3
9
  export declare function toolNameCorrectionNotice(requested: string, resolved: string): string;
4
10
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"tool-name-alias.d.ts","sourceRoot":"","sources":["../src/tool-name-alias.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,SAAS,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAgB3G,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,MAAM,GAAG,SAAS,CAQvG;AAED,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEpF;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CACpC,cAAc,EAAE,YAAY,EAC5B,QAAQ,EAAE,aAAa,EACvB,MAAM,EAAE,eAAe,GACrB,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CAWhC;AAED,wBAAgB,sBAAsB,CACrC,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,EAChC,aAAa,EAAE,MAAM,EACrB,YAAY,EAAE,MAAM,GAClB,eAAe,CAAC,OAAO,CAAC,CAS1B"}
1
+ {"version":3,"file":"tool-name-alias.d.ts","sourceRoot":"","sources":["../src/tool-name-alias.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,SAAS,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE3G;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,MAAM,GAAG,SAAS,CAEvG;AAED,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEpF;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CACpC,cAAc,EAAE,YAAY,EAC5B,QAAQ,EAAE,aAAa,EACvB,MAAM,EAAE,eAAe,GACrB,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CAWhC;AAED,wBAAgB,sBAAsB,CACrC,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,EAChC,aAAa,EAAE,MAAM,EACrB,YAAY,EAAE,MAAM,GAClB,eAAe,CAAC,OAAO,CAAC,CAS1B"}
@@ -1,25 +1,12 @@
1
+ import { resolveToolNameMatch } from "@earendil-works/pi-ai/utils/tool-name-match";
1
2
  /**
2
- * Some provider wire paths show the model non-native tools as
3
- * `mcp__<id>__<Name>` (recased, under a namespace senpi never defined), and a
4
- * model can carry that shape into a call for a tool it learned by its bare
5
- * name. Resolve such a call only when exactly one available tool matches after
6
- * stripping the namespace and folding case and `-`/`_` separators; never guess
7
- * between two candidates.
3
+ * A model can call a tool by a name it was never registered under: recased,
4
+ * under a gateway namespace (`mcp__<id>__<Name>`, any case), or without the
5
+ * namespace a registered tool carries. The shared matcher resolves such a name
6
+ * only when exactly one available tool matches; it never guesses.
8
7
  */
9
- const GATEWAY_TOOL_NAMESPACE = /^mcp__[^_]+__(.+)$/;
10
- function foldToolName(name) {
11
- return name.toLowerCase().replaceAll(/[-_]/g, "");
12
- }
13
8
  export function resolveToolNameAlias(requested, available) {
14
- const names = [...new Set(available)];
15
- if (names.includes(requested))
16
- return requested;
17
- const unnamespaced = GATEWAY_TOOL_NAMESPACE.exec(requested)?.[1] ?? requested;
18
- if (names.includes(unnamespaced))
19
- return unnamespaced;
20
- const key = foldToolName(unnamespaced);
21
- const matches = names.filter((name) => foldToolName(name) === key);
22
- return matches.length === 1 ? matches[0] : undefined;
9
+ return resolveToolNameMatch(requested, available);
23
10
  }
24
11
  export function toolNameCorrectionNotice(requested, resolved) {
25
12
  return `[auto-corrected] no tool is named "${requested}"; ran "${resolved}". Call tools by their exact listed name.`;
@@ -1 +1 @@
1
- {"version":3,"file":"tool-name-alias.js","sourceRoot":"","sources":["../src/tool-name-alias.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,MAAM,sBAAsB,GAAG,oBAAoB,CAAC;AAEpD,SAAS,YAAY,CAAC,IAAY;IACjC,OAAO,IAAI,CAAC,WAAW,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AACnD,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,SAAiB,EAAE,SAA2B;IAClF,MAAM,KAAK,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;IACtC,IAAI,KAAK,CAAC,QAAQ,CAAC,SAAS,CAAC;QAAE,OAAO,SAAS,CAAC;IAChD,MAAM,YAAY,GAAG,sBAAsB,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,SAAS,CAAC;IAC9E,IAAI,KAAK,CAAC,QAAQ,CAAC,YAAY,CAAC;QAAE,OAAO,YAAY,CAAC;IACtD,MAAM,GAAG,GAAG,YAAY,CAAC,YAAY,CAAC,CAAC;IACvC,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC;IACnE,OAAO,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACtD,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,SAAiB,EAAE,QAAgB;IAC3E,OAAO,sCAAsC,SAAS,WAAW,QAAQ,2CAA2C,CAAC;AACtH,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACpC,cAA4B,EAC5B,QAAuB,EACvB,MAAuB;IAEvB,IAAI,QAAQ,CAAC,UAAU,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IACnD,MAAM,KAAK,GAAG,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC1F,IAAI,KAAK;QAAE,OAAO,KAAK,CAAC;IACxB,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,sBAAsB,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;IACtF,IAAI,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAC9B,MAAM,WAAW,GAAG,oBAAoB,CACvC,QAAQ,CAAC,IAAI,EACb,CAAC,cAAc,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,CAC/D,CAAC;IACF,OAAO,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC;AAClF,CAAC;AAED,MAAM,UAAU,sBAAsB,CACrC,MAAgC,EAChC,aAAqB,EACrB,YAAoB;IAEpB,OAAO;QACN,GAAG,MAAM;QACT,8GAA8G;QAC9G,OAAO,EAAE;YACR,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,wBAAwB,CAAC,aAAa,EAAE,YAAY,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE;YAChG,GAAG,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC;SACzB;KACD,CAAC;AACH,CAAC","sourcesContent":["import type { AgentContext, AgentLoopConfig, AgentTool, AgentToolCall, AgentToolResult } from \"./types.ts\";\n\n/**\n * Some provider wire paths show the model non-native tools as\n * `mcp__<id>__<Name>` (recased, under a namespace senpi never defined), and a\n * model can carry that shape into a call for a tool it learned by its bare\n * name. Resolve such a call only when exactly one available tool matches after\n * stripping the namespace and folding case and `-`/`_` separators; never guess\n * between two candidates.\n */\nconst GATEWAY_TOOL_NAMESPACE = /^mcp__[^_]+__(.+)$/;\n\nfunction foldToolName(name: string): string {\n\treturn name.toLowerCase().replaceAll(/[-_]/g, \"\");\n}\n\nexport function resolveToolNameAlias(requested: string, available: Iterable<string>): string | undefined {\n\tconst names = [...new Set(available)];\n\tif (names.includes(requested)) return requested;\n\tconst unnamespaced = GATEWAY_TOOL_NAMESPACE.exec(requested)?.[1] ?? requested;\n\tif (names.includes(unnamespaced)) return unnamespaced;\n\tconst key = foldToolName(unnamespaced);\n\tconst matches = names.filter((name) => foldToolName(name) === key);\n\treturn matches.length === 1 ? matches[0] : undefined;\n}\n\nexport function toolNameCorrectionNotice(requested: string, resolved: string): string {\n\treturn `[auto-corrected] no tool is named \"${requested}\"; ran \"${resolved}\". Call tools by their exact listed name.`;\n}\n\n/**\n * Find the tool a call will run, resolving an unknown name through the host\n * resolver and then the alias rule. Runs before `tool_execution_start` so every\n * event names the tool that executes, never the name the model mistyped.\n */\nexport async function resolveCallTool(\n\tcurrentContext: AgentContext,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n): Promise<AgentTool | undefined> {\n\tif (toolCall.incomplete === true) return undefined;\n\tconst exact = currentContext.tools?.find((candidate) => candidate.name === toolCall.name);\n\tif (exact) return exact;\n\tconst resolved = await config.resolveUnknownToolCall?.(toolCall.name, currentContext);\n\tif (resolved) return resolved;\n\tconst aliasedName = resolveToolNameAlias(\n\t\ttoolCall.name,\n\t\t(currentContext.tools ?? []).map((candidate) => candidate.name),\n\t);\n\treturn currentContext.tools?.find((candidate) => candidate.name === aliasedName);\n}\n\nexport function withToolNameCorrection(\n\tresult: AgentToolResult<unknown>,\n\trequestedName: string,\n\tresolvedName: string,\n): AgentToolResult<unknown> {\n\treturn {\n\t\t...result,\n\t\t// Model-only: it steers the model back to exact names; the user sees the resolved tool as if called directly.\n\t\tcontent: [\n\t\t\t{ type: \"text\", text: toolNameCorrectionNotice(requestedName, resolvedName), audience: \"model\" },\n\t\t\t...(result.content ?? []),\n\t\t],\n\t};\n}\n"]}
1
+ {"version":3,"file":"tool-name-alias.js","sourceRoot":"","sources":["../src/tool-name-alias.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,6CAA6C,CAAC;AAGnF;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,SAAiB,EAAE,SAA2B;IAClF,OAAO,oBAAoB,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;AACnD,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,SAAiB,EAAE,QAAgB;IAC3E,OAAO,sCAAsC,SAAS,WAAW,QAAQ,2CAA2C,CAAC;AACtH,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACpC,cAA4B,EAC5B,QAAuB,EACvB,MAAuB;IAEvB,IAAI,QAAQ,CAAC,UAAU,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IACnD,MAAM,KAAK,GAAG,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC1F,IAAI,KAAK;QAAE,OAAO,KAAK,CAAC;IACxB,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,sBAAsB,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;IACtF,IAAI,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAC9B,MAAM,WAAW,GAAG,oBAAoB,CACvC,QAAQ,CAAC,IAAI,EACb,CAAC,cAAc,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,CAC/D,CAAC;IACF,OAAO,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC;AAClF,CAAC;AAED,MAAM,UAAU,sBAAsB,CACrC,MAAgC,EAChC,aAAqB,EACrB,YAAoB;IAEpB,OAAO;QACN,GAAG,MAAM;QACT,8GAA8G;QAC9G,OAAO,EAAE;YACR,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,wBAAwB,CAAC,aAAa,EAAE,YAAY,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE;YAChG,GAAG,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC;SACzB;KACD,CAAC;AACH,CAAC","sourcesContent":["import { resolveToolNameMatch } from \"@earendil-works/pi-ai/utils/tool-name-match\";\nimport type { AgentContext, AgentLoopConfig, AgentTool, AgentToolCall, AgentToolResult } from \"./types.ts\";\n\n/**\n * A model can call a tool by a name it was never registered under: recased,\n * under a gateway namespace (`mcp__<id>__<Name>`, any case), or without the\n * namespace a registered tool carries. The shared matcher resolves such a name\n * only when exactly one available tool matches; it never guesses.\n */\nexport function resolveToolNameAlias(requested: string, available: Iterable<string>): string | undefined {\n\treturn resolveToolNameMatch(requested, available);\n}\n\nexport function toolNameCorrectionNotice(requested: string, resolved: string): string {\n\treturn `[auto-corrected] no tool is named \"${requested}\"; ran \"${resolved}\". Call tools by their exact listed name.`;\n}\n\n/**\n * Find the tool a call will run, resolving an unknown name through the host\n * resolver and then the alias rule. Runs before `tool_execution_start` so every\n * event names the tool that executes, never the name the model mistyped.\n */\nexport async function resolveCallTool(\n\tcurrentContext: AgentContext,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n): Promise<AgentTool | undefined> {\n\tif (toolCall.incomplete === true) return undefined;\n\tconst exact = currentContext.tools?.find((candidate) => candidate.name === toolCall.name);\n\tif (exact) return exact;\n\tconst resolved = await config.resolveUnknownToolCall?.(toolCall.name, currentContext);\n\tif (resolved) return resolved;\n\tconst aliasedName = resolveToolNameAlias(\n\t\ttoolCall.name,\n\t\t(currentContext.tools ?? []).map((candidate) => candidate.name),\n\t);\n\treturn currentContext.tools?.find((candidate) => candidate.name === aliasedName);\n}\n\nexport function withToolNameCorrection(\n\tresult: AgentToolResult<unknown>,\n\trequestedName: string,\n\tresolvedName: string,\n): AgentToolResult<unknown> {\n\treturn {\n\t\t...result,\n\t\t// Model-only: it steers the model back to exact names; the user sees the resolved tool as if called directly.\n\t\tcontent: [\n\t\t\t{ type: \"text\", text: toolNameCorrectionNotice(requestedName, resolvedName), audience: \"model\" },\n\t\t\t...(result.content ?? []),\n\t\t],\n\t};\n}\n"]}
@@ -355,6 +355,8 @@ export interface AgentState {
355
355
  /** Available tools. Assigning a new array copies the top-level array. */
356
356
  set tools(tools: AgentTool<any>[]);
357
357
  get tools(): AgentTool<any>[];
358
+ /** Tool list the provider receives when it differs from `tools`; see {@link AgentContext.declaredTools}. */
359
+ declaredTools?: AgentTool<any>[];
358
360
  /** Conversation transcript. Assigning a new array copies the top-level array. */
359
361
  set messages(messages: AgentMessage[]);
360
362
  get messages(): AgentMessage[];
@@ -429,6 +431,12 @@ export interface AgentContext {
429
431
  messages: AgentMessage[];
430
432
  /** Tools available for this run. */
431
433
  tools?: AgentTool<any>[];
434
+ /**
435
+ * Superset of `tools` to declare to the provider, keeping the tool prefix byte-stable while the
436
+ * callable set changes (senpi#2095). Honored only for models that accept an allowed-tools
437
+ * restriction; tool calls still resolve against `tools` alone.
438
+ */
439
+ declaredTools?: AgentTool<any>[];
432
440
  }
433
441
  /**
434
442
  * Events emitted by the Agent for UI updates.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAChB,qBAAqB,EACrB,2BAA2B,EAC3B,OAAO,EACP,kBAAkB,EAClB,YAAY,EACZ,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,WAAW,EACX,iBAAi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AAE,GAAG,CAAC;IAAC,aAAa,EAAE,GAAG,CAAA;CAAE,GACtG;IAAE,IAAI,EAAE,oBAAoB,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,GAAG,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tContext,\n\tCursorExecHandlers,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tThinkingSelection,\n\tTool,\n\tToolResultMessage,\n\tUsage,\n} from \"@earendil-works/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop. `Models.streamSimple` satisfies\n * this shape.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then scheduled in concurrent waves.\n * Tools with `executionMode: \"sequential\"` run as exclusive barriers; parallel tools before\n * or after the barrier can still execute concurrently with each other.\n * `tool_execution_end` is emitted in tool completion order after each tool is finalized,\n * while tool-result message artifacts are emitted later in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/**\n * Controls how many queued user messages are injected when the agent loop reaches a queue drain point.\n *\n * - \"all\": drain and inject every queued message at that point.\n * - \"one-at-a-time\": drain and inject only the oldest queued message, leaving the rest queued for later drain points.\n */\nexport type QueueMode = \"all\" | \"one-at-a-time\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n\t/**\n\t * Hint that the agent should stop after the current tool batch when this call is blocked.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n * - `usage`: if provided, replaces the tool result usage\n * - `terminate`: if provided, replaces the early-termination hint\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content`, `details`, or `usage`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n\t/** Usage from the final tool execution itself, if available. Not used for main LLM context accounting. */\n\tusage?: Usage;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `shouldStopAfterTurn`. */\nexport interface ShouldStopAfterTurnContext {\n\t/** The assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool result messages passed to the preceding `turn_end` event. */\n\ttoolResults: ToolResultMessage[];\n\t/** Current agent context after the turn's assistant message and tool results have been appended. */\n\tcontext: AgentContext;\n\t/** Messages that this loop invocation will return if it exits at this point. Prompt runs include the initial prompt messages; continuation runs do not include pre-existing context messages. */\n\tnewMessages: AgentMessage[];\n}\n\n/** Replacement runtime state used by the agent loop before starting another provider request. */\nexport interface AgentLoopTurnUpdate {\n\t/** Context for the next provider request. */\n\tcontext?: AgentContext;\n\t/** Model for the next provider request. */\n\tmodel?: Model<any>;\n\t/** Thinking level for the next provider request. */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Thinking selection for the next provider request: undefined leaves it unchanged, null clears it. */\n\tthinkingSelection?: ThinkingSelection | null;\n\t/** Whether the next provider request should abort a server-selected fallback. */\n\tabortServerSideFallback?: boolean;\n}\n\nexport interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Cursor exec-channel tool handlers (cursor-agent models only).\n\t *\n\t * Cursor's server-driven protocol executes tools MID-STREAM: the server\n\t * blocks on an in-band reply, so the provider runs these handlers while\n\t * the Run stream is open, synthesizes already-resolved `toolCall` blocks\n\t * (marked `kCursorExecResolved`, which this loop skips), and buffers each\n\t * paired `ToolResultMessage` for emission right after the assistant\n\t * message. Other providers ignore this field.\n\t */\n\tcursorExecHandlers?: CursorExecHandlers | ((runSignal: AbortSignal) => CursorExecHandlers);\n\n\t/**\n\t * Maximum time in milliseconds to wait for the FIRST provider stream event.\n\t * Providers emit their first event only once the HTTP response begins, so a\n\t * dead upstream that accepts the request but never answers is otherwise only\n\t * bounded by `timeoutMs` (the idle timeout, default 5 minutes). After the\n\t * first event arrives, `timeoutMs` governs inter-event idleness as before.\n\t * Unset or non-positive values disable the start bound.\n\t */\n\tstreamStartTimeoutMs?: number;\n\n\t/** Provider/SDK timeout override for only the first request in this loop invocation. */\n\tinitialRequestTimeoutMs?: number;\n\n\t/** Stream-start timeout override for only the first request in this loop invocation. */\n\tinitialRequestStreamStartTimeoutMs?: number;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after each turn fully completes and `turn_end` has been emitted.\n\t *\n\t * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,\n\t * without starting another LLM call. The current assistant response and any tool executions finish normally.\n\t * This callback sees the completed-turn context and runs before `prepareNextTurn`.\n\t *\n\t * Use this to request a graceful stop after the current turn, e.g. before context gets too full.\n\t *\n\t * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t */\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\n\t/**\n\t * Called after each completed assistant turn, including a normal stop response, before the loop decides whether another provider request starts.\n\t * A terminating-tool continuation emits its `turn_start` boundary first so queue owners can clear\n\t * or replace pending input before preparation finishes and the continuation is admitted.\n\t * `shouldStopAfterTurn` and an empty terminating tool batch can end the run before preparation.\n\t * Return replacement context/model/thinking state to affect the next turn.\n\t * Return undefined to keep using the current context/config.\n\t */\n\tprepareNextTurn?: (\n\t\tcontext: PrepareNextTurnContext,\n\t) => AgentLoopTurnUpdate | undefined | Promise<AgentLoopTurnUpdate | undefined>;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Restores messages previously returned by a queue callback when next-turn preparation cannot continue.\n\t * Restored messages must be placed before messages queued after the drain.\n\t */\n\trestorePendingMessages?: (queue: \"steering\" | \"followUp\", messages: AgentMessage[]) => Promise<void> | void;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools in concurrent waves;\n\t * per-tool `executionMode: \"sequential\"` calls act as exclusive barriers,\n\t * emit `tool_execution_end` in tool completion order after each tool is finalized,\n\t * then emit tool-result message artifacts later in assistant source order\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Optional migration guidance for tool names intentionally removed by an extension.\n\t * The matching hint is appended to the normal unknown-tool error before hooks run.\n\t */\n\tremovedToolHints?: Record<string, string>;\n\n\t/**\n\t * Called when a model names a tool absent from the current context snapshot.\n\t * Return a newly available tool to continue normal validation and execution, or\n\t * undefined to emit the existing unknown-tool result. Hosts may use this to\n\t * activate a registered lazy tool at call time.\n\t */\n\tresolveUnknownToolCall?: (\n\t\ttoolName: string,\n\t\tcontext: AgentContext,\n\t) => AgentTool | undefined | Promise<AgentTool | undefined>;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * A blocked result can also set `terminate: true` to participate in the batch early-termination rule.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `usage` replaces the tool result usage\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from @earendil-works/pi-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@earendil-works/pi-agent-core\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/** System prompt sent with each model request. */\n\tsystemPrompt: string;\n\t/** Active model used for future turns. */\n\tmodel: Model<any>;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/**\n\t * Provenance-bearing thinking selection, when the user or a legacy variant\n\t * alias explicitly chose a level. Absent for defaulted effective levels.\n\t */\n\tthinkingSelection?: ThinkingSelection;\n\t/** First reasoning effort on the branch, used to preserve Responses cache prefixes. */\n\treasoningBaseline?: string;\n\t/** Available tools. Assigning a new array copies the top-level array. */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/** Conversation transcript. Assigning a new array copies the top-level array. */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/**\n\t * True while the agent is processing a prompt or continuation.\n\t *\n\t * This remains true until awaited `agent_end` listeners settle.\n\t */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the current streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool call ids currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error message from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Arbitrary structured details for logs or UI rendering. */\n\tdetails: T;\n\t/** Usage from the final tool execution itself, if available. Not used for main LLM context accounting. */\n\tusage?: Usage;\n\t/** Names of tools introduced by this result and available from this transcript point onward. */\n\taddedToolNames?: string[];\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n\t/**\n\t * Report a failure without throwing: `true` marks this result as a tool error while keeping\n\t * `content` and `details` intact for the model and renderers. Omitted or `false` means success.\n\t */\n\tisError?: boolean;\n}\n\n/**\n * Callback used by tools to stream partial execution updates.\n *\n * The callback is scoped to the current `execute()` invocation. Calls made after\n * the tool promise settles are ignored.\n */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/** Execute the tool call. Throw on failure instead of encoding errors in `content`. */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/** Recovery policy for an effect whose durable intent exists but whose outcome is unknown. */\n\treplay?: \"never\" | \"safe\";\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool acts as an exclusive barrier in parallel batches.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed into the low-level agent loop. */\nexport interface AgentContext {\n\t/** System prompt included with the request. */\n\tsystemPrompt: string;\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| { type: \"tool_execution_end\"; toolCallId: string; toolName: string; result: any; isError: boolean };\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tContext,\n\tCursorExecHandlers,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tThinkingSelection,\n\tTool,\n\tToolResultMessage,\n\tUsage,\n} from \"@earendil-works/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop. `Models.streamSimple` satisfies\n * this shape.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then scheduled in concurrent waves.\n * Tools with `executionMode: \"sequential\"` run as exclusive barriers; parallel tools before\n * or after the barrier can still execute concurrently with each other.\n * `tool_execution_end` is emitted in tool completion order after each tool is finalized,\n * while tool-result message artifacts are emitted later in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/**\n * Controls how many queued user messages are injected when the agent loop reaches a queue drain point.\n *\n * - \"all\": drain and inject every queued message at that point.\n * - \"one-at-a-time\": drain and inject only the oldest queued message, leaving the rest queued for later drain points.\n */\nexport type QueueMode = \"all\" | \"one-at-a-time\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n\t/**\n\t * Hint that the agent should stop after the current tool batch when this call is blocked.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n * - `usage`: if provided, replaces the tool result usage\n * - `terminate`: if provided, replaces the early-termination hint\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content`, `details`, or `usage`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n\t/** Usage from the final tool execution itself, if available. Not used for main LLM context accounting. */\n\tusage?: Usage;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `shouldStopAfterTurn`. */\nexport interface ShouldStopAfterTurnContext {\n\t/** The assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool result messages passed to the preceding `turn_end` event. */\n\ttoolResults: ToolResultMessage[];\n\t/** Current agent context after the turn's assistant message and tool results have been appended. */\n\tcontext: AgentContext;\n\t/** Messages that this loop invocation will return if it exits at this point. Prompt runs include the initial prompt messages; continuation runs do not include pre-existing context messages. */\n\tnewMessages: AgentMessage[];\n}\n\n/** Replacement runtime state used by the agent loop before starting another provider request. */\nexport interface AgentLoopTurnUpdate {\n\t/** Context for the next provider request. */\n\tcontext?: AgentContext;\n\t/** Model for the next provider request. */\n\tmodel?: Model<any>;\n\t/** Thinking level for the next provider request. */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Thinking selection for the next provider request: undefined leaves it unchanged, null clears it. */\n\tthinkingSelection?: ThinkingSelection | null;\n\t/** Whether the next provider request should abort a server-selected fallback. */\n\tabortServerSideFallback?: boolean;\n}\n\nexport interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Cursor exec-channel tool handlers (cursor-agent models only).\n\t *\n\t * Cursor's server-driven protocol executes tools MID-STREAM: the server\n\t * blocks on an in-band reply, so the provider runs these handlers while\n\t * the Run stream is open, synthesizes already-resolved `toolCall` blocks\n\t * (marked `kCursorExecResolved`, which this loop skips), and buffers each\n\t * paired `ToolResultMessage` for emission right after the assistant\n\t * message. Other providers ignore this field.\n\t */\n\tcursorExecHandlers?: CursorExecHandlers | ((runSignal: AbortSignal) => CursorExecHandlers);\n\n\t/**\n\t * Maximum time in milliseconds to wait for the FIRST provider stream event.\n\t * Providers emit their first event only once the HTTP response begins, so a\n\t * dead upstream that accepts the request but never answers is otherwise only\n\t * bounded by `timeoutMs` (the idle timeout, default 5 minutes). After the\n\t * first event arrives, `timeoutMs` governs inter-event idleness as before.\n\t * Unset or non-positive values disable the start bound.\n\t */\n\tstreamStartTimeoutMs?: number;\n\n\t/** Provider/SDK timeout override for only the first request in this loop invocation. */\n\tinitialRequestTimeoutMs?: number;\n\n\t/** Stream-start timeout override for only the first request in this loop invocation. */\n\tinitialRequestStreamStartTimeoutMs?: number;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after each turn fully completes and `turn_end` has been emitted.\n\t *\n\t * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,\n\t * without starting another LLM call. The current assistant response and any tool executions finish normally.\n\t * This callback sees the completed-turn context and runs before `prepareNextTurn`.\n\t *\n\t * Use this to request a graceful stop after the current turn, e.g. before context gets too full.\n\t *\n\t * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t */\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\n\t/**\n\t * Called after each completed assistant turn, including a normal stop response, before the loop decides whether another provider request starts.\n\t * A terminating-tool continuation emits its `turn_start` boundary first so queue owners can clear\n\t * or replace pending input before preparation finishes and the continuation is admitted.\n\t * `shouldStopAfterTurn` and an empty terminating tool batch can end the run before preparation.\n\t * Return replacement context/model/thinking state to affect the next turn.\n\t * Return undefined to keep using the current context/config.\n\t */\n\tprepareNextTurn?: (\n\t\tcontext: PrepareNextTurnContext,\n\t) => AgentLoopTurnUpdate | undefined | Promise<AgentLoopTurnUpdate | undefined>;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Restores messages previously returned by a queue callback when next-turn preparation cannot continue.\n\t * Restored messages must be placed before messages queued after the drain.\n\t */\n\trestorePendingMessages?: (queue: \"steering\" | \"followUp\", messages: AgentMessage[]) => Promise<void> | void;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools in concurrent waves;\n\t * per-tool `executionMode: \"sequential\"` calls act as exclusive barriers,\n\t * emit `tool_execution_end` in tool completion order after each tool is finalized,\n\t * then emit tool-result message artifacts later in assistant source order\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Optional migration guidance for tool names intentionally removed by an extension.\n\t * The matching hint is appended to the normal unknown-tool error before hooks run.\n\t */\n\tremovedToolHints?: Record<string, string>;\n\n\t/**\n\t * Called when a model names a tool absent from the current context snapshot.\n\t * Return a newly available tool to continue normal validation and execution, or\n\t * undefined to emit the existing unknown-tool result. Hosts may use this to\n\t * activate a registered lazy tool at call time.\n\t */\n\tresolveUnknownToolCall?: (\n\t\ttoolName: string,\n\t\tcontext: AgentContext,\n\t) => AgentTool | undefined | Promise<AgentTool | undefined>;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * A blocked result can also set `terminate: true` to participate in the batch early-termination rule.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `usage` replaces the tool result usage\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from @earendil-works/pi-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@earendil-works/pi-agent-core\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/** System prompt sent with each model request. */\n\tsystemPrompt: string;\n\t/** Active model used for future turns. */\n\tmodel: Model<any>;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/**\n\t * Provenance-bearing thinking selection, when the user or a legacy variant\n\t * alias explicitly chose a level. Absent for defaulted effective levels.\n\t */\n\tthinkingSelection?: ThinkingSelection;\n\t/** First reasoning effort on the branch, used to preserve Responses cache prefixes. */\n\treasoningBaseline?: string;\n\t/** Available tools. Assigning a new array copies the top-level array. */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/** Tool list the provider receives when it differs from `tools`; see {@link AgentContext.declaredTools}. */\n\tdeclaredTools?: AgentTool<any>[];\n\t/** Conversation transcript. Assigning a new array copies the top-level array. */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/**\n\t * True while the agent is processing a prompt or continuation.\n\t *\n\t * This remains true until awaited `agent_end` listeners settle.\n\t */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the current streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool call ids currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error message from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Arbitrary structured details for logs or UI rendering. */\n\tdetails: T;\n\t/** Usage from the final tool execution itself, if available. Not used for main LLM context accounting. */\n\tusage?: Usage;\n\t/** Names of tools introduced by this result and available from this transcript point onward. */\n\taddedToolNames?: string[];\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n\t/**\n\t * Report a failure without throwing: `true` marks this result as a tool error while keeping\n\t * `content` and `details` intact for the model and renderers. Omitted or `false` means success.\n\t */\n\tisError?: boolean;\n}\n\n/**\n * Callback used by tools to stream partial execution updates.\n *\n * The callback is scoped to the current `execute()` invocation. Calls made after\n * the tool promise settles are ignored.\n */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/** Execute the tool call. Throw on failure instead of encoding errors in `content`. */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/** Recovery policy for an effect whose durable intent exists but whose outcome is unknown. */\n\treplay?: \"never\" | \"safe\";\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool acts as an exclusive barrier in parallel batches.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed into the low-level agent loop. */\nexport interface AgentContext {\n\t/** System prompt included with the request. */\n\tsystemPrompt: string;\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for this run. */\n\ttools?: AgentTool<any>[];\n\t/**\n\t * Superset of `tools` to declare to the provider, keeping the tool prefix byte-stable while the\n\t * callable set changes (senpi#2095). Honored only for models that accept an allowed-tools\n\t * restriction; tool calls still resolve against `tools` alone.\n\t */\n\tdeclaredTools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| { type: \"tool_execution_end\"; toolCallId: string; toolName: string; result: any; isError: boolean };\n"]}
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-agent-core",
3
- "version": "2026.9.23-5",
3
+ "version": "2026.9.24-2",
4
4
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -57,8 +57,8 @@
57
57
  },
58
58
  "dependencies": {
59
59
  "@earendil-works/chord": "0.85.1",
60
- "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.9.23-5",
61
- "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.23-5",
60
+ "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.9.24-2",
61
+ "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.9.24-2",
62
62
  "diff": "9.0.0",
63
63
  "ignore": "7.0.9",
64
64
  "typebox": "1.3.34",
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic-tool-references.d.ts","sourceRoot":"","sources":["../../src/api/anthropic-tool-references.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEX,4BAA4B,EAE5B,MAAM,uDAAuD,CAAC;AA4F/D,wBAAgB,+BAA+B,CAAC,MAAM,EAAE,4BAA4B,GAAG,4BAA4B,CAkIlH"}
1
+ {"version":3,"file":"anthropic-tool-references.d.ts","sourceRoot":"","sources":["../../src/api/anthropic-tool-references.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEX,4BAA4B,EAE5B,MAAM,uDAAuD,CAAC;AA8D/D,wBAAgB,+BAA+B,CAAC,MAAM,EAAE,4BAA4B,GAAG,4BAA4B,CAkIlH"}
@@ -1,3 +1,4 @@
1
+ import { resolveToolNameMatch } from "../utils/tool-name-match.js";
1
2
  import { demotedToolCallText, demotedToolResultText } from "../utils/unavailable-tool-text.js";
2
3
  function isRecord(value) {
3
4
  return typeof value === "object" && value !== null;
@@ -27,14 +28,11 @@ function isRecord(value) {
27
28
  * The same wire path can also recase the tool it namespaces (`memory` comes
28
29
  * back as `mcp__a4e6__Memory`, `lsp_symbols` as `mcp__a4e6__LspSymbols`), so
29
30
  * the suffix alone no longer matches the request's tool name byte for byte.
30
- * Names are therefore compared with case and `_`/`-` separators folded away,
31
- * and a folded key resolves only when exactly one request tool owns it: the
32
- * fold never guesses between two candidates.
31
+ * Names are therefore resolved by the shared lenient matcher
32
+ * (`utils/tool-name-match.ts`, also used by the inbound tool-call resolver):
33
+ * case and `_`/`-` folded away, an `mcp_`/`mcp__` prefix stripped on either
34
+ * side, and a name resolves only when exactly one request tool matches.
33
35
  */
34
- const GATEWAY_TOOL_NAMESPACE = /^mcp__[^_]+__(.+)$/;
35
- function foldToolNameKey(name) {
36
- return name.toLowerCase().replaceAll(/[-_]/g, "");
37
- }
38
36
  function collectAvailableToolNames(tools) {
39
37
  const defined = new Set();
40
38
  if (Array.isArray(tools)) {
@@ -43,32 +41,7 @@ function collectAvailableToolNames(tools) {
43
41
  defined.add(tool.name);
44
42
  }
45
43
  }
46
- const folded = new Map();
47
- const ambiguous = new Set();
48
- for (const name of defined) {
49
- const key = foldToolNameKey(name);
50
- if (folded.has(key))
51
- ambiguous.add(key);
52
- else
53
- folded.set(key, name);
54
- }
55
- for (const key of ambiguous)
56
- folded.delete(key);
57
- return { defined, folded };
58
- }
59
- function resolveAvailableToolName(name, available) {
60
- const suffix = GATEWAY_TOOL_NAMESPACE.exec(name)?.[1];
61
- const candidates = suffix === undefined ? [name] : [name, suffix];
62
- for (const candidate of candidates) {
63
- if (available.defined.has(candidate))
64
- return candidate;
65
- }
66
- for (const candidate of candidates) {
67
- const folded = available.folded.get(foldToolNameKey(candidate));
68
- if (folded !== undefined)
69
- return folded;
70
- }
71
- return undefined;
44
+ return defined;
72
45
  }
73
46
  function isNativeToolSearchResultBlock(block) {
74
47
  return (isRecord(block) &&
@@ -82,7 +55,7 @@ export function demoteUnavailableToolReferences(params) {
82
55
  if (!Array.isArray(messages) || messages.length === 0)
83
56
  return params;
84
57
  const available = collectAvailableToolNames(params.tools);
85
- const resolve = (name) => resolveAvailableToolName(name, available);
58
+ const resolve = (name) => resolveToolNameMatch(name, available);
86
59
  const demotedCallNames = new Map();
87
60
  const renamedCallNames = new Map();
88
61
  for (const message of messages) {
@@ -99,7 +72,7 @@ export function demoteUnavailableToolReferences(params) {
99
72
  }
100
73
  }
101
74
  let changed = false;
102
- const availableToolNames = [...available.defined];
75
+ const availableToolNames = [...available];
103
76
  const seenDemotedCallNames = new Set();
104
77
  const rewrittenMessages = [];
105
78
  for (const message of messages) {