@ai-agent-forge/agent-forge 0.86.3 → 0.86.5

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 (238) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/bundle/.build-manifest.json +500 -434
  3. package/dist/bundle/chunks/anthropic-messages-ALDZBUKI.js +6 -0
  4. package/dist/bundle/chunks/anthropic.js +2 -2
  5. package/dist/bundle/chunks/{azure-openai-responses-WQCZWFAH.js → azure-openai-responses-A2WJWZFB.js} +1 -1
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  7. package/dist/bundle/chunks/chunk-A7GUOX2H.js +141 -0
  8. package/dist/bundle/chunks/{chunk-WGLBM2BP.js → chunk-CIX3FSBK.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-RK2X2KU2.js → chunk-EALJ5DDX.js} +111 -101
  10. package/dist/bundle/chunks/chunk-OO6DJ3CL.js +31 -0
  11. package/dist/bundle/chunks/{chunk-N6BQJSGH.js → chunk-SQFG22WN.js} +3 -3
  12. package/dist/bundle/chunks/{chunk-V46XUTK3.js → chunk-Y7HXTASS.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-3WE3W52L.js → chunk-YJCQVXW5.js} +1 -1
  14. package/dist/bundle/chunks/github-copilot.js +1 -1
  15. package/dist/bundle/chunks/google-generative-ai-NIB4WONV.js +2 -0
  16. package/dist/bundle/chunks/google-vertex-DCPYUEUO.js +2 -0
  17. package/dist/bundle/chunks/mistral-conversations-OC6LA5XL.js +5 -0
  18. package/dist/bundle/chunks/{openai-codex-responses-YDJSZOIH.js → openai-codex-responses-IO2X4Y7L.js} +1 -1
  19. package/dist/bundle/chunks/openai-codex.js +2 -2
  20. package/dist/bundle/chunks/{openai-completions-UPRWTQPT.js → openai-completions-XYQQHETU.js} +1 -1
  21. package/dist/bundle/chunks/{openai-responses-O63W6HQ3.js → openai-responses-DLIRN3CI.js} +1 -1
  22. package/dist/bundle/chunks/{openrouter-images-G3GT5BVT.js → openrouter-images-G4GQRUSG.js} +1 -1
  23. package/dist/bundle/chunks/openrouter.js +2 -2
  24. package/dist/bundle/chunks/{pi-messages-SLF355GF.js → pi-messages-E6RRYBO7.js} +1 -1
  25. package/dist/bundle/chunks/radius.js +2 -2
  26. package/dist/bundle/chunks/{virtual-modules-O72ICTMQ.js → virtual-modules-3IZ4MYSQ.js} +1 -1
  27. package/dist/bundle/cli.js +1 -1
  28. package/dist/bundle/index.js +1 -1
  29. package/dist/bundle/rpc-entry.js +1 -1
  30. package/dist/capabilities/builtin.d.ts +4 -2
  31. package/dist/capabilities/builtin.d.ts.map +1 -1
  32. package/dist/capabilities/builtin.js +5 -1
  33. package/dist/capabilities/builtin.js.map +1 -1
  34. package/dist/cli/plugin-command.d.ts.map +1 -1
  35. package/dist/cli/plugin-command.js +51 -5
  36. package/dist/cli/plugin-command.js.map +1 -1
  37. package/dist/core/agent-session-compaction.d.ts +2 -2
  38. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  39. package/dist/core/agent-session-compaction.js +54 -6
  40. package/dist/core/agent-session-compaction.js.map +1 -1
  41. package/dist/core/agent-session-internal.d.ts +2 -4
  42. package/dist/core/agent-session-internal.d.ts.map +1 -1
  43. package/dist/core/agent-session-internal.js.map +1 -1
  44. package/dist/core/agent-session-paths.d.ts +2 -0
  45. package/dist/core/agent-session-paths.d.ts.map +1 -1
  46. package/dist/core/agent-session-paths.js +2 -1
  47. package/dist/core/agent-session-paths.js.map +1 -1
  48. package/dist/core/agent-session-projection.d.ts +10 -4
  49. package/dist/core/agent-session-projection.d.ts.map +1 -1
  50. package/dist/core/agent-session-projection.js +17 -4
  51. package/dist/core/agent-session-projection.js.map +1 -1
  52. package/dist/core/agent-session.d.ts +19 -5
  53. package/dist/core/agent-session.d.ts.map +1 -1
  54. package/dist/core/agent-session.js +30 -4
  55. package/dist/core/agent-session.js.map +1 -1
  56. package/dist/core/extensions/bootstrap-compaction-policy.d.ts.map +1 -1
  57. package/dist/core/extensions/bootstrap-compaction-policy.js +1 -2
  58. package/dist/core/extensions/bootstrap-compaction-policy.js.map +1 -1
  59. package/dist/core/extensions/bootstrap-lifecycle.d.ts +1 -1
  60. package/dist/core/extensions/bootstrap-lifecycle.d.ts.map +1 -1
  61. package/dist/core/extensions/bootstrap-lifecycle.js +5 -2
  62. package/dist/core/extensions/bootstrap-lifecycle.js.map +1 -1
  63. package/dist/core/extensions/capability-runtime-store.d.ts.map +1 -1
  64. package/dist/core/extensions/capability-runtime-store.js +1 -0
  65. package/dist/core/extensions/capability-runtime-store.js.map +1 -1
  66. package/dist/core/extensions/capability-runtime-types.d.ts +16 -1
  67. package/dist/core/extensions/capability-runtime-types.d.ts.map +1 -1
  68. package/dist/core/extensions/capability-runtime-types.js.map +1 -1
  69. package/dist/core/extensions/capability-runtime.d.ts.map +1 -1
  70. package/dist/core/extensions/capability-runtime.js +38 -2
  71. package/dist/core/extensions/capability-runtime.js.map +1 -1
  72. package/dist/core/extensions/index.d.ts +1 -1
  73. package/dist/core/extensions/index.d.ts.map +1 -1
  74. package/dist/core/extensions/index.js.map +1 -1
  75. package/dist/core/extensions/lifecycle-catalog.d.ts +46 -0
  76. package/dist/core/extensions/lifecycle-catalog.d.ts.map +1 -1
  77. package/dist/core/extensions/lifecycle-catalog.js +101 -0
  78. package/dist/core/extensions/lifecycle-catalog.js.map +1 -1
  79. package/dist/core/extensions/microcompact.d.ts +16 -8
  80. package/dist/core/extensions/microcompact.d.ts.map +1 -1
  81. package/dist/core/extensions/microcompact.js +9 -7
  82. package/dist/core/extensions/microcompact.js.map +1 -1
  83. package/dist/core/extensions/provider-failover.d.ts +106 -0
  84. package/dist/core/extensions/provider-failover.d.ts.map +1 -0
  85. package/dist/core/extensions/provider-failover.js +692 -0
  86. package/dist/core/extensions/provider-failover.js.map +1 -0
  87. package/dist/core/facade/coding-agent-facade.d.ts +13 -6
  88. package/dist/core/facade/coding-agent-facade.d.ts.map +1 -1
  89. package/dist/core/facade/coding-agent-facade.js +3 -1
  90. package/dist/core/facade/coding-agent-facade.js.map +1 -1
  91. package/dist/core/keybindings.d.ts +6 -6
  92. package/dist/core/keybindings.d.ts.map +1 -1
  93. package/dist/core/keybindings.js +23 -6
  94. package/dist/core/keybindings.js.map +1 -1
  95. package/dist/core/model-config.d.ts +102 -0
  96. package/dist/core/model-config.d.ts.map +1 -1
  97. package/dist/core/model-config.js +46 -14
  98. package/dist/core/model-config.js.map +1 -1
  99. package/dist/core/model-resolver.d.ts.map +1 -1
  100. package/dist/core/model-resolver.js +1 -1
  101. package/dist/core/model-resolver.js.map +1 -1
  102. package/dist/core/model-runtime.d.ts +15 -0
  103. package/dist/core/model-runtime.d.ts.map +1 -1
  104. package/dist/core/model-runtime.js +30 -18
  105. package/dist/core/model-runtime.js.map +1 -1
  106. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  107. package/dist/core/remote-catalog-provider.js +4 -9
  108. package/dist/core/remote-catalog-provider.js.map +1 -1
  109. package/dist/core/sdk.d.ts.map +1 -1
  110. package/dist/core/sdk.js +107 -24
  111. package/dist/core/sdk.js.map +1 -1
  112. package/dist/core/session-manager.d.ts +2 -0
  113. package/dist/core/session-manager.d.ts.map +1 -1
  114. package/dist/core/session-manager.js +10 -5
  115. package/dist/core/session-manager.js.map +1 -1
  116. package/dist/core/settings-manager.d.ts +74 -5
  117. package/dist/core/settings-manager.d.ts.map +1 -1
  118. package/dist/core/settings-manager.js +143 -10
  119. package/dist/core/settings-manager.js.map +1 -1
  120. package/dist/core/slash-commands.d.ts.map +1 -1
  121. package/dist/core/slash-commands.js +17 -2
  122. package/dist/core/slash-commands.js.map +1 -1
  123. package/dist/core/tools/bash.d.ts.map +1 -1
  124. package/dist/core/tools/bash.js +9 -10
  125. package/dist/core/tools/bash.js.map +1 -1
  126. package/dist/core/tools/render-utils.d.ts +6 -0
  127. package/dist/core/tools/render-utils.d.ts.map +1 -1
  128. package/dist/core/tools/render-utils.js +26 -0
  129. package/dist/core/tools/render-utils.js.map +1 -1
  130. package/dist/core/tools/tool-definition.d.ts +21 -2
  131. package/dist/core/tools/tool-definition.d.ts.map +1 -1
  132. package/dist/core/tools/tool-definition.js.map +1 -1
  133. package/dist/main.d.ts.map +1 -1
  134. package/dist/main.js +3 -6
  135. package/dist/main.js.map +1 -1
  136. package/dist/modes/interactive/components/agents-view.d.ts +57 -0
  137. package/dist/modes/interactive/components/agents-view.d.ts.map +1 -0
  138. package/dist/modes/interactive/components/agents-view.js +260 -0
  139. package/dist/modes/interactive/components/agents-view.js.map +1 -0
  140. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  141. package/dist/modes/interactive/components/custom-editor.js +2 -2
  142. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  143. package/dist/modes/interactive/components/footer.d.ts +15 -0
  144. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  145. package/dist/modes/interactive/components/footer.js +90 -9
  146. package/dist/modes/interactive/components/footer.js.map +1 -1
  147. package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -1
  148. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  149. package/dist/modes/interactive/components/scoped-models-selector.js +1 -1
  150. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  151. package/dist/modes/interactive/components/settings-selector.d.ts +3 -1
  152. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  153. package/dist/modes/interactive/components/settings-selector.js +12 -2
  154. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  155. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  156. package/dist/modes/interactive/components/thinking-selector.js +1 -1
  157. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  158. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  159. package/dist/modes/interactive/components/tool-execution.js +89 -10
  160. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  161. package/dist/modes/interactive/components/user-message-selector.d.ts +3 -0
  162. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  163. package/dist/modes/interactive/components/user-message-selector.js +9 -3
  164. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  165. package/dist/modes/interactive/components/workflow-view.d.ts +119 -0
  166. package/dist/modes/interactive/components/workflow-view.d.ts.map +1 -0
  167. package/dist/modes/interactive/components/workflow-view.js +638 -0
  168. package/dist/modes/interactive/components/workflow-view.js.map +1 -0
  169. package/dist/modes/interactive/interactive-commands.d.ts +22 -0
  170. package/dist/modes/interactive/interactive-commands.d.ts.map +1 -1
  171. package/dist/modes/interactive/interactive-commands.js +56 -0
  172. package/dist/modes/interactive/interactive-commands.js.map +1 -1
  173. package/dist/modes/interactive/interactive-mode.d.ts +51 -1
  174. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  175. package/dist/modes/interactive/interactive-mode.js +218 -37
  176. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  177. package/dist/modes/interactive/interactive-selectors.d.ts +2 -4
  178. package/dist/modes/interactive/interactive-selectors.d.ts.map +1 -1
  179. package/dist/modes/interactive/interactive-selectors.js +10 -1
  180. package/dist/modes/interactive/interactive-selectors.js.map +1 -1
  181. package/dist/modes/print-mode.d.ts.map +1 -1
  182. package/dist/modes/print-mode.js +5 -0
  183. package/dist/modes/print-mode.js.map +1 -1
  184. package/dist/modes/rpc/rpc-client.d.ts +3 -1
  185. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  186. package/dist/modes/rpc/rpc-client.js +4 -2
  187. package/dist/modes/rpc/rpc-client.js.map +1 -1
  188. package/dist/modes/rpc/rpc-types.d.ts +1 -0
  189. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  190. package/dist/modes/rpc/rpc-types.js.map +1 -1
  191. package/dist/plugins/ecosystem/bootstrap-factory-manifest.d.ts.map +1 -1
  192. package/dist/plugins/ecosystem/bootstrap-factory-manifest.js +7 -0
  193. package/dist/plugins/ecosystem/bootstrap-factory-manifest.js.map +1 -1
  194. package/dist/plugins/ecosystem/cli.d.ts.map +1 -1
  195. package/dist/plugins/ecosystem/cli.js +1 -1
  196. package/dist/plugins/ecosystem/cli.js.map +1 -1
  197. package/dist/plugins/ecosystem/install-store-paths.d.ts +15 -0
  198. package/dist/plugins/ecosystem/install-store-paths.d.ts.map +1 -0
  199. package/dist/plugins/ecosystem/install-store-paths.js +58 -0
  200. package/dist/plugins/ecosystem/install-store-paths.js.map +1 -0
  201. package/dist/plugins/ecosystem/node-disk-registry-source.d.ts.map +1 -1
  202. package/dist/plugins/ecosystem/node-disk-registry-source.js +3 -8
  203. package/dist/plugins/ecosystem/node-disk-registry-source.js.map +1 -1
  204. package/dist/plugins/ecosystem/node-package-install-host.d.ts.map +1 -1
  205. package/dist/plugins/ecosystem/node-package-install-host.js +9 -1
  206. package/dist/plugins/ecosystem/node-package-install-host.js.map +1 -1
  207. package/dist/plugins/ecosystem/node-package-install-persistence.d.ts.map +1 -1
  208. package/dist/plugins/ecosystem/node-package-install-persistence.js +3 -8
  209. package/dist/plugins/ecosystem/node-package-install-persistence.js.map +1 -1
  210. package/dist/profile/plugin-profiles.d.ts +2 -0
  211. package/dist/profile/plugin-profiles.d.ts.map +1 -1
  212. package/dist/profile/plugin-profiles.js +4 -0
  213. package/dist/profile/plugin-profiles.js.map +1 -1
  214. package/dist/profiles/builtin-suites.d.ts +19 -2
  215. package/dist/profiles/builtin-suites.d.ts.map +1 -1
  216. package/dist/profiles/builtin-suites.js +20 -2
  217. package/dist/profiles/builtin-suites.js.map +1 -1
  218. package/dist/profiles/suite-loader.d.ts.map +1 -1
  219. package/dist/profiles/suite-loader.js +4 -1
  220. package/dist/profiles/suite-loader.js.map +1 -1
  221. package/dist/utils/clipboard.d.ts.map +1 -1
  222. package/dist/utils/clipboard.js +10 -10
  223. package/dist/utils/clipboard.js.map +1 -1
  224. package/dist/utils/shell.d.ts +1 -3
  225. package/dist/utils/shell.d.ts.map +1 -1
  226. package/dist/utils/shell.js +3 -30
  227. package/dist/utils/shell.js.map +1 -1
  228. package/docs/keybindings.md +8 -8
  229. package/docs/models.md +1 -1
  230. package/docs/rpc.md +3 -1
  231. package/docs/settings.md +2 -1
  232. package/package.json +4 -4
  233. package/dist/bundle/chunks/anthropic-messages-EVFQ6MLR.js +0 -6
  234. package/dist/bundle/chunks/chunk-F6SBZUJG.js +0 -141
  235. package/dist/bundle/chunks/chunk-NUHFSC37.js +0 -25
  236. package/dist/bundle/chunks/google-generative-ai-ISTTUZMW.js +0 -2
  237. package/dist/bundle/chunks/google-vertex-NS7ZF7DK.js +0 -2
  238. package/dist/bundle/chunks/mistral-conversations-GINO6Z4I.js +0 -5
@@ -1,5 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{shortHash}from"./chunk-PJACZCIR.js";import{buildBaseOptions,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-TBPTHASB.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-6R7UI4IY.js";import{parseStreamingJson}from"./chunk-7ZY7IXZD.js";import{calculateCost,clampThinkingLevel}from"./chunk-V46XUTK3.js";import{AssistantMessageEventStream}from"./chunk-WGLBM2BP.js";import"./chunk-4L3WN2XY.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output=createOutput(model);try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let normalizeMistralToolCallId=createMistralToolCallIdNormalizer(),transformedMessages=transformMessages(context.messages,model,id=>normalizeMistralToolCallId(id)),payload=buildChatPayload(model,context,transformedMessages,options),nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let mistralStream=await requestMistralStream(model,payload,apiKey,options);if(stream2.push({type:"start",partial:output}),await consumeChatStream(model,output,stream2,mistralStream),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialArgs;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatMistralError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoning=clampedReasoning==="off"?void 0:clampedReasoning,shouldUseReasoning=model.reasoning&&reasoning!==void 0;return stream(model,context,{...base,promptMode:shouldUseReasoning&&usesPromptModeReasoning(model)?"reasoning":void 0,reasoningEffort:shouldUseReasoning&&usesReasoningEffort(model)?mapReasoningEffort(model,reasoning):void 0})};function createOutput(model){return{role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function createMistralToolCallIdNormalizer(){let idMap=new Map,reverseMap=new Map;return id=>{let existing=idMap.get(id);if(existing)return existing;let attempt=0;for(;;){let candidate=deriveMistralToolCallId(id,attempt),owner=reverseMap.get(candidate);if(!owner||owner===id)return idMap.set(id,candidate),reverseMap.set(candidate,id),candidate;attempt++}}}function deriveMistralToolCallId(id,attempt){let normalized=id.replace(/[^a-zA-Z0-9]/g,"");if(attempt===0&&normalized.length===MISTRAL_TOOL_CALL_ID_LENGTH)return normalized;let seedBase=normalized||id,seed=attempt===0?seedBase:`${seedBase}:${attempt}`;return shortHash(seed).replace(/[^a-zA-Z0-9]/g,"").slice(0,MISTRAL_TOOL_CALL_ID_LENGTH)}function formatMistralError(error){if(error instanceof Error){let httpError=error,statusCode=typeof httpError.statusCode=="number"?httpError.statusCode:void 0,bodyText=typeof httpError.body=="string"?httpError.body.trim():void 0;return statusCode!==void 0&&bodyText?`Mistral API error (${statusCode}): ${truncateErrorText(bodyText,MAX_MISTRAL_ERROR_BODY_CHARS)}`:statusCode!==void 0?`Mistral API error (${statusCode}): ${error.message}`:error.message}return safeJsonStringify(error)}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}async function requestMistralStream(model,payload,apiKey,options){let baseUrl=new URL(model.baseUrl);baseUrl.pathname=`${baseUrl.pathname.replace(/\/+$/u,"")}/`;let url=new URL("v1/chat/completions",baseUrl),headers=buildMistralHeaders(model,apiKey,options),timeoutSignal=AbortSignal.timeout(options?.timeoutMs??6e4),signal=options?.signal?AbortSignal.any([options.signal,timeoutSignal]):timeoutSignal,response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers,body:JSON.stringify(toMistralWirePayload(payload)),signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body=await response.text();throw new MistralHttpError(response.status,body,response.statusText)}if(!response.body)throw new Error("Mistral response has no body");return readMistralEvents(response.body,signal)}var MistralHttpError=class extends Error{statusCode;body;constructor(statusCode,body,statusText){super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,"toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let 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);return match?.index===void 0?void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
3
- `).trim();if(!data)return;if(data==="[DONE]")return MISTRAL_STREAM_DONE;let parsed=JSON.parse(data);if(!isMistralRecord(parsed)||!Array.isArray(parsed.choices))throw new Error("Invalid Mistral streaming event");return{data:parsed}}function buildChatPayload(model,context,messages,options){let payload={model:model.id,stream:!0,messages:toChatMessages(messages,model.input.includes("image"))};return context.tools?.length&&(payload.tools=toFunctionTools(context.tools)),options?.temperature!==void 0&&(payload.temperature=options.temperature),options?.maxTokens!==void 0&&(payload.maxTokens=options.maxTokens),options?.toolChoice&&(payload.toolChoice=mapToolChoice(options.toolChoice)),options?.promptMode&&(payload.promptMode=options.promptMode),options?.reasoningEffort&&(payload.reasoningEffort=options.reasoningEffort),shouldUsePromptCaching(options)&&(payload.promptCacheKey=options.sessionId),context.systemPrompt&&payload.messages.unshift({role:"system",content:sanitizeSurrogates(context.systemPrompt)}),payload}function shouldUsePromptCaching(options){return options?.cacheRetention!=="none"&&!!options?.sessionId}function getMistralCachedPromptTokens(usage,promptTokens){let rawUsage=usage,rawCachedTokens=rawUsage.promptTokensDetails?.cachedTokens??rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.promptTokenDetails?.cachedTokens??rawUsage.prompt_token_details?.cached_tokens??rawUsage.numCachedTokens??rawUsage.num_cached_tokens??0,cachedTokens=typeof rawCachedTokens=="number"&&Number.isFinite(rawCachedTokens)?rawCachedTokens:0;return Math.min(promptTokens,Math.max(0,cachedTokens))}async function consumeChatStream(model,output,stream2,mistralStream){let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1,toolBlocksByKey=new Map,finishCurrentBlock=block=>{if(block){if(block.type==="text"){stream2.push({type:"text_end",contentIndex:blockIndex(),content:block.text,partial:output});return}block.type==="thinking"&&stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:block.thinking,partial:output})}};for await(let event of mistralStream){let chunk=event.data;if(output.responseId||=chunk.id,chunk.usage){let promptTokens=chunk.usage.prompt_tokens||0,cachedPromptTokens=getMistralCachedPromptTokens(chunk.usage,promptTokens);output.usage.input=Math.max(0,promptTokens-cachedPromptTokens),output.usage.output=chunk.usage.completion_tokens||0,output.usage.cacheRead=cachedPromptTokens,output.usage.cacheWrite=0,output.usage.totalTokens=chunk.usage.total_tokens||output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(model,output.usage)}let choice=chunk.choices[0];if(!choice)continue;if(choice.finish_reason){output.rawStopReason=choice.finish_reason;let stopReasonResult=mapChatStopReason(choice.finish_reason);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}let delta=choice.delta;if(delta.content!==null&&delta.content!==void 0){let contentItems=typeof delta.content=="string"?[delta.content]:delta.content;for(let item of contentItems){if(typeof item=="string"){let textDelta=sanitizeSurrogates(item);(!currentBlock||currentBlock.type!=="text")&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output});continue}if(item.type==="thinking"){let deltaText=(item.thinking??[]).map(part=>part.text??"").filter(text=>text.length>0).join(""),thinkingDelta=sanitizeSurrogates(deltaText);if(!thinkingDelta)continue;(!currentBlock||currentBlock.type!=="thinking")&&(finishCurrentBlock(currentBlock),currentBlock={type:"thinking",thinking:""},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})),currentBlock.thinking+=thinkingDelta,stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:thinkingDelta,partial:output});continue}if(item.type==="text"){let textDelta=sanitizeSurrogates(item.text??"");(!currentBlock||currentBlock.type!=="text")&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output})}}}let toolCalls=delta.tool_calls||[];for(let toolCall of toolCalls){currentBlock&&(finishCurrentBlock(currentBlock),currentBlock=null);let callId=toolCall.id&&toolCall.id!=="null"?toolCall.id:deriveMistralToolCallId(`toolcall:${toolCall.index??0}`,0),key=toolCall.index??callId,existingIndex=toolBlocksByKey.get(key),block;if(existingIndex!==void 0){let existing=output.content[existingIndex];existing?.type==="toolCall"&&(block=existing)}block||(block={type:"toolCall",id:callId,name:toolCall.function.name,arguments:{},partialArgs:""},output.content.push(block),toolBlocksByKey.set(key,output.content.length-1),stream2.push({type:"toolcall_start",contentIndex:output.content.length-1,partial:output}));let argsDelta=typeof toolCall.function.arguments=="string"?toolCall.function.arguments:JSON.stringify(toolCall.function.arguments||{});block.partialArgs=(block.partialArgs||"")+argsDelta,block.arguments=parseStreamingJson(block.partialArgs),stream2.push({type:"toolcall_delta",contentIndex:toolBlocksByKey.get(key),delta:argsDelta,partial:output})}}finishCurrentBlock(currentBlock);for(let index of toolBlocksByKey.values()){let block=output.content[index];if(block.type!=="toolCall")continue;let toolBlock=block;toolBlock.arguments=parseStreamingJson(toolBlock.partialArgs),delete toolBlock.partialArgs,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:toolBlock,partial:output})}}function toFunctionTools(tools){return tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,!0);return{type:"function",function:{name:tool.name,description:tool.description,parameters:stripSymbolKeys(getJsonSchemaToolParameters(tool,strict)),strict:strict??!1}}})}function stripSymbolKeys(value){if(Array.isArray(value))return value.map(item=>stripSymbolKeys(item));if(value&&typeof value=="object"){let result={};for(let[key,entry]of Object.entries(value))result[key]=stripSymbolKeys(entry);return result}return value}function toChatMessages(messages,supportsImages){let result=[];for(let msg of messages){if(msg.role==="user"){if(typeof msg.content=="string"){result.push({role:"user",content:sanitizeSurrogates(msg.content)});continue}let hadImages=msg.content.some(item=>item.type==="image"),content=msg.content.filter(item=>item.type==="text"||supportsImages).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",imageUrl:`data:${item.mimeType};base64,${item.data}`});if(content.length>0){result.push({role:"user",content});continue}hadImages&&!supportsImages&&result.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(msg.role==="assistant"){let contentParts=[],toolCalls=[];for(let block of msg.content){if(block.type==="text"){block.text.trim().length>0&&contentParts.push({type:"text",text:sanitizeSurrogates(block.text)});continue}if(block.type==="thinking"){block.thinking.trim().length>0&&contentParts.push({type:"thinking",thinking:[{type:"text",text:sanitizeSurrogates(block.thinking)}]});continue}toolCalls.push({id:block.id,type:"function",function:{name:block.name,arguments:JSON.stringify(block.arguments||{})},index:0})}let assistantMessage={role:"assistant",prefix:!1};contentParts.length>0&&(assistantMessage.content=contentParts),toolCalls.length>0&&(assistantMessage.toolCalls=toolCalls),(contentParts.length>0||toolCalls.length>0)&&result.push(assistantMessage);continue}let toolContent=[],textResult=msg.content.filter(part=>part.type==="text").map(part=>part.type==="text"?sanitizeSurrogates(part.text):"").join(`
4
- `),hasImages=msg.content.some(part=>part.type==="image"),toolText=buildToolResultText(textResult,hasImages,supportsImages,msg.isError);toolContent.push({type:"text",text:toolText});for(let part of msg.content)supportsImages&&part.type==="image"&&toolContent.push({type:"image_url",imageUrl:`data:${part.mimeType};base64,${part.data}`});result.push({role:"tool",toolCallId:msg.toolCallId,name:msg.toolName,content:toolContent})}return result}function buildToolResultText(text,hasImages,supportsImages,isError){let trimmed=text.trim(),errorPrefix=isError?"[tool error] ":"";return trimmed.length>0?`${errorPrefix}${trimmed}${hasImages&&!supportsImages?`
5
- [tool image omitted: model does not support images]`:""}`:hasImages?supportsImages?isError?"[tool error] (see attached image)":"(see attached image)":isError?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)":isError?"[tool error] (no tool output)":"(no tool output)"}function usesReasoningEffort(model){return model.id==="mistral-small-2603"||model.id==="mistral-small-latest"||model.id.startsWith("mistral-medium-")}function usesPromptModeReasoning(model){return model.reasoning&&!usesReasoningEffort(model)}function mapReasoningEffort(model,level){return model.thinkingLevelMap?.[level]??"high"}function mapToolChoice(choice){if(choice)return choice==="auto"||choice==="none"||choice==="any"||choice==="required"?choice:{type:"function",function:{name:choice.function.name}}}function mapChatStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}}}export{stream,streamSimple};