@daniel156161/prism 0.2.101 → 0.2.105

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 (205) hide show
  1. package/README.md +2 -2
  2. package/dist/pi/pi-env.d.ts +1 -1
  3. package/dist/pi/pi-env.js +1 -1
  4. package/dist/prism-extensions/integrations/ai-memory-system.js +16 -9
  5. package/dist/prism-extensions/integrations/ai-memory-system.js.map +1 -1
  6. package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts.map +1 -1
  7. package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +23 -25
  8. package/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js.map +1 -1
  9. package/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.d.ts.map +1 -1
  10. package/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js +3 -1
  11. package/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js.map +1 -1
  12. package/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +3 -2
  13. package/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts.map +1 -1
  14. package/node_modules/@earendil-works/pi-agent-core/dist/types.js.map +1 -1
  15. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  16. package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.d.ts.map +1 -1
  17. package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +1 -1
  18. package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js.map +1 -1
  19. package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.d.ts.map +1 -1
  20. package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +38 -6
  21. package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js.map +1 -1
  22. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts +75 -0
  23. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts.map +1 -1
  24. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +75 -0
  25. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js.map +1 -1
  26. package/node_modules/@earendil-works/pi-ai/dist/providers/cloudflare-ai-gateway.d.ts +3 -1
  27. package/node_modules/@earendil-works/pi-ai/dist/providers/cloudflare-ai-gateway.d.ts.map +1 -1
  28. package/node_modules/@earendil-works/pi-ai/dist/providers/cloudflare-ai-gateway.js.map +1 -1
  29. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  30. package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  31. package/node_modules/@earendil-works/pi-ai/dist/providers/data/azure-openai-responses.json +1 -1
  32. package/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  33. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  34. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  35. package/node_modules/@earendil-works/pi-ai/dist/providers/data/deepseek.json +1 -1
  36. package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  37. package/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
  38. package/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  39. package/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax-cn.json +1 -1
  40. package/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax.json +1 -1
  41. package/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  42. package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  43. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
  44. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  45. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  46. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  47. package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan-cn.json +1 -1
  48. package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan.json +1 -1
  49. package/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  50. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  51. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
  52. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai.json +1 -1
  53. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +1 -1
  54. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts.map +1 -1
  55. package/node_modules/@earendil-works/pi-ai/dist/types.js.map +1 -1
  56. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  57. package/node_modules/@earendil-works/pi-client/CHANGELOG.md +1 -1
  58. package/node_modules/@earendil-works/pi-client/package.json +2 -2
  59. package/node_modules/@earendil-works/pi-coding-agent/CHANGELOG.md +47 -3
  60. package/node_modules/@earendil-works/pi-coding-agent/README.md +5 -4
  61. package/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-GPPBJGBU.js → chunk-2KVJKXS2.js} +1 -1
  62. package/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-E5KXRMZK.js → chunk-OMWWHBTG.js} +69 -68
  63. package/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/github-copilot.js +1 -1
  64. package/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{google-generative-ai-XDKMGBCJ.js → google-generative-ai-YMUPJBKR.js} +1 -1
  65. package/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{google-vertex-D5FGEO3Y.js → google-vertex-MPWMV4OF.js} +1 -1
  66. package/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/https-proxy-agent-2VXB7436.js +13 -0
  67. package/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{mistral-conversations-YK73UAOZ.js → mistral-conversations-Q3AWZJAZ.js} +1 -1
  68. package/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{openai-completions-JD4WAC3R.js → openai-completions-ERMU2SS7.js} +1 -1
  69. package/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js +1 -1
  70. package/node_modules/@earendil-works/pi-coding-agent/dist/bundle/index.js +1 -1
  71. package/node_modules/@earendil-works/pi-coding-agent/dist/bundle/rpc-entry.js +1 -1
  72. package/node_modules/@earendil-works/pi-coding-agent/dist/cli/startup-ui.d.ts.map +1 -1
  73. package/node_modules/@earendil-works/pi-coding-agent/dist/cli/startup-ui.js +2 -1
  74. package/node_modules/@earendil-works/pi-coding-agent/dist/cli/startup-ui.js.map +1 -1
  75. package/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.d.ts +12 -1
  76. package/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.d.ts.map +1 -1
  77. package/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.js +77 -9
  78. package/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.js.map +1 -1
  79. package/node_modules/@earendil-works/pi-coding-agent/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  80. package/node_modules/@earendil-works/pi-coding-agent/dist/core/compaction/branch-summarization.js +4 -3
  81. package/node_modules/@earendil-works/pi-coding-agent/dist/core/compaction/branch-summarization.js.map +1 -1
  82. package/node_modules/@earendil-works/pi-coding-agent/dist/core/compaction/compaction.d.ts +5 -0
  83. package/node_modules/@earendil-works/pi-coding-agent/dist/core/compaction/compaction.d.ts.map +1 -1
  84. package/node_modules/@earendil-works/pi-coding-agent/dist/core/compaction/compaction.js +19 -5
  85. package/node_modules/@earendil-works/pi-coding-agent/dist/core/compaction/compaction.js.map +1 -1
  86. package/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/index.d.ts +1 -1
  87. package/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/index.d.ts.map +1 -1
  88. package/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/index.js.map +1 -1
  89. package/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/runner.d.ts +5 -0
  90. package/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/runner.d.ts.map +1 -1
  91. package/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/runner.js +45 -1
  92. package/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/runner.js.map +1 -1
  93. package/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/types.d.ts +18 -1
  94. package/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/types.d.ts.map +1 -1
  95. package/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/types.js.map +1 -1
  96. package/node_modules/@earendil-works/pi-coding-agent/dist/core/session-manager.d.ts.map +1 -1
  97. package/node_modules/@earendil-works/pi-coding-agent/dist/core/session-manager.js +4 -2
  98. package/node_modules/@earendil-works/pi-coding-agent/dist/core/session-manager.js.map +1 -1
  99. package/node_modules/@earendil-works/pi-coding-agent/dist/core/settings-manager.d.ts +8 -1
  100. package/node_modules/@earendil-works/pi-coding-agent/dist/core/settings-manager.d.ts.map +1 -1
  101. package/node_modules/@earendil-works/pi-coding-agent/dist/core/settings-manager.js +17 -0
  102. package/node_modules/@earendil-works/pi-coding-agent/dist/core/settings-manager.js.map +1 -1
  103. package/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/client.d.ts +6 -0
  104. package/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/client.d.ts.map +1 -1
  105. package/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/client.js +7 -0
  106. package/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/client.js.map +1 -1
  107. package/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/provider.d.ts +3 -1
  108. package/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/provider.d.ts.map +1 -1
  109. package/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/provider.js +27 -6
  110. package/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/provider.js.map +1 -1
  111. package/node_modules/@earendil-works/pi-coding-agent/dist/index.d.ts +2 -1
  112. package/node_modules/@earendil-works/pi-coding-agent/dist/index.d.ts.map +1 -1
  113. package/node_modules/@earendil-works/pi-coding-agent/dist/index.js +1 -0
  114. package/node_modules/@earendil-works/pi-coding-agent/dist/index.js.map +1 -1
  115. package/node_modules/@earendil-works/pi-coding-agent/dist/main.d.ts.map +1 -1
  116. package/node_modules/@earendil-works/pi-coding-agent/dist/main.js +2 -0
  117. package/node_modules/@earendil-works/pi-coding-agent/dist/main.js.map +1 -1
  118. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/settings-selector.d.ts +2 -0
  119. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  120. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/settings-selector.js +10 -0
  121. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/settings-selector.js.map +1 -1
  122. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/interactive-mode.d.ts +4 -0
  123. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  124. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/interactive-mode.js +55 -31
  125. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/interactive-mode.js.map +1 -1
  126. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-client.d.ts +7 -0
  127. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  128. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-client.js +7 -0
  129. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-client.js.map +1 -1
  130. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  131. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-mode.js +3 -0
  132. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-mode.js.map +1 -1
  133. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-types.d.ts +12 -0
  134. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  135. package/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-types.js.map +1 -1
  136. package/node_modules/@earendil-works/pi-coding-agent/dist/utils/shell.d.ts.map +1 -1
  137. package/node_modules/@earendil-works/pi-coding-agent/dist/utils/shell.js +6 -4
  138. package/node_modules/@earendil-works/pi-coding-agent/dist/utils/shell.js.map +1 -1
  139. package/node_modules/@earendil-works/pi-coding-agent/docs/compaction.md +2 -0
  140. package/node_modules/@earendil-works/pi-coding-agent/docs/custom-provider.md +7 -7
  141. package/node_modules/@earendil-works/pi-coding-agent/docs/environment-variables.md +3 -0
  142. package/node_modules/@earendil-works/pi-coding-agent/docs/extensions.md +18 -0
  143. package/node_modules/@earendil-works/pi-coding-agent/docs/keybindings.md +1 -1
  144. package/node_modules/@earendil-works/pi-coding-agent/docs/quickstart.md +1 -1
  145. package/node_modules/@earendil-works/pi-coding-agent/docs/rpc.md +23 -0
  146. package/node_modules/@earendil-works/pi-coding-agent/docs/settings.md +12 -4
  147. package/node_modules/@earendil-works/pi-coding-agent/docs/terminal-setup.md +12 -0
  148. package/node_modules/@earendil-works/pi-coding-agent/docs/usage.md +4 -3
  149. package/node_modules/@earendil-works/pi-coding-agent/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  150. package/node_modules/@earendil-works/pi-coding-agent/examples/extensions/custom-provider-anthropic/package.json +1 -1
  151. package/node_modules/@earendil-works/pi-coding-agent/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  152. package/node_modules/@earendil-works/pi-coding-agent/examples/extensions/gondolin/package-lock.json +2 -2
  153. package/node_modules/@earendil-works/pi-coding-agent/examples/extensions/gondolin/package.json +1 -1
  154. package/node_modules/@earendil-works/pi-coding-agent/examples/extensions/sandbox/package-lock.json +2 -2
  155. package/node_modules/@earendil-works/pi-coding-agent/examples/extensions/sandbox/package.json +1 -1
  156. package/node_modules/@earendil-works/pi-coding-agent/examples/extensions/with-deps/package-lock.json +2 -2
  157. package/node_modules/@earendil-works/pi-coding-agent/examples/extensions/with-deps/package.json +1 -1
  158. package/node_modules/@earendil-works/pi-coding-agent/package.json +6 -6
  159. package/node_modules/@earendil-works/pi-protocol/package.json +1 -1
  160. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  161. package/node_modules/@earendil-works/pi-tui/README.md +1 -1
  162. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.d.ts +1 -0
  163. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.d.ts.map +1 -1
  164. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.js +36 -3
  165. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.js.map +1 -1
  166. package/node_modules/@earendil-works/pi-tui/dist/index.d.ts +1 -1
  167. package/node_modules/@earendil-works/pi-tui/dist/index.d.ts.map +1 -1
  168. package/node_modules/@earendil-works/pi-tui/dist/index.js +1 -1
  169. package/node_modules/@earendil-works/pi-tui/dist/index.js.map +1 -1
  170. package/node_modules/@earendil-works/pi-tui/dist/terminal-image.d.ts +2 -0
  171. package/node_modules/@earendil-works/pi-tui/dist/terminal-image.d.ts.map +1 -1
  172. package/node_modules/@earendil-works/pi-tui/dist/terminal-image.js +37 -2
  173. package/node_modules/@earendil-works/pi-tui/dist/terminal-image.js.map +1 -1
  174. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts +11 -0
  175. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts.map +1 -1
  176. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +58 -15
  177. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js.map +1 -1
  178. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.d.ts.map +1 -1
  179. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js +105 -45
  180. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js.map +1 -1
  181. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  182. package/node_modules/@types/node/README.md +1 -1
  183. package/node_modules/@types/node/buffer.buffer.d.ts +5 -0
  184. package/node_modules/@types/node/crypto.d.ts +0 -2
  185. package/node_modules/@types/node/dgram.d.ts +119 -4
  186. package/node_modules/@types/node/fs/promises.d.ts +61 -65
  187. package/node_modules/@types/node/fs.d.ts +86 -76
  188. package/node_modules/@types/node/http.d.ts +1 -1
  189. package/node_modules/@types/node/http2.d.ts +2 -2
  190. package/node_modules/@types/node/index.d.ts +1 -0
  191. package/node_modules/@types/node/inspector.d.ts +2 -1
  192. package/node_modules/@types/node/net.d.ts +108 -16
  193. package/node_modules/@types/node/package.json +2 -2
  194. package/node_modules/@types/node/quic.d.ts +37 -11
  195. package/node_modules/@types/node/stream/iter.d.ts +4 -4
  196. package/node_modules/@types/node/tls.d.ts +24 -0
  197. package/node_modules/@types/node/ts5.6/buffer.buffer.d.ts +5 -0
  198. package/node_modules/@types/node/ts5.6/index.d.ts +1 -0
  199. package/node_modules/@types/node/ts5.7/index.d.ts +1 -0
  200. package/node_modules/@types/node/tty.d.ts +4 -3
  201. package/node_modules/@types/node/vfs.d.ts +210 -0
  202. package/node_modules/@types/node/vm.d.ts +1 -1
  203. package/package.json +9 -9
  204. package/src/prism-extensions/integrations/ai-memory-system.ts +14 -9
  205. package/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/dist-RDWOYWHR.js +0 -13
@@ -183,6 +183,7 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
183
183
  *
184
184
  * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,
185
185
  * without starting another LLM call. The current assistant response and any tool executions finish normally.
186
+ * This callback sees the completed-turn context and runs before `prepareNextTurn`.
186
187
  *
187
188
  * Use this to request a graceful stop after the current turn, e.g. before context gets too full.
188
189
  *
@@ -190,8 +191,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
190
191
  */
191
192
  shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;
192
193
  /**
193
- * Called after `turn_end` and before the loop decides whether another provider request should start.
194
- * Return replacement context/model/thinking state to affect the next turn in this run.
194
+ * Called after `turn_end` when the loop will continue, immediately before the next turn starts.
195
+ * Return replacement context/model/thinking state to affect that turn.
195
196
  * Return undefined to keep using the current context/config.
196
197
  */
197
198
  prepareNextTurn?: (context: PrepareNextTurnContext) => AgentLoopTurnUpdate | undefined | Promise<AgentLoopTurnUpdate | undefined>;
@@ -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,YAAY,EACZ,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,WAAW,EACX,IAAI,EACJ,iBAAiB,EACjB,KAAK,EACL,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAE/C;;;;;;;;;GASG;AACH,MAAM,MAAM,QAAQ,GAAG,CACtB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,KACzB,2BAA2B,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;AAExE;;;;;;;GAOG;AACH,MAAM,MAAM,iBAAiB,GAAG,YAAY,GAAG,UAAU,CAAC;AAE1D;;;;;GAKG;AACH,MAAM,MAAM,SAAS,GAAG,KAAK,GAAG,eAAe,CAAC;AAEhD,wEAAwE;AACxE,MAAM,MAAM,aAAa,GAAG,OAAO,CAA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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","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\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 allowed tools execute concurrently.\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}\n\nexport interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\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 *\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 `turn_end` and before the loop decides whether another provider request should start.\n\t * Return replacement context/model/thinking state to affect the next turn in this run.\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 * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently;\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 * 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 \"@mariozechner/agent\" {\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/** 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}\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/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\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.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAChB,qBAAqB,EACrB,2BAA2B,EAC3B,OAAO,EACP,YAAY,EACZ,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,WAAW,EACX,IAAI,EACJ,iBAAiB,EACjB,KAAK,EACL,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAE/C;;;;;;;;;GASG;AACH,MAAM,MAAM,QAAQ,GAAG,CACtB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,KACzB,2BAA2B,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;AAExE;;;;;;;GAOG;AACH,MAAM,MAAM,iBAAiB,GAAG,YAAY,GAAG,UAAU,CAAC;AAE1D;;;;;GAKG;AACH,MAAM,MAAM,SAAS,GAAG,KAAK,GAAG,eAAe,CAAC;AAE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CAAC;IAAC,IAAI,EAAE,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","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\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 allowed tools execute concurrently.\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}\n\nexport interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\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 `turn_end` when the loop will continue, immediately before the next turn starts.\n\t * Return replacement context/model/thinking state to affect that 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 * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently;\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 * 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 \"@mariozechner/agent\" {\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/** 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}\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/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\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 +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\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\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 allowed tools execute concurrently.\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}\n\nexport interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\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 *\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 `turn_end` and before the loop decides whether another provider request should start.\n\t * Return replacement context/model/thinking state to affect the next turn in this run.\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 * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently;\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 * 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 \"@mariozechner/agent\" {\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/** 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}\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/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\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\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\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 allowed tools execute concurrently.\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}\n\nexport interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\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 `turn_end` when the loop will continue, immediately before the next turn starts.\n\t * Return replacement context/model/thinking state to affect that 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 * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently;\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 * 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 \"@mariozechner/agent\" {\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/** 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}\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/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\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,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-agent-core",
3
- "version": "0.84.3",
3
+ "version": "0.84.4",
4
4
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -35,8 +35,8 @@
35
35
  "prepublishOnly": "npm run build"
36
36
  },
37
37
  "dependencies": {
38
- "@earendil-works/pi-ai": "^0.84.3",
39
- "@earendil-works/pi-telemetry": "^0.84.3",
38
+ "@earendil-works/pi-ai": "^0.84.4",
39
+ "@earendil-works/pi-telemetry": "^0.84.4",
40
40
  "diff": "8.0.4",
41
41
  "ignore": "7.0.5",
42
42
  "typebox": "1.3.7",
@@ -1 +1 @@
1
- {"version":3,"file":"mistral-conversations.d.ts","sourceRoot":"","sources":["../../src/api/mistral-conversations.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAKX,mBAAmB,EAEnB,cAAc,EACd,aAAa,EAKb,MAAM,aAAa,CAAC;AAcrB;;GAEG;AACH,KAAK,sBAAsB,GAAG,MAAM,GAAG,MAAM,CAAC;AAE9C,MAAM,WAAW,cAAe,SAAQ,aAAa;IACpD,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG,UAAU,GAAG;QAAE,IAAI,EAAE,UAAU,CAAC;QAAC,QAAQ,EAAE;YAAE,IAAI,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAC;IACrG,UAAU,CAAC,EAAE,WAAW,CAAC;IACzB,eAAe,CAAC,EAAE,sBAAsB,CAAC;CACzC;AAiFD;;GAEG;AACH,eAAO,MAAM,MAAM,EAAE,cAAc,CAAC,uBAAuB,EAAE,cAAc,CAsD1E,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,YAAY,EAAE,cAAc,CAAC,uBAAuB,EAAE,mBAAmB,CAwBrF,CAAC","sourcesContent":["import { calculateCost, clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tContext,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n} from \"../types.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { getJsonSchemaToolParameters, resolveJsonSchemaStrictSampling } from \"./constrained-sampling.ts\";\nimport { buildBaseOptions } from \"./simple-options.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\nconst MISTRAL_TOOL_CALL_ID_LENGTH = 9;\nconst MAX_MISTRAL_ERROR_BODY_CHARS = 4000;\n\n/**\n * Provider-specific options for the Mistral API.\n */\ntype MistralReasoningEffort = \"none\" | \"high\";\n\nexport interface MistralOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"any\" | \"required\" | { type: \"function\"; function: { name: string } };\n\tpromptMode?: \"reasoning\";\n\treasoningEffort?: MistralReasoningEffort;\n}\n\ntype MistralContentChunk =\n\t| { type: \"text\"; text: string }\n\t| { type: \"image_url\"; imageUrl: string }\n\t| { type: \"thinking\"; thinking: Array<{ type: \"text\"; text: string }> };\n\ntype MistralRequestToolCall = {\n\tid: string;\n\ttype: \"function\";\n\tfunction: { name: string; arguments: string };\n\tindex: number;\n};\n\ntype MistralChatMessage = {\n\trole: \"system\" | \"user\" | \"assistant\" | \"tool\";\n\tcontent?: string | MistralContentChunk[];\n\ttoolCalls?: MistralRequestToolCall[];\n\ttoolCallId?: string;\n\tname?: string;\n\tprefix?: boolean;\n};\n\ntype MistralFunctionTool = {\n\ttype: \"function\";\n\tfunction: {\n\t\tname: string;\n\t\tdescription: string;\n\t\tparameters: Record<string, unknown>;\n\t\tstrict: boolean;\n\t};\n};\n\ntype MistralChatPayload = {\n\t[key: string]: unknown;\n\tmodel: string;\n\tstream: boolean;\n\tmessages: MistralChatMessage[];\n\ttools?: MistralFunctionTool[];\n\ttemperature?: number;\n\tmaxTokens?: number;\n\ttoolChoice?: Exclude<MistralOptions[\"toolChoice\"], undefined>;\n\tpromptMode?: \"reasoning\";\n\treasoningEffort?: MistralReasoningEffort;\n\tpromptCacheKey?: string;\n};\n\ntype MistralStreamContentChunk = {\n\ttype: string;\n\ttext?: string;\n\tthinking?: Array<{ text?: string }>;\n};\n\ntype MistralStreamToolCall = {\n\tid?: string;\n\tindex?: number;\n\tfunction: {\n\t\tname: string;\n\t\targuments: string | Record<string, unknown>;\n\t};\n};\n\ntype MistralCompletionEvent = {\n\tdata: {\n\t\tid?: string;\n\t\tusage?: {\n\t\t\t[key: string]: unknown;\n\t\t\tprompt_tokens?: number;\n\t\t\tcompletion_tokens?: number;\n\t\t\ttotal_tokens?: number;\n\t\t};\n\t\tchoices: Array<{\n\t\t\tfinish_reason?: string | null;\n\t\t\tdelta: {\n\t\t\t\tcontent?: string | MistralStreamContentChunk[] | null;\n\t\t\t\ttool_calls?: MistralStreamToolCall[] | null;\n\t\t\t};\n\t\t}>;\n\t};\n};\n\n/**\n * Stream responses from the native Mistral Chat Completions endpoint.\n */\nexport const stream: StreamFunction<\"mistral-conversations\", MistralOptions> = (\n\tmodel: Model<\"mistral-conversations\">,\n\tcontext: Context,\n\toptions?: MistralOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output = createOutput(model);\n\n\t\ttry {\n\t\t\tconst apiKey = options?.apiKey;\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t\t\t}\n\n\t\t\tconst normalizeMistralToolCallId = createMistralToolCallIdNormalizer();\n\t\t\tconst transformedMessages = transformMessages(context.messages, model, (id) => normalizeMistralToolCallId(id));\n\n\t\t\tlet payload = buildChatPayload(model, context, transformedMessages, options);\n\t\t\tconst nextPayload = await options?.onPayload?.(payload, model);\n\t\t\tif (nextPayload !== undefined) {\n\t\t\t\tpayload = nextPayload as MistralChatPayload;\n\t\t\t}\n\t\t\tconst mistralStream = await requestMistralStream(model, payload, apiKey, options);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\tawait consumeChatStream(model, output, stream, mistralStream);\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"pending\") {\n\t\t\t\tthrow new Error(\"Mistral stream ended without a finish reason\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\t// partialArgs is only a streaming scratch buffer; never persist it.\n\t\t\t\tdelete (block as { partialArgs?: string }).partialArgs;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatMistralError(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\n/**\n * Maps provider-agnostic `SimpleStreamOptions` to Mistral options.\n */\nexport const streamSimple: StreamFunction<\"mistral-conversations\", SimpleStreamOptions> = (\n\tmodel: Model<\"mistral-conversations\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = {\n\t\t...buildBaseOptions(model, context, options, apiKey),\n\t\ttoolChoice: options?.toolChoice,\n\t} satisfies MistralOptions;\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoning = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\tconst shouldUseReasoning = model.reasoning && reasoning !== undefined;\n\n\treturn stream(model, context, {\n\t\t...base,\n\t\tpromptMode: shouldUseReasoning && usesPromptModeReasoning(model) ? \"reasoning\" : undefined,\n\t\treasoningEffort:\n\t\t\tshouldUseReasoning && usesReasoningEffort(model) ? mapReasoningEffort(model, reasoning) : undefined,\n\t} satisfies MistralOptions);\n};\n\nfunction createOutput(model: Model<\"mistral-conversations\">): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"pending\",\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createMistralToolCallIdNormalizer(): (id: string) => string {\n\tconst idMap = new Map<string, string>();\n\tconst reverseMap = new Map<string, string>();\n\n\treturn (id: string): string => {\n\t\tconst existing = idMap.get(id);\n\t\tif (existing) return existing;\n\n\t\tlet attempt = 0;\n\t\twhile (true) {\n\t\t\tconst candidate = deriveMistralToolCallId(id, attempt);\n\t\t\tconst owner = reverseMap.get(candidate);\n\t\t\tif (!owner || owner === id) {\n\t\t\t\tidMap.set(id, candidate);\n\t\t\t\treverseMap.set(candidate, id);\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t\tattempt++;\n\t\t}\n\t};\n}\n\nfunction deriveMistralToolCallId(id: string, attempt: number): string {\n\tconst normalized = id.replace(/[^a-zA-Z0-9]/g, \"\");\n\tif (attempt === 0 && normalized.length === MISTRAL_TOOL_CALL_ID_LENGTH) return normalized;\n\tconst seedBase = normalized || id;\n\tconst seed = attempt === 0 ? seedBase : `${seedBase}:${attempt}`;\n\treturn shortHash(seed)\n\t\t.replace(/[^a-zA-Z0-9]/g, \"\")\n\t\t.slice(0, MISTRAL_TOOL_CALL_ID_LENGTH);\n}\n\nfunction formatMistralError(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tconst httpError = error as Error & { statusCode?: unknown; body?: unknown };\n\t\tconst statusCode = typeof httpError.statusCode === \"number\" ? httpError.statusCode : undefined;\n\t\tconst bodyText = typeof httpError.body === \"string\" ? httpError.body.trim() : undefined;\n\t\tif (statusCode !== undefined && bodyText) {\n\t\t\treturn `Mistral API error (${statusCode}): ${truncateErrorText(bodyText, MAX_MISTRAL_ERROR_BODY_CHARS)}`;\n\t\t}\n\t\tif (statusCode !== undefined) return `Mistral API error (${statusCode}): ${error.message}`;\n\t\treturn error.message;\n\t}\n\treturn safeJsonStringify(error);\n}\n\nfunction truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\nfunction safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nasync function requestMistralStream(\n\tmodel: Model<\"mistral-conversations\">,\n\tpayload: MistralChatPayload,\n\tapiKey: string,\n\toptions?: MistralOptions,\n): Promise<AsyncIterable<MistralCompletionEvent>> {\n\tconst baseUrl = new URL(model.baseUrl);\n\tbaseUrl.pathname = `${baseUrl.pathname.replace(/\\/+$/u, \"\")}/`;\n\tconst url = new URL(\"v1/chat/completions\", baseUrl);\n\tconst headers = buildMistralHeaders(model, apiKey, options);\n\tconst timeoutSignal = AbortSignal.timeout(options?.timeoutMs ?? 60_000);\n\tconst signal = options?.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;\n\tconst response = await (options?.fetch ?? globalThis.fetch)(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(toMistralWirePayload(payload)),\n\t\tsignal,\n\t});\n\n\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\n\tif (!response.ok) {\n\t\tconst body = await response.text();\n\t\tthrow new MistralHttpError(response.status, body, response.statusText);\n\t}\n\tif (!response.body) {\n\t\tthrow new Error(\"Mistral response has no body\");\n\t}\n\n\treturn readMistralEvents(response.body, signal);\n}\n\nclass MistralHttpError extends Error {\n\tstatusCode: number;\n\tbody: string;\n\n\tconstructor(statusCode: number, body: string, statusText: string) {\n\t\tsuper(statusText || `Request failed with status ${statusCode}`);\n\t\tthis.name = \"MistralHttpError\";\n\t\tthis.statusCode = statusCode;\n\t\tthis.body = body;\n\t}\n}\n\nfunction buildMistralHeaders(model: Model<\"mistral-conversations\">, apiKey: string, options?: MistralOptions): Headers {\n\tconst headers = new Headers({\n\t\t\"User-Agent\": getPiUserAgent(),\n\t\taccept: \"text/event-stream\",\n\t\tauthorization: `Bearer ${apiKey}`,\n\t\t\"content-type\": \"application/json\",\n\t});\n\tapplyMistralHeaderOverrides(headers, model.headers);\n\tapplyMistralHeaderOverrides(headers, options?.headers);\n\n\tconst hasExplicitAffinity =\n\t\thasMistralHeaderOverride(model.headers, \"x-affinity\") || hasMistralHeaderOverride(options?.headers, \"x-affinity\");\n\tif (shouldUsePromptCaching(options) && !hasExplicitAffinity) {\n\t\theaders.set(\"x-affinity\", options.sessionId);\n\t}\n\n\treturn headers;\n}\n\nfunction applyMistralHeaderOverrides(headers: Headers, overrides?: Record<string, string | null>): void {\n\tif (!overrides) return;\n\tfor (const [name, value] of Object.entries(overrides)) {\n\t\tif (value === null) headers.delete(name);\n\t\telse headers.set(name, value);\n\t}\n}\n\nfunction hasMistralHeaderOverride(overrides: Record<string, string | null> | undefined, target: string): boolean {\n\treturn !!overrides && Object.keys(overrides).some((name) => name.toLowerCase() === target);\n}\n\nfunction toMistralWirePayload(payload: MistralChatPayload): Record<string, unknown> {\n\tconst wirePayload: Record<string, unknown> = { ...payload };\n\tfor (const [source, target] of [\n\t\t[\"topP\", \"top_p\"],\n\t\t[\"maxTokens\", \"max_tokens\"],\n\t\t[\"randomSeed\", \"random_seed\"],\n\t\t[\"responseFormat\", \"response_format\"],\n\t\t[\"toolChoice\", \"tool_choice\"],\n\t\t[\"presencePenalty\", \"presence_penalty\"],\n\t\t[\"frequencyPenalty\", \"frequency_penalty\"],\n\t\t[\"parallelToolCalls\", \"parallel_tool_calls\"],\n\t\t[\"reasoningEffort\", \"reasoning_effort\"],\n\t\t[\"promptMode\", \"prompt_mode\"],\n\t\t[\"promptCacheKey\", \"prompt_cache_key\"],\n\t\t[\"safePrompt\", \"safe_prompt\"],\n\t] as const) {\n\t\tremapMistralProperty(wirePayload, source, target);\n\t}\n\twirePayload.messages = payload.messages.map((message) => toMistralWireMessage(message));\n\n\tconst responseFormat = wirePayload.response_format;\n\tif (isMistralRecord(responseFormat)) {\n\t\tconst wireResponseFormat = { ...responseFormat };\n\t\tremapMistralProperty(wireResponseFormat, \"jsonSchema\", \"json_schema\");\n\t\tconst jsonSchema = wireResponseFormat.json_schema;\n\t\tif (isMistralRecord(jsonSchema)) {\n\t\t\tconst wireJsonSchema = { ...jsonSchema };\n\t\t\tremapMistralProperty(wireJsonSchema, \"schemaDefinition\", \"schema\");\n\t\t\twireResponseFormat.json_schema = wireJsonSchema;\n\t\t}\n\t\twirePayload.response_format = wireResponseFormat;\n\t}\n\n\treturn wirePayload;\n}\n\nfunction toMistralWireMessage(message: MistralChatMessage): Record<string, unknown> {\n\tconst wireMessage: Record<string, unknown> = { ...message };\n\tremapMistralProperty(wireMessage, \"toolCalls\", \"tool_calls\");\n\tremapMistralProperty(wireMessage, \"toolCallId\", \"tool_call_id\");\n\tif (Array.isArray(message.content)) {\n\t\twireMessage.content = message.content.map((chunk) => toMistralWireContentChunk(chunk));\n\t}\n\treturn wireMessage;\n}\n\nfunction toMistralWireContentChunk(chunk: MistralContentChunk): Record<string, unknown> {\n\tconst wireChunk: Record<string, unknown> = { ...chunk };\n\tfor (const [source, target] of [\n\t\t[\"imageUrl\", \"image_url\"],\n\t\t[\"documentUrl\", \"document_url\"],\n\t\t[\"documentName\", \"document_name\"],\n\t\t[\"fileId\", \"file_id\"],\n\t\t[\"referenceIds\", \"reference_ids\"],\n\t\t[\"inputAudio\", \"input_audio\"],\n\t] as const) {\n\t\tremapMistralProperty(wireChunk, source, target);\n\t}\n\treturn wireChunk;\n}\n\nfunction remapMistralProperty(record: Record<string, unknown>, source: string, target: string): void {\n\tif (!(source in record)) return;\n\trecord[target] = record[source];\n\tdelete record[source];\n}\n\nfunction isMistralRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nconst MISTRAL_STREAM_DONE = Symbol(\"mistral-stream-done\");\n\nasync function* readMistralEvents(\n\tbody: ReadableStream<Uint8Array>,\n\tsignal: AbortSignal,\n): AsyncGenerator<MistralCompletionEvent> {\n\tconst reader = body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = \"\";\n\tconst onAbort = () => {\n\t\tvoid reader.cancel().catch(() => {});\n\t};\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\n\ttry {\n\t\twhile (true) {\n\t\t\tif (signal.aborted) throw signal.reason;\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (signal.aborted) throw signal.reason;\n\t\t\tbuffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n\n\t\t\tlet boundary = findMistralEventBoundary(buffer);\n\t\t\twhile (boundary) {\n\t\t\t\tconst event = parseMistralEvent(buffer.slice(0, boundary.index));\n\t\t\t\tbuffer = buffer.slice(boundary.index + boundary.length);\n\t\t\t\tif (event === MISTRAL_STREAM_DONE) return;\n\t\t\t\tif (event) yield event;\n\t\t\t\tboundary = findMistralEventBoundary(buffer);\n\t\t\t}\n\n\t\t\tif (done) break;\n\t\t}\n\n\t\tif (buffer.trim()) {\n\t\t\tconst event = parseMistralEvent(buffer);\n\t\t\tif (event !== MISTRAL_STREAM_DONE && event) yield event;\n\t\t}\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\ttry {\n\t\t\tawait reader.cancel();\n\t\t} catch {}\n\t\ttry {\n\t\t\treader.releaseLock();\n\t\t} catch {}\n\t}\n}\n\nfunction findMistralEventBoundary(buffer: string): { index: number; length: number } | undefined {\n\tconst match = /\\r\\n\\r\\n|\\r\\n\\r|\\r\\n\\n|\\r\\r\\n|\\n\\r\\n|\\r\\r|\\n\\r|\\n\\n/u.exec(buffer);\n\treturn match?.index === undefined ? undefined : { index: match.index, length: match[0].length };\n}\n\nfunction parseMistralEvent(raw: string): MistralCompletionEvent | typeof MISTRAL_STREAM_DONE | undefined {\n\tconst data = raw\n\t\t.split(/\\r\\n|\\r|\\n/u)\n\t\t.filter((line) => line.startsWith(\"data:\"))\n\t\t.map((line) => line.slice(5).trimStart())\n\t\t.join(\"\\n\")\n\t\t.trim();\n\tif (!data) return undefined;\n\tif (data === \"[DONE]\") return MISTRAL_STREAM_DONE;\n\n\tconst parsed: unknown = JSON.parse(data);\n\tif (!isMistralRecord(parsed) || !Array.isArray(parsed.choices)) {\n\t\tthrow new Error(\"Invalid Mistral streaming event\");\n\t}\n\treturn { data: parsed as MistralCompletionEvent[\"data\"] };\n}\n\nfunction buildChatPayload(\n\tmodel: Model<\"mistral-conversations\">,\n\tcontext: Context,\n\tmessages: Message[],\n\toptions?: MistralOptions,\n): MistralChatPayload {\n\tconst payload: MistralChatPayload = {\n\t\tmodel: model.id,\n\t\tstream: true,\n\t\tmessages: toChatMessages(messages, model.input.includes(\"image\")),\n\t};\n\n\tif (context.tools?.length) payload.tools = toFunctionTools(context.tools);\n\tif (options?.temperature !== undefined) payload.temperature = options.temperature;\n\tif (options?.maxTokens !== undefined) payload.maxTokens = options.maxTokens;\n\tif (options?.toolChoice) payload.toolChoice = mapToolChoice(options.toolChoice);\n\tif (options?.promptMode) payload.promptMode = options.promptMode;\n\tif (options?.reasoningEffort) payload.reasoningEffort = options.reasoningEffort;\n\tif (shouldUsePromptCaching(options)) payload.promptCacheKey = options.sessionId;\n\n\tif (context.systemPrompt) {\n\t\tpayload.messages.unshift({\n\t\t\trole: \"system\",\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\n\treturn payload;\n}\n\nfunction shouldUsePromptCaching(options?: MistralOptions): options is MistralOptions & { sessionId: string } {\n\treturn options?.cacheRetention !== \"none\" && !!options?.sessionId;\n}\n\nfunction getMistralCachedPromptTokens(usage: unknown, promptTokens: number): number {\n\tconst rawUsage = usage as {\n\t\tpromptTokensDetails?: { cachedTokens?: unknown } | null;\n\t\tprompt_tokens_details?: { cached_tokens?: unknown } | null;\n\t\tpromptTokenDetails?: { cachedTokens?: unknown } | null;\n\t\tprompt_token_details?: { cached_tokens?: unknown } | null;\n\t\tnumCachedTokens?: unknown;\n\t\tnum_cached_tokens?: unknown;\n\t};\n\tconst rawCachedTokens =\n\t\trawUsage.promptTokensDetails?.cachedTokens ??\n\t\trawUsage.prompt_tokens_details?.cached_tokens ??\n\t\trawUsage.promptTokenDetails?.cachedTokens ??\n\t\trawUsage.prompt_token_details?.cached_tokens ??\n\t\trawUsage.numCachedTokens ??\n\t\trawUsage.num_cached_tokens ??\n\t\t0;\n\tconst cachedTokens = typeof rawCachedTokens === \"number\" && Number.isFinite(rawCachedTokens) ? rawCachedTokens : 0;\n\treturn Math.min(promptTokens, Math.max(0, cachedTokens));\n}\n\nasync function consumeChatStream(\n\tmodel: Model<\"mistral-conversations\">,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmistralStream: AsyncIterable<MistralCompletionEvent>,\n): Promise<void> {\n\tlet currentBlock: TextContent | ThinkingContent | null = null;\n\tconst blocks = output.content;\n\tconst blockIndex = () => blocks.length - 1;\n\tconst toolBlocksByKey = new Map<string, number>();\n\n\tconst finishCurrentBlock = (block?: typeof currentBlock) => {\n\t\tif (!block) return;\n\t\tif (block.type === \"text\") {\n\t\t\tstream.push({\n\t\t\t\ttype: \"text_end\",\n\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\tcontent: block.text,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (block.type === \"thinking\") {\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_end\",\n\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\tcontent: block.thinking,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t}\n\t};\n\n\tfor await (const event of mistralStream) {\n\t\tconst chunk = event.data;\n\t\t// Mistral's streamed CompletionChunk carries an id field. Keep the first non-empty one,\n\t\t// mirroring how OpenAI-style streaming exposes a stable response identifier per stream.\n\t\toutput.responseId ||= chunk.id;\n\n\t\tif (chunk.usage) {\n\t\t\tconst promptTokens = chunk.usage.prompt_tokens || 0;\n\t\t\tconst cachedPromptTokens = getMistralCachedPromptTokens(chunk.usage, promptTokens);\n\n\t\t\toutput.usage.input = Math.max(0, promptTokens - cachedPromptTokens);\n\t\t\toutput.usage.output = chunk.usage.completion_tokens || 0;\n\t\t\toutput.usage.cacheRead = cachedPromptTokens;\n\t\t\toutput.usage.cacheWrite = 0;\n\t\t\toutput.usage.totalTokens =\n\t\t\t\tchunk.usage.total_tokens ||\n\t\t\t\toutput.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;\n\t\t\tcalculateCost(model, output.usage);\n\t\t}\n\n\t\tconst choice = chunk.choices[0];\n\t\tif (!choice) continue;\n\n\t\tif (choice.finish_reason) {\n\t\t\toutput.rawStopReason = choice.finish_reason;\n\t\t\tconst stopReasonResult = mapChatStopReason(choice.finish_reason);\n\t\t\toutput.stopReason = stopReasonResult.stopReason;\n\t\t\tif (stopReasonResult.errorMessage) {\n\t\t\t\toutput.errorMessage = stopReasonResult.errorMessage;\n\t\t\t}\n\t\t}\n\n\t\tconst delta = choice.delta;\n\t\tif (delta.content !== null && delta.content !== undefined) {\n\t\t\tconst contentItems = typeof delta.content === \"string\" ? [delta.content] : delta.content;\n\t\t\tfor (const item of contentItems) {\n\t\t\t\tif (typeof item === \"string\") {\n\t\t\t\t\tconst textDelta = sanitizeSurrogates(item);\n\t\t\t\t\tif (!currentBlock || currentBlock.type !== \"text\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t\tcurrentBlock.text += textDelta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: textDelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (item.type === \"thinking\") {\n\t\t\t\t\tconst deltaText = (item.thinking ?? [])\n\t\t\t\t\t\t.map((part) => part.text ?? \"\")\n\t\t\t\t\t\t.filter((text) => text.length > 0)\n\t\t\t\t\t\t.join(\"\");\n\t\t\t\t\tconst thinkingDelta = sanitizeSurrogates(deltaText);\n\t\t\t\t\tif (!thinkingDelta) continue;\n\t\t\t\t\tif (!currentBlock || currentBlock.type !== \"thinking\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t\tcurrentBlock.thinking += thinkingDelta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: thinkingDelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\tconst textDelta = sanitizeSurrogates(item.text ?? \"\");\n\t\t\t\t\tif (!currentBlock || currentBlock.type !== \"text\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t\tcurrentBlock.text += textDelta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: textDelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst toolCalls = delta.tool_calls || [];\n\t\tfor (const toolCall of toolCalls) {\n\t\t\tif (currentBlock) {\n\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\tcurrentBlock = null;\n\t\t\t}\n\t\t\tconst callId =\n\t\t\t\ttoolCall.id && toolCall.id !== \"null\"\n\t\t\t\t\t? toolCall.id\n\t\t\t\t\t: deriveMistralToolCallId(`toolcall:${toolCall.index ?? 0}`, 0);\n\t\t\tconst key = `${callId}:${toolCall.index || 0}`;\n\t\t\tconst existingIndex = toolBlocksByKey.get(key);\n\t\t\tlet block: (ToolCall & { partialArgs?: string }) | undefined;\n\n\t\t\tif (existingIndex !== undefined) {\n\t\t\t\tconst existing = output.content[existingIndex];\n\t\t\t\tif (existing?.type === \"toolCall\") {\n\t\t\t\t\tblock = existing as ToolCall & { partialArgs?: string };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!block) {\n\t\t\t\tblock = {\n\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\tid: callId,\n\t\t\t\t\tname: toolCall.function.name,\n\t\t\t\t\targuments: {},\n\t\t\t\t\tpartialArgs: \"\",\n\t\t\t\t};\n\t\t\t\toutput.content.push(block);\n\t\t\t\ttoolBlocksByKey.set(key, output.content.length - 1);\n\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: output.content.length - 1, partial: output });\n\t\t\t}\n\n\t\t\tconst argsDelta =\n\t\t\t\ttypeof toolCall.function.arguments === \"string\"\n\t\t\t\t\t? toolCall.function.arguments\n\t\t\t\t\t: JSON.stringify(toolCall.function.arguments || {});\n\t\t\tblock.partialArgs = (block.partialArgs || \"\") + argsDelta;\n\t\t\tblock.arguments = parseStreamingJson<Record<string, unknown>>(block.partialArgs);\n\t\t\tstream.push({\n\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\tcontentIndex: toolBlocksByKey.get(key)!,\n\t\t\t\tdelta: argsDelta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t}\n\t}\n\n\tfinishCurrentBlock(currentBlock);\n\tfor (const index of toolBlocksByKey.values()) {\n\t\tconst block = output.content[index];\n\t\tif (block.type !== \"toolCall\") continue;\n\t\tconst toolBlock = block as ToolCall & { partialArgs?: string };\n\t\ttoolBlock.arguments = parseStreamingJson<Record<string, unknown>>(toolBlock.partialArgs);\n\t\t// Finalize in-place and strip the scratch buffer so replay only\n\t\t// carries parsed arguments.\n\t\tdelete toolBlock.partialArgs;\n\t\tstream.push({\n\t\t\ttype: \"toolcall_end\",\n\t\t\tcontentIndex: index,\n\t\t\ttoolCall: toolBlock,\n\t\t\tpartial: output,\n\t\t});\n\t}\n}\n\nfunction toFunctionTools(tools: Tool[]): MistralFunctionTool[] {\n\treturn tools.map((tool) => {\n\t\tconst strict = resolveJsonSchemaStrictSampling(tool, true);\n\t\treturn {\n\t\t\ttype: \"function\",\n\t\t\tfunction: {\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tparameters: stripSymbolKeys(getJsonSchemaToolParameters(tool, strict)) as Record<string, unknown>,\n\t\t\t\tstrict: strict ?? false,\n\t\t\t},\n\t\t};\n\t});\n}\n\nfunction stripSymbolKeys(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\treturn value.map((item) => stripSymbolKeys(item));\n\t}\n\n\tif (value && typeof value === \"object\") {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, entry] of Object.entries(value)) {\n\t\t\tresult[key] = stripSymbolKeys(entry);\n\t\t}\n\t\treturn result;\n\t}\n\n\treturn value;\n}\n\nfunction toChatMessages(messages: Message[], supportsImages: boolean): MistralChatMessage[] {\n\tconst result: MistralChatMessage[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tresult.push({ role: \"user\", content: sanitizeSurrogates(msg.content) });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst hadImages = msg.content.some((item) => item.type === \"image\");\n\t\t\tconst content: MistralContentChunk[] = msg.content\n\t\t\t\t.filter((item) => item.type === \"text\" || supportsImages)\n\t\t\t\t.map((item) => {\n\t\t\t\t\tif (item.type === \"text\") return { type: \"text\", text: sanitizeSurrogates(item.text) };\n\t\t\t\t\treturn { type: \"image_url\", imageUrl: `data:${item.mimeType};base64,${item.data}` };\n\t\t\t\t});\n\t\t\tif (content.length > 0) {\n\t\t\t\tresult.push({ role: \"user\", content });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (hadImages && !supportsImages) {\n\t\t\t\tresult.push({ role: \"user\", content: \"(image omitted: model does not support images)\" });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst contentParts: MistralContentChunk[] = [];\n\t\t\tconst toolCalls: MistralRequestToolCall[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (block.text.trim().length > 0) {\n\t\t\t\t\t\tcontentParts.push({ type: \"text\", text: sanitizeSurrogates(block.text) });\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (block.thinking.trim().length > 0) {\n\t\t\t\t\t\tcontentParts.push({\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: [{ type: \"text\", text: sanitizeSurrogates(block.thinking) }],\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttoolCalls.push({\n\t\t\t\t\tid: block.id,\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tfunction: { name: block.name, arguments: JSON.stringify(block.arguments || {}) },\n\t\t\t\t\tindex: 0,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst assistantMessage: MistralChatMessage = { role: \"assistant\", prefix: false };\n\t\t\tif (contentParts.length > 0) assistantMessage.content = contentParts;\n\t\t\tif (toolCalls.length > 0) assistantMessage.toolCalls = toolCalls;\n\t\t\tif (contentParts.length > 0 || toolCalls.length > 0) result.push(assistantMessage);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst toolContent: MistralContentChunk[] = [];\n\t\tconst textResult = msg.content\n\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t.map((part) => (part.type === \"text\" ? sanitizeSurrogates(part.text) : \"\"))\n\t\t\t.join(\"\\n\");\n\t\tconst hasImages = msg.content.some((part) => part.type === \"image\");\n\t\tconst toolText = buildToolResultText(textResult, hasImages, supportsImages, msg.isError);\n\t\ttoolContent.push({ type: \"text\", text: toolText });\n\t\tfor (const part of msg.content) {\n\t\t\tif (!supportsImages) continue;\n\t\t\tif (part.type !== \"image\") continue;\n\t\t\ttoolContent.push({\n\t\t\t\ttype: \"image_url\",\n\t\t\t\timageUrl: `data:${part.mimeType};base64,${part.data}`,\n\t\t\t});\n\t\t}\n\t\tresult.push({\n\t\t\trole: \"tool\",\n\t\t\ttoolCallId: msg.toolCallId,\n\t\t\tname: msg.toolName,\n\t\t\tcontent: toolContent,\n\t\t});\n\t}\n\n\treturn result;\n}\n\nfunction buildToolResultText(text: string, hasImages: boolean, supportsImages: boolean, isError: boolean): string {\n\tconst trimmed = text.trim();\n\tconst errorPrefix = isError ? \"[tool error] \" : \"\";\n\n\tif (trimmed.length > 0) {\n\t\tconst imageSuffix = hasImages && !supportsImages ? \"\\n[tool image omitted: model does not support images]\" : \"\";\n\t\treturn `${errorPrefix}${trimmed}${imageSuffix}`;\n\t}\n\n\tif (hasImages) {\n\t\tif (supportsImages) {\n\t\t\treturn isError ? \"[tool error] (see attached image)\" : \"(see attached image)\";\n\t\t}\n\t\treturn isError\n\t\t\t? \"[tool error] (image omitted: model does not support images)\"\n\t\t\t: \"(image omitted: model does not support images)\";\n\t}\n\n\treturn isError ? \"[tool error] (no tool output)\" : \"(no tool output)\";\n}\n\nfunction usesReasoningEffort(model: Model<\"mistral-conversations\">): boolean {\n\treturn model.id === \"mistral-small-2603\" || model.id === \"mistral-small-latest\" || model.id === \"mistral-medium-3.5\";\n}\n\nfunction usesPromptModeReasoning(model: Model<\"mistral-conversations\">): boolean {\n\treturn model.reasoning && !usesReasoningEffort(model);\n}\n\nfunction mapReasoningEffort(\n\tmodel: Model<\"mistral-conversations\">,\n\tlevel: Exclude<SimpleStreamOptions[\"reasoning\"], undefined>,\n): MistralReasoningEffort {\n\treturn (model.thinkingLevelMap?.[level] ?? \"high\") as MistralReasoningEffort;\n}\n\nfunction mapToolChoice(\n\tchoice: MistralOptions[\"toolChoice\"],\n): \"auto\" | \"none\" | \"any\" | \"required\" | { type: \"function\"; function: { name: string } } | undefined {\n\tif (!choice) return undefined;\n\tif (choice === \"auto\" || choice === \"none\" || choice === \"any\" || choice === \"required\") {\n\t\treturn choice;\n\t}\n\treturn {\n\t\ttype: \"function\",\n\t\tfunction: { name: choice.function.name },\n\t};\n}\n\nfunction mapChatStopReason(reason: string | null): { stopReason: StopReason; errorMessage?: string } {\n\tif (reason === null) return { stopReason: \"stop\" };\n\tswitch (reason) {\n\t\tcase \"stop\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"length\":\n\t\tcase \"model_length\":\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase \"tool_calls\":\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tcase \"error\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider stopped with: error\" };\n\t\tdefault:\n\t\t\treturn { stopReason: \"error\", errorMessage: `Provider stopped with: ${reason}` };\n\t}\n}\n"]}
1
+ {"version":3,"file":"mistral-conversations.d.ts","sourceRoot":"","sources":["../../src/api/mistral-conversations.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAKX,mBAAmB,EAEnB,cAAc,EACd,aAAa,EAKb,MAAM,aAAa,CAAC;AAcrB;;GAEG;AACH,KAAK,sBAAsB,GAAG,MAAM,GAAG,MAAM,CAAC;AAE9C,MAAM,WAAW,cAAe,SAAQ,aAAa;IACpD,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG,UAAU,GAAG;QAAE,IAAI,EAAE,UAAU,CAAC;QAAC,QAAQ,EAAE;YAAE,IAAI,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAC;IACrG,UAAU,CAAC,EAAE,WAAW,CAAC;IACzB,eAAe,CAAC,EAAE,sBAAsB,CAAC;CACzC;AAiFD;;GAEG;AACH,eAAO,MAAM,MAAM,EAAE,cAAc,CAAC,uBAAuB,EAAE,cAAc,CAsD1E,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,YAAY,EAAE,cAAc,CAAC,uBAAuB,EAAE,mBAAmB,CAwBrF,CAAC","sourcesContent":["import { calculateCost, clampThinkingLevel } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tContext,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n} from \"../types.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { getJsonSchemaToolParameters, resolveJsonSchemaStrictSampling } from \"./constrained-sampling.ts\";\nimport { buildBaseOptions } from \"./simple-options.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\nconst MISTRAL_TOOL_CALL_ID_LENGTH = 9;\nconst MAX_MISTRAL_ERROR_BODY_CHARS = 4000;\n\n/**\n * Provider-specific options for the Mistral API.\n */\ntype MistralReasoningEffort = \"none\" | \"high\";\n\nexport interface MistralOptions extends StreamOptions {\n\ttoolChoice?: \"auto\" | \"none\" | \"any\" | \"required\" | { type: \"function\"; function: { name: string } };\n\tpromptMode?: \"reasoning\";\n\treasoningEffort?: MistralReasoningEffort;\n}\n\ntype MistralContentChunk =\n\t| { type: \"text\"; text: string }\n\t| { type: \"image_url\"; imageUrl: string }\n\t| { type: \"thinking\"; thinking: Array<{ type: \"text\"; text: string }> };\n\ntype MistralRequestToolCall = {\n\tid: string;\n\ttype: \"function\";\n\tfunction: { name: string; arguments: string };\n\tindex: number;\n};\n\ntype MistralChatMessage = {\n\trole: \"system\" | \"user\" | \"assistant\" | \"tool\";\n\tcontent?: string | MistralContentChunk[];\n\ttoolCalls?: MistralRequestToolCall[];\n\ttoolCallId?: string;\n\tname?: string;\n\tprefix?: boolean;\n};\n\ntype MistralFunctionTool = {\n\ttype: \"function\";\n\tfunction: {\n\t\tname: string;\n\t\tdescription: string;\n\t\tparameters: Record<string, unknown>;\n\t\tstrict: boolean;\n\t};\n};\n\ntype MistralChatPayload = {\n\t[key: string]: unknown;\n\tmodel: string;\n\tstream: boolean;\n\tmessages: MistralChatMessage[];\n\ttools?: MistralFunctionTool[];\n\ttemperature?: number;\n\tmaxTokens?: number;\n\ttoolChoice?: Exclude<MistralOptions[\"toolChoice\"], undefined>;\n\tpromptMode?: \"reasoning\";\n\treasoningEffort?: MistralReasoningEffort;\n\tpromptCacheKey?: string;\n};\n\ntype MistralStreamContentChunk = {\n\ttype: string;\n\ttext?: string;\n\tthinking?: Array<{ text?: string }>;\n};\n\ntype MistralStreamToolCall = {\n\tid?: string;\n\tindex?: number;\n\tfunction: {\n\t\tname: string;\n\t\targuments: string | Record<string, unknown>;\n\t};\n};\n\ntype MistralCompletionEvent = {\n\tdata: {\n\t\tid?: string;\n\t\tusage?: {\n\t\t\t[key: string]: unknown;\n\t\t\tprompt_tokens?: number;\n\t\t\tcompletion_tokens?: number;\n\t\t\ttotal_tokens?: number;\n\t\t};\n\t\tchoices: Array<{\n\t\t\tfinish_reason?: string | null;\n\t\t\tdelta: {\n\t\t\t\tcontent?: string | MistralStreamContentChunk[] | null;\n\t\t\t\ttool_calls?: MistralStreamToolCall[] | null;\n\t\t\t};\n\t\t}>;\n\t};\n};\n\n/**\n * Stream responses from the native Mistral Chat Completions endpoint.\n */\nexport const stream: StreamFunction<\"mistral-conversations\", MistralOptions> = (\n\tmodel: Model<\"mistral-conversations\">,\n\tcontext: Context,\n\toptions?: MistralOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output = createOutput(model);\n\n\t\ttry {\n\t\t\tconst apiKey = options?.apiKey;\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t\t\t}\n\n\t\t\tconst normalizeMistralToolCallId = createMistralToolCallIdNormalizer();\n\t\t\tconst transformedMessages = transformMessages(context.messages, model, (id) => normalizeMistralToolCallId(id));\n\n\t\t\tlet payload = buildChatPayload(model, context, transformedMessages, options);\n\t\t\tconst nextPayload = await options?.onPayload?.(payload, model);\n\t\t\tif (nextPayload !== undefined) {\n\t\t\t\tpayload = nextPayload as MistralChatPayload;\n\t\t\t}\n\t\t\tconst mistralStream = await requestMistralStream(model, payload, apiKey, options);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\tawait consumeChatStream(model, output, stream, mistralStream);\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"pending\") {\n\t\t\t\tthrow new Error(\"Mistral stream ended without a finish reason\");\n\t\t\t}\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(output.errorMessage || \"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\t// partialArgs is only a streaming scratch buffer; never persist it.\n\t\t\t\tdelete (block as { partialArgs?: string }).partialArgs;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatMistralError(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\n/**\n * Maps provider-agnostic `SimpleStreamOptions` to Mistral options.\n */\nexport const streamSimple: StreamFunction<\"mistral-conversations\", SimpleStreamOptions> = (\n\tmodel: Model<\"mistral-conversations\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = {\n\t\t...buildBaseOptions(model, context, options, apiKey),\n\t\ttoolChoice: options?.toolChoice,\n\t} satisfies MistralOptions;\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoning = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\tconst shouldUseReasoning = model.reasoning && reasoning !== undefined;\n\n\treturn stream(model, context, {\n\t\t...base,\n\t\tpromptMode: shouldUseReasoning && usesPromptModeReasoning(model) ? \"reasoning\" : undefined,\n\t\treasoningEffort:\n\t\t\tshouldUseReasoning && usesReasoningEffort(model) ? mapReasoningEffort(model, reasoning) : undefined,\n\t} satisfies MistralOptions);\n};\n\nfunction createOutput(model: Model<\"mistral-conversations\">): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"pending\",\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createMistralToolCallIdNormalizer(): (id: string) => string {\n\tconst idMap = new Map<string, string>();\n\tconst reverseMap = new Map<string, string>();\n\n\treturn (id: string): string => {\n\t\tconst existing = idMap.get(id);\n\t\tif (existing) return existing;\n\n\t\tlet attempt = 0;\n\t\twhile (true) {\n\t\t\tconst candidate = deriveMistralToolCallId(id, attempt);\n\t\t\tconst owner = reverseMap.get(candidate);\n\t\t\tif (!owner || owner === id) {\n\t\t\t\tidMap.set(id, candidate);\n\t\t\t\treverseMap.set(candidate, id);\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t\tattempt++;\n\t\t}\n\t};\n}\n\nfunction deriveMistralToolCallId(id: string, attempt: number): string {\n\tconst normalized = id.replace(/[^a-zA-Z0-9]/g, \"\");\n\tif (attempt === 0 && normalized.length === MISTRAL_TOOL_CALL_ID_LENGTH) return normalized;\n\tconst seedBase = normalized || id;\n\tconst seed = attempt === 0 ? seedBase : `${seedBase}:${attempt}`;\n\treturn shortHash(seed)\n\t\t.replace(/[^a-zA-Z0-9]/g, \"\")\n\t\t.slice(0, MISTRAL_TOOL_CALL_ID_LENGTH);\n}\n\nfunction formatMistralError(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tconst httpError = error as Error & { statusCode?: unknown; body?: unknown };\n\t\tconst statusCode = typeof httpError.statusCode === \"number\" ? httpError.statusCode : undefined;\n\t\tconst bodyText = typeof httpError.body === \"string\" ? httpError.body.trim() : undefined;\n\t\tif (statusCode !== undefined && bodyText) {\n\t\t\treturn `Mistral API error (${statusCode}): ${truncateErrorText(bodyText, MAX_MISTRAL_ERROR_BODY_CHARS)}`;\n\t\t}\n\t\tif (statusCode !== undefined) return `Mistral API error (${statusCode}): ${error.message}`;\n\t\treturn error.message;\n\t}\n\treturn safeJsonStringify(error);\n}\n\nfunction truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\nfunction safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nasync function requestMistralStream(\n\tmodel: Model<\"mistral-conversations\">,\n\tpayload: MistralChatPayload,\n\tapiKey: string,\n\toptions?: MistralOptions,\n): Promise<AsyncIterable<MistralCompletionEvent>> {\n\tconst baseUrl = new URL(model.baseUrl);\n\tbaseUrl.pathname = `${baseUrl.pathname.replace(/\\/+$/u, \"\")}/`;\n\tconst url = new URL(\"v1/chat/completions\", baseUrl);\n\tconst headers = buildMistralHeaders(model, apiKey, options);\n\tconst timeoutSignal = AbortSignal.timeout(options?.timeoutMs ?? 60_000);\n\tconst signal = options?.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;\n\tconst response = await (options?.fetch ?? globalThis.fetch)(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(toMistralWirePayload(payload)),\n\t\tsignal,\n\t});\n\n\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\n\tif (!response.ok) {\n\t\tconst body = await response.text();\n\t\tthrow new MistralHttpError(response.status, body, response.statusText);\n\t}\n\tif (!response.body) {\n\t\tthrow new Error(\"Mistral response has no body\");\n\t}\n\n\treturn readMistralEvents(response.body, signal);\n}\n\nclass MistralHttpError extends Error {\n\tstatusCode: number;\n\tbody: string;\n\n\tconstructor(statusCode: number, body: string, statusText: string) {\n\t\tsuper(statusText || `Request failed with status ${statusCode}`);\n\t\tthis.name = \"MistralHttpError\";\n\t\tthis.statusCode = statusCode;\n\t\tthis.body = body;\n\t}\n}\n\nfunction buildMistralHeaders(model: Model<\"mistral-conversations\">, apiKey: string, options?: MistralOptions): Headers {\n\tconst headers = new Headers({\n\t\t\"User-Agent\": getPiUserAgent(),\n\t\taccept: \"text/event-stream\",\n\t\tauthorization: `Bearer ${apiKey}`,\n\t\t\"content-type\": \"application/json\",\n\t});\n\tapplyMistralHeaderOverrides(headers, model.headers);\n\tapplyMistralHeaderOverrides(headers, options?.headers);\n\n\tconst hasExplicitAffinity =\n\t\thasMistralHeaderOverride(model.headers, \"x-affinity\") || hasMistralHeaderOverride(options?.headers, \"x-affinity\");\n\tif (shouldUsePromptCaching(options) && !hasExplicitAffinity) {\n\t\theaders.set(\"x-affinity\", options.sessionId);\n\t}\n\n\treturn headers;\n}\n\nfunction applyMistralHeaderOverrides(headers: Headers, overrides?: Record<string, string | null>): void {\n\tif (!overrides) return;\n\tfor (const [name, value] of Object.entries(overrides)) {\n\t\tif (value === null) headers.delete(name);\n\t\telse headers.set(name, value);\n\t}\n}\n\nfunction hasMistralHeaderOverride(overrides: Record<string, string | null> | undefined, target: string): boolean {\n\treturn !!overrides && Object.keys(overrides).some((name) => name.toLowerCase() === target);\n}\n\nfunction toMistralWirePayload(payload: MistralChatPayload): Record<string, unknown> {\n\tconst wirePayload: Record<string, unknown> = { ...payload };\n\tfor (const [source, target] of [\n\t\t[\"topP\", \"top_p\"],\n\t\t[\"maxTokens\", \"max_tokens\"],\n\t\t[\"randomSeed\", \"random_seed\"],\n\t\t[\"responseFormat\", \"response_format\"],\n\t\t[\"toolChoice\", \"tool_choice\"],\n\t\t[\"presencePenalty\", \"presence_penalty\"],\n\t\t[\"frequencyPenalty\", \"frequency_penalty\"],\n\t\t[\"parallelToolCalls\", \"parallel_tool_calls\"],\n\t\t[\"reasoningEffort\", \"reasoning_effort\"],\n\t\t[\"promptMode\", \"prompt_mode\"],\n\t\t[\"promptCacheKey\", \"prompt_cache_key\"],\n\t\t[\"safePrompt\", \"safe_prompt\"],\n\t] as const) {\n\t\tremapMistralProperty(wirePayload, source, target);\n\t}\n\twirePayload.messages = payload.messages.map((message) => toMistralWireMessage(message));\n\n\tconst responseFormat = wirePayload.response_format;\n\tif (isMistralRecord(responseFormat)) {\n\t\tconst wireResponseFormat = { ...responseFormat };\n\t\tremapMistralProperty(wireResponseFormat, \"jsonSchema\", \"json_schema\");\n\t\tconst jsonSchema = wireResponseFormat.json_schema;\n\t\tif (isMistralRecord(jsonSchema)) {\n\t\t\tconst wireJsonSchema = { ...jsonSchema };\n\t\t\tremapMistralProperty(wireJsonSchema, \"schemaDefinition\", \"schema\");\n\t\t\twireResponseFormat.json_schema = wireJsonSchema;\n\t\t}\n\t\twirePayload.response_format = wireResponseFormat;\n\t}\n\n\treturn wirePayload;\n}\n\nfunction toMistralWireMessage(message: MistralChatMessage): Record<string, unknown> {\n\tconst wireMessage: Record<string, unknown> = { ...message };\n\tremapMistralProperty(wireMessage, \"toolCalls\", \"tool_calls\");\n\tremapMistralProperty(wireMessage, \"toolCallId\", \"tool_call_id\");\n\tif (Array.isArray(message.content)) {\n\t\twireMessage.content = message.content.map((chunk) => toMistralWireContentChunk(chunk));\n\t}\n\treturn wireMessage;\n}\n\nfunction toMistralWireContentChunk(chunk: MistralContentChunk): Record<string, unknown> {\n\tconst wireChunk: Record<string, unknown> = { ...chunk };\n\tfor (const [source, target] of [\n\t\t[\"imageUrl\", \"image_url\"],\n\t\t[\"documentUrl\", \"document_url\"],\n\t\t[\"documentName\", \"document_name\"],\n\t\t[\"fileId\", \"file_id\"],\n\t\t[\"referenceIds\", \"reference_ids\"],\n\t\t[\"inputAudio\", \"input_audio\"],\n\t] as const) {\n\t\tremapMistralProperty(wireChunk, source, target);\n\t}\n\treturn wireChunk;\n}\n\nfunction remapMistralProperty(record: Record<string, unknown>, source: string, target: string): void {\n\tif (!(source in record)) return;\n\trecord[target] = record[source];\n\tdelete record[source];\n}\n\nfunction isMistralRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nconst MISTRAL_STREAM_DONE = Symbol(\"mistral-stream-done\");\n\nasync function* readMistralEvents(\n\tbody: ReadableStream<Uint8Array>,\n\tsignal: AbortSignal,\n): AsyncGenerator<MistralCompletionEvent> {\n\tconst reader = body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = \"\";\n\tconst onAbort = () => {\n\t\tvoid reader.cancel().catch(() => {});\n\t};\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\n\ttry {\n\t\twhile (true) {\n\t\t\tif (signal.aborted) throw signal.reason;\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (signal.aborted) throw signal.reason;\n\t\t\tbuffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n\n\t\t\tlet boundary = findMistralEventBoundary(buffer);\n\t\t\twhile (boundary) {\n\t\t\t\tconst event = parseMistralEvent(buffer.slice(0, boundary.index));\n\t\t\t\tbuffer = buffer.slice(boundary.index + boundary.length);\n\t\t\t\tif (event === MISTRAL_STREAM_DONE) return;\n\t\t\t\tif (event) yield event;\n\t\t\t\tboundary = findMistralEventBoundary(buffer);\n\t\t\t}\n\n\t\t\tif (done) break;\n\t\t}\n\n\t\tif (buffer.trim()) {\n\t\t\tconst event = parseMistralEvent(buffer);\n\t\t\tif (event !== MISTRAL_STREAM_DONE && event) yield event;\n\t\t}\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\ttry {\n\t\t\tawait reader.cancel();\n\t\t} catch {}\n\t\ttry {\n\t\t\treader.releaseLock();\n\t\t} catch {}\n\t}\n}\n\nfunction findMistralEventBoundary(buffer: string): { index: number; length: number } | undefined {\n\tconst match = /\\r\\n\\r\\n|\\r\\n\\r|\\r\\n\\n|\\r\\r\\n|\\n\\r\\n|\\r\\r|\\n\\r|\\n\\n/u.exec(buffer);\n\treturn match?.index === undefined ? undefined : { index: match.index, length: match[0].length };\n}\n\nfunction parseMistralEvent(raw: string): MistralCompletionEvent | typeof MISTRAL_STREAM_DONE | undefined {\n\tconst data = raw\n\t\t.split(/\\r\\n|\\r|\\n/u)\n\t\t.filter((line) => line.startsWith(\"data:\"))\n\t\t.map((line) => line.slice(5).trimStart())\n\t\t.join(\"\\n\")\n\t\t.trim();\n\tif (!data) return undefined;\n\tif (data === \"[DONE]\") return MISTRAL_STREAM_DONE;\n\n\tconst parsed: unknown = JSON.parse(data);\n\tif (!isMistralRecord(parsed) || !Array.isArray(parsed.choices)) {\n\t\tthrow new Error(\"Invalid Mistral streaming event\");\n\t}\n\treturn { data: parsed as MistralCompletionEvent[\"data\"] };\n}\n\nfunction buildChatPayload(\n\tmodel: Model<\"mistral-conversations\">,\n\tcontext: Context,\n\tmessages: Message[],\n\toptions?: MistralOptions,\n): MistralChatPayload {\n\tconst payload: MistralChatPayload = {\n\t\tmodel: model.id,\n\t\tstream: true,\n\t\tmessages: toChatMessages(messages, model.input.includes(\"image\")),\n\t};\n\n\tif (context.tools?.length) payload.tools = toFunctionTools(context.tools);\n\tif (options?.temperature !== undefined) payload.temperature = options.temperature;\n\tif (options?.maxTokens !== undefined) payload.maxTokens = options.maxTokens;\n\tif (options?.toolChoice) payload.toolChoice = mapToolChoice(options.toolChoice);\n\tif (options?.promptMode) payload.promptMode = options.promptMode;\n\tif (options?.reasoningEffort) payload.reasoningEffort = options.reasoningEffort;\n\tif (shouldUsePromptCaching(options)) payload.promptCacheKey = options.sessionId;\n\n\tif (context.systemPrompt) {\n\t\tpayload.messages.unshift({\n\t\t\trole: \"system\",\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\n\treturn payload;\n}\n\nfunction shouldUsePromptCaching(options?: MistralOptions): options is MistralOptions & { sessionId: string } {\n\treturn options?.cacheRetention !== \"none\" && !!options?.sessionId;\n}\n\nfunction getMistralCachedPromptTokens(usage: unknown, promptTokens: number): number {\n\tconst rawUsage = usage as {\n\t\tpromptTokensDetails?: { cachedTokens?: unknown } | null;\n\t\tprompt_tokens_details?: { cached_tokens?: unknown } | null;\n\t\tpromptTokenDetails?: { cachedTokens?: unknown } | null;\n\t\tprompt_token_details?: { cached_tokens?: unknown } | null;\n\t\tnumCachedTokens?: unknown;\n\t\tnum_cached_tokens?: unknown;\n\t};\n\tconst rawCachedTokens =\n\t\trawUsage.promptTokensDetails?.cachedTokens ??\n\t\trawUsage.prompt_tokens_details?.cached_tokens ??\n\t\trawUsage.promptTokenDetails?.cachedTokens ??\n\t\trawUsage.prompt_token_details?.cached_tokens ??\n\t\trawUsage.numCachedTokens ??\n\t\trawUsage.num_cached_tokens ??\n\t\t0;\n\tconst cachedTokens = typeof rawCachedTokens === \"number\" && Number.isFinite(rawCachedTokens) ? rawCachedTokens : 0;\n\treturn Math.min(promptTokens, Math.max(0, cachedTokens));\n}\n\nasync function consumeChatStream(\n\tmodel: Model<\"mistral-conversations\">,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmistralStream: AsyncIterable<MistralCompletionEvent>,\n): Promise<void> {\n\tlet currentBlock: TextContent | ThinkingContent | null = null;\n\tconst blocks = output.content;\n\tconst blockIndex = () => blocks.length - 1;\n\tconst toolBlocksByKey = new Map<string | number, number>();\n\n\tconst finishCurrentBlock = (block?: typeof currentBlock) => {\n\t\tif (!block) return;\n\t\tif (block.type === \"text\") {\n\t\t\tstream.push({\n\t\t\t\ttype: \"text_end\",\n\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\tcontent: block.text,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (block.type === \"thinking\") {\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_end\",\n\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\tcontent: block.thinking,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t}\n\t};\n\n\tfor await (const event of mistralStream) {\n\t\tconst chunk = event.data;\n\t\t// Mistral's streamed CompletionChunk carries an id field. Keep the first non-empty one,\n\t\t// mirroring how OpenAI-style streaming exposes a stable response identifier per stream.\n\t\toutput.responseId ||= chunk.id;\n\n\t\tif (chunk.usage) {\n\t\t\tconst promptTokens = chunk.usage.prompt_tokens || 0;\n\t\t\tconst cachedPromptTokens = getMistralCachedPromptTokens(chunk.usage, promptTokens);\n\n\t\t\toutput.usage.input = Math.max(0, promptTokens - cachedPromptTokens);\n\t\t\toutput.usage.output = chunk.usage.completion_tokens || 0;\n\t\t\toutput.usage.cacheRead = cachedPromptTokens;\n\t\t\toutput.usage.cacheWrite = 0;\n\t\t\toutput.usage.totalTokens =\n\t\t\t\tchunk.usage.total_tokens ||\n\t\t\t\toutput.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;\n\t\t\tcalculateCost(model, output.usage);\n\t\t}\n\n\t\tconst choice = chunk.choices[0];\n\t\tif (!choice) continue;\n\n\t\tif (choice.finish_reason) {\n\t\t\toutput.rawStopReason = choice.finish_reason;\n\t\t\tconst stopReasonResult = mapChatStopReason(choice.finish_reason);\n\t\t\toutput.stopReason = stopReasonResult.stopReason;\n\t\t\tif (stopReasonResult.errorMessage) {\n\t\t\t\toutput.errorMessage = stopReasonResult.errorMessage;\n\t\t\t}\n\t\t}\n\n\t\tconst delta = choice.delta;\n\t\tif (delta.content !== null && delta.content !== undefined) {\n\t\t\tconst contentItems = typeof delta.content === \"string\" ? [delta.content] : delta.content;\n\t\t\tfor (const item of contentItems) {\n\t\t\t\tif (typeof item === \"string\") {\n\t\t\t\t\tconst textDelta = sanitizeSurrogates(item);\n\t\t\t\t\tif (!currentBlock || currentBlock.type !== \"text\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t\tcurrentBlock.text += textDelta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: textDelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (item.type === \"thinking\") {\n\t\t\t\t\tconst deltaText = (item.thinking ?? [])\n\t\t\t\t\t\t.map((part) => part.text ?? \"\")\n\t\t\t\t\t\t.filter((text) => text.length > 0)\n\t\t\t\t\t\t.join(\"\");\n\t\t\t\t\tconst thinkingDelta = sanitizeSurrogates(deltaText);\n\t\t\t\t\tif (!thinkingDelta) continue;\n\t\t\t\t\tif (!currentBlock || currentBlock.type !== \"thinking\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t\tcurrentBlock.thinking += thinkingDelta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: thinkingDelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\tconst textDelta = sanitizeSurrogates(item.text ?? \"\");\n\t\t\t\t\tif (!currentBlock || currentBlock.type !== \"text\") {\n\t\t\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t\t\t}\n\t\t\t\t\tcurrentBlock.text += textDelta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: textDelta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst toolCalls = delta.tool_calls || [];\n\t\tfor (const toolCall of toolCalls) {\n\t\t\tif (currentBlock) {\n\t\t\t\tfinishCurrentBlock(currentBlock);\n\t\t\t\tcurrentBlock = null;\n\t\t\t}\n\t\t\tconst callId =\n\t\t\t\ttoolCall.id && toolCall.id !== \"null\"\n\t\t\t\t\t? toolCall.id\n\t\t\t\t\t: deriveMistralToolCallId(`toolcall:${toolCall.index ?? 0}`, 0);\n\t\t\tconst key = toolCall.index ?? callId;\n\t\t\tconst existingIndex = toolBlocksByKey.get(key);\n\t\t\tlet block: (ToolCall & { partialArgs?: string }) | undefined;\n\n\t\t\tif (existingIndex !== undefined) {\n\t\t\t\tconst existing = output.content[existingIndex];\n\t\t\t\tif (existing?.type === \"toolCall\") {\n\t\t\t\t\tblock = existing as ToolCall & { partialArgs?: string };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!block) {\n\t\t\t\tblock = {\n\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\tid: callId,\n\t\t\t\t\tname: toolCall.function.name,\n\t\t\t\t\targuments: {},\n\t\t\t\t\tpartialArgs: \"\",\n\t\t\t\t};\n\t\t\t\toutput.content.push(block);\n\t\t\t\ttoolBlocksByKey.set(key, output.content.length - 1);\n\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: output.content.length - 1, partial: output });\n\t\t\t}\n\n\t\t\tconst argsDelta =\n\t\t\t\ttypeof toolCall.function.arguments === \"string\"\n\t\t\t\t\t? toolCall.function.arguments\n\t\t\t\t\t: JSON.stringify(toolCall.function.arguments || {});\n\t\t\tblock.partialArgs = (block.partialArgs || \"\") + argsDelta;\n\t\t\tblock.arguments = parseStreamingJson<Record<string, unknown>>(block.partialArgs);\n\t\t\tstream.push({\n\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\tcontentIndex: toolBlocksByKey.get(key)!,\n\t\t\t\tdelta: argsDelta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t}\n\t}\n\n\tfinishCurrentBlock(currentBlock);\n\tfor (const index of toolBlocksByKey.values()) {\n\t\tconst block = output.content[index];\n\t\tif (block.type !== \"toolCall\") continue;\n\t\tconst toolBlock = block as ToolCall & { partialArgs?: string };\n\t\ttoolBlock.arguments = parseStreamingJson<Record<string, unknown>>(toolBlock.partialArgs);\n\t\t// Finalize in-place and strip the scratch buffer so replay only\n\t\t// carries parsed arguments.\n\t\tdelete toolBlock.partialArgs;\n\t\tstream.push({\n\t\t\ttype: \"toolcall_end\",\n\t\t\tcontentIndex: index,\n\t\t\ttoolCall: toolBlock,\n\t\t\tpartial: output,\n\t\t});\n\t}\n}\n\nfunction toFunctionTools(tools: Tool[]): MistralFunctionTool[] {\n\treturn tools.map((tool) => {\n\t\tconst strict = resolveJsonSchemaStrictSampling(tool, true);\n\t\treturn {\n\t\t\ttype: \"function\",\n\t\t\tfunction: {\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tparameters: stripSymbolKeys(getJsonSchemaToolParameters(tool, strict)) as Record<string, unknown>,\n\t\t\t\tstrict: strict ?? false,\n\t\t\t},\n\t\t};\n\t});\n}\n\nfunction stripSymbolKeys(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\treturn value.map((item) => stripSymbolKeys(item));\n\t}\n\n\tif (value && typeof value === \"object\") {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, entry] of Object.entries(value)) {\n\t\t\tresult[key] = stripSymbolKeys(entry);\n\t\t}\n\t\treturn result;\n\t}\n\n\treturn value;\n}\n\nfunction toChatMessages(messages: Message[], supportsImages: boolean): MistralChatMessage[] {\n\tconst result: MistralChatMessage[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tresult.push({ role: \"user\", content: sanitizeSurrogates(msg.content) });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst hadImages = msg.content.some((item) => item.type === \"image\");\n\t\t\tconst content: MistralContentChunk[] = msg.content\n\t\t\t\t.filter((item) => item.type === \"text\" || supportsImages)\n\t\t\t\t.map((item) => {\n\t\t\t\t\tif (item.type === \"text\") return { type: \"text\", text: sanitizeSurrogates(item.text) };\n\t\t\t\t\treturn { type: \"image_url\", imageUrl: `data:${item.mimeType};base64,${item.data}` };\n\t\t\t\t});\n\t\t\tif (content.length > 0) {\n\t\t\t\tresult.push({ role: \"user\", content });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (hadImages && !supportsImages) {\n\t\t\t\tresult.push({ role: \"user\", content: \"(image omitted: model does not support images)\" });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst contentParts: MistralContentChunk[] = [];\n\t\t\tconst toolCalls: MistralRequestToolCall[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (block.text.trim().length > 0) {\n\t\t\t\t\t\tcontentParts.push({ type: \"text\", text: sanitizeSurrogates(block.text) });\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (block.thinking.trim().length > 0) {\n\t\t\t\t\t\tcontentParts.push({\n\t\t\t\t\t\t\ttype: \"thinking\",\n\t\t\t\t\t\t\tthinking: [{ type: \"text\", text: sanitizeSurrogates(block.thinking) }],\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttoolCalls.push({\n\t\t\t\t\tid: block.id,\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tfunction: { name: block.name, arguments: JSON.stringify(block.arguments || {}) },\n\t\t\t\t\tindex: 0,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst assistantMessage: MistralChatMessage = { role: \"assistant\", prefix: false };\n\t\t\tif (contentParts.length > 0) assistantMessage.content = contentParts;\n\t\t\tif (toolCalls.length > 0) assistantMessage.toolCalls = toolCalls;\n\t\t\tif (contentParts.length > 0 || toolCalls.length > 0) result.push(assistantMessage);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst toolContent: MistralContentChunk[] = [];\n\t\tconst textResult = msg.content\n\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t.map((part) => (part.type === \"text\" ? sanitizeSurrogates(part.text) : \"\"))\n\t\t\t.join(\"\\n\");\n\t\tconst hasImages = msg.content.some((part) => part.type === \"image\");\n\t\tconst toolText = buildToolResultText(textResult, hasImages, supportsImages, msg.isError);\n\t\ttoolContent.push({ type: \"text\", text: toolText });\n\t\tfor (const part of msg.content) {\n\t\t\tif (!supportsImages) continue;\n\t\t\tif (part.type !== \"image\") continue;\n\t\t\ttoolContent.push({\n\t\t\t\ttype: \"image_url\",\n\t\t\t\timageUrl: `data:${part.mimeType};base64,${part.data}`,\n\t\t\t});\n\t\t}\n\t\tresult.push({\n\t\t\trole: \"tool\",\n\t\t\ttoolCallId: msg.toolCallId,\n\t\t\tname: msg.toolName,\n\t\t\tcontent: toolContent,\n\t\t});\n\t}\n\n\treturn result;\n}\n\nfunction buildToolResultText(text: string, hasImages: boolean, supportsImages: boolean, isError: boolean): string {\n\tconst trimmed = text.trim();\n\tconst errorPrefix = isError ? \"[tool error] \" : \"\";\n\n\tif (trimmed.length > 0) {\n\t\tconst imageSuffix = hasImages && !supportsImages ? \"\\n[tool image omitted: model does not support images]\" : \"\";\n\t\treturn `${errorPrefix}${trimmed}${imageSuffix}`;\n\t}\n\n\tif (hasImages) {\n\t\tif (supportsImages) {\n\t\t\treturn isError ? \"[tool error] (see attached image)\" : \"(see attached image)\";\n\t\t}\n\t\treturn isError\n\t\t\t? \"[tool error] (image omitted: model does not support images)\"\n\t\t\t: \"(image omitted: model does not support images)\";\n\t}\n\n\treturn isError ? \"[tool error] (no tool output)\" : \"(no tool output)\";\n}\n\nfunction usesReasoningEffort(model: Model<\"mistral-conversations\">): boolean {\n\treturn model.id === \"mistral-small-2603\" || model.id === \"mistral-small-latest\" || model.id === \"mistral-medium-3.5\";\n}\n\nfunction usesPromptModeReasoning(model: Model<\"mistral-conversations\">): boolean {\n\treturn model.reasoning && !usesReasoningEffort(model);\n}\n\nfunction mapReasoningEffort(\n\tmodel: Model<\"mistral-conversations\">,\n\tlevel: Exclude<SimpleStreamOptions[\"reasoning\"], undefined>,\n): MistralReasoningEffort {\n\treturn (model.thinkingLevelMap?.[level] ?? \"high\") as MistralReasoningEffort;\n}\n\nfunction mapToolChoice(\n\tchoice: MistralOptions[\"toolChoice\"],\n): \"auto\" | \"none\" | \"any\" | \"required\" | { type: \"function\"; function: { name: string } } | undefined {\n\tif (!choice) return undefined;\n\tif (choice === \"auto\" || choice === \"none\" || choice === \"any\" || choice === \"required\") {\n\t\treturn choice;\n\t}\n\treturn {\n\t\ttype: \"function\",\n\t\tfunction: { name: choice.function.name },\n\t};\n}\n\nfunction mapChatStopReason(reason: string | null): { stopReason: StopReason; errorMessage?: string } {\n\tif (reason === null) return { stopReason: \"stop\" };\n\tswitch (reason) {\n\t\tcase \"stop\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"length\":\n\t\tcase \"model_length\":\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase \"tool_calls\":\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tcase \"error\":\n\t\t\treturn { stopReason: \"error\", errorMessage: \"Provider stopped with: error\" };\n\t\tdefault:\n\t\t\treturn { stopReason: \"error\", errorMessage: `Provider stopped with: ${reason}` };\n\t}\n}\n"]}
@@ -518,7 +518,7 @@ async function consumeChatStream(model, output, stream, mistralStream) {
518
518
  const callId = toolCall.id && toolCall.id !== "null"
519
519
  ? toolCall.id
520
520
  : deriveMistralToolCallId(`toolcall:${toolCall.index ?? 0}`, 0);
521
- const key = `${callId}:${toolCall.index || 0}`;
521
+ const key = toolCall.index ?? callId;
522
522
  const existingIndex = toolBlocksByKey.get(key);
523
523
  let block;
524
524
  if (existingIndex !== undefined) {