@draht/coding-agent 2026.11.19-1 → 2026.11.21-1

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 (186) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/bundle/chunks/{anthropic-messages-7PTOA4ZA.js → anthropic-messages-JAAJVU3F.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-CDW6FCMN.js → azure-openai-responses-N4SHTXJ6.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +5 -5
  5. package/dist/bundle/chunks/{chunk-MXA4WY3C.js → chunk-2DUHHN23.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-7HQNDYWE.js → chunk-4MO4FSW4.js} +2 -2
  7. package/dist/bundle/chunks/{chunk-MHNW355A.js → chunk-7VQD47PF.js} +1 -1
  8. package/dist/bundle/chunks/chunk-A6BJNLBN.js +16 -0
  9. package/dist/bundle/chunks/{chunk-WOIC265R.js → chunk-BHLOLWW6.js} +38 -35
  10. package/dist/bundle/chunks/{chunk-HKQ3PU5T.js → chunk-BSVP25DF.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-RI7HJ6AF.js → chunk-EGJQSI6O.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-4FPBO5KP.js → chunk-EHGC5YA6.js} +2 -2
  13. package/dist/bundle/chunks/{chunk-YOPX5URH.js → chunk-EJUBHUKG.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-JI5YDTBB.js → chunk-FHUNJPUZ.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-BQMYLQSG.js → chunk-ICD4T57T.js} +3 -3
  16. package/dist/bundle/chunks/{chunk-BIXKXDGW.js → chunk-IUK7PQZQ.js} +1 -1
  17. package/dist/bundle/chunks/chunk-J6WPFP55.js +30 -0
  18. package/dist/bundle/chunks/chunk-LHWSZITO.js +2 -0
  19. package/dist/bundle/chunks/{chunk-CAOOVEOM.js → chunk-TQH3TSOY.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-GAABJAG4.js → chunk-U7QL6N7M.js} +11 -11
  21. package/dist/bundle/chunks/chunk-X7F5FNNE.js +31 -0
  22. package/dist/bundle/chunks/{chunk-O2P5SYXT.js → chunk-XP47TR6S.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-B6OJ7QX4.js → chunk-ZWE4WYUP.js} +1 -1
  24. package/dist/bundle/chunks/{cli-QUYXUKRF.js → cli-FQY4GIEZ.js} +1 -1
  25. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-W63EWPDW.js → cloudflare-workers-ai-system-one-UZT2D6OE.js} +1 -1
  26. package/dist/bundle/chunks/{execute-KGJOWTPG.js → execute-7ZBBCFJX.js} +1 -1
  27. package/dist/bundle/chunks/github-copilot.js +1 -1
  28. package/dist/bundle/chunks/{google-generative-ai-M5WKK5CW.js → google-generative-ai-V4OXSUYB.js} +1 -1
  29. package/dist/bundle/chunks/{google-vertex-UYNOGPMI.js → google-vertex-FHE7WELO.js} +1 -1
  30. package/dist/bundle/chunks/{llama-cpp-classify-SAUGLDPT.js → llama-cpp-classify-OOBHWVRW.js} +1 -1
  31. package/dist/bundle/chunks/{mistral-conversations-VQ3J6W5K.js → mistral-conversations-P2UXS4YP.js} +2 -2
  32. package/dist/bundle/chunks/openai-codex-responses-6EVE5GBS.js +10 -0
  33. package/dist/bundle/chunks/{openai-completions-WAW7BG4E.js → openai-completions-J455OHQY.js} +2 -2
  34. package/dist/bundle/chunks/{openai-decisions-KHHHHMGW.js → openai-decisions-3YUUL56O.js} +1 -1
  35. package/dist/bundle/chunks/{openai-responses-GWADST54.js → openai-responses-T6LS2BDK.js} +1 -1
  36. package/dist/bundle/chunks/{openrouter-images-AP626CWG.js → openrouter-images-3QKLSH5X.js} +1 -1
  37. package/dist/bundle/chunks/{pi-messages-H5TYIEJT.js → pi-messages-SMJVFBS5.js} +1 -1
  38. package/dist/bundle/chunks/{runtime-73OLLYOI.js → runtime-ZTL2QJTC.js} +1 -1
  39. package/dist/bundle/chunks/{settings-manager-CWRQW6PZ.js → settings-manager-DB22TF7G.js} +1 -1
  40. package/dist/bundle/chunks/{typesafe-system-one-RLPGOT75.js → typesafe-system-one-OLZERWYH.js} +1 -1
  41. package/dist/bundle/chunks/{virtual-modules-5V4G5GQH.js → virtual-modules-GB7JDLCJ.js} +1 -1
  42. package/dist/bundle/cli-runtime.js +1 -1
  43. package/dist/bundle/index.js +1 -1
  44. package/dist/bundle/rpc-entry.js +1 -1
  45. package/dist/cli/config-selector.d.ts.map +1 -1
  46. package/dist/cli/config-selector.js +9 -6
  47. package/dist/cli/config-selector.js.map +1 -1
  48. package/dist/cli/session-picker.d.ts.map +1 -1
  49. package/dist/cli/session-picker.js +9 -6
  50. package/dist/cli/session-picker.js.map +1 -1
  51. package/dist/cli/startup-ui.d.ts.map +1 -1
  52. package/dist/cli/startup-ui.js +4 -0
  53. package/dist/cli/startup-ui.js.map +1 -1
  54. package/dist/core/agent-session-runtime.d.ts +11 -0
  55. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  56. package/dist/core/agent-session-runtime.js +19 -0
  57. package/dist/core/agent-session-runtime.js.map +1 -1
  58. package/dist/core/agent-session.d.ts +1 -0
  59. package/dist/core/agent-session.d.ts.map +1 -1
  60. package/dist/core/agent-session.js +4 -5
  61. package/dist/core/agent-session.js.map +1 -1
  62. package/dist/core/export-html/ansi-to-html.d.ts +1 -1
  63. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  64. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  65. package/dist/core/export-html/tool-renderer.js.map +1 -1
  66. package/dist/core/extensions/loader.d.ts.map +1 -1
  67. package/dist/core/extensions/loader.js +18 -1
  68. package/dist/core/extensions/loader.js.map +1 -1
  69. package/dist/core/extensions/runner.d.ts.map +1 -1
  70. package/dist/core/extensions/runner.js +5 -0
  71. package/dist/core/extensions/runner.js.map +1 -1
  72. package/dist/core/extensions/types.d.ts +5 -0
  73. package/dist/core/extensions/types.d.ts.map +1 -1
  74. package/dist/core/extensions/types.js.map +1 -1
  75. package/dist/core/model-resolver.d.ts +0 -7
  76. package/dist/core/model-resolver.d.ts.map +1 -1
  77. package/dist/core/model-resolver.js +3 -60
  78. package/dist/core/model-resolver.js.map +1 -1
  79. package/dist/core/package-manager.d.ts +16 -0
  80. package/dist/core/package-manager.d.ts.map +1 -1
  81. package/dist/core/package-manager.js +46 -3
  82. package/dist/core/package-manager.js.map +1 -1
  83. package/dist/core/resource-loader.d.ts +5 -1
  84. package/dist/core/resource-loader.d.ts.map +1 -1
  85. package/dist/core/resource-loader.js +2 -0
  86. package/dist/core/resource-loader.js.map +1 -1
  87. package/dist/core/session-manager.d.ts.map +1 -1
  88. package/dist/core/session-manager.js +3 -1
  89. package/dist/core/session-manager.js.map +1 -1
  90. package/dist/core/tools/bash.js +1 -1
  91. package/dist/core/tools/bash.js.map +1 -1
  92. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  93. package/dist/core/tools/output-accumulator.js +3 -2
  94. package/dist/core/tools/output-accumulator.js.map +1 -1
  95. package/dist/core/tools/truncate.d.ts +1 -1
  96. package/dist/core/tools/truncate.d.ts.map +1 -1
  97. package/dist/core/tools/truncate.js +11 -5
  98. package/dist/core/tools/truncate.js.map +1 -1
  99. package/dist/extensions/llama/provider.d.ts.map +1 -1
  100. package/dist/extensions/llama/provider.js +5 -3
  101. package/dist/extensions/llama/provider.js.map +1 -1
  102. package/dist/main.d.ts.map +1 -1
  103. package/dist/main.js +30 -12
  104. package/dist/main.js.map +1 -1
  105. package/dist/modes/diagnostics-stderr.d.ts +4 -0
  106. package/dist/modes/diagnostics-stderr.d.ts.map +1 -0
  107. package/dist/modes/diagnostics-stderr.js +11 -0
  108. package/dist/modes/diagnostics-stderr.js.map +1 -0
  109. package/dist/modes/interactive/components/assistant-message.d.ts +2 -1
  110. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  111. package/dist/modes/interactive/components/assistant-message.js +9 -3
  112. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  113. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  114. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  115. package/dist/modes/interactive/components/config-selector.js +5 -2
  116. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  117. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  118. package/dist/modes/interactive/components/model-selector.js +5 -2
  119. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  120. package/dist/modes/interactive/components/oauth-selector.d.ts +1 -1
  121. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  122. package/dist/modes/interactive/components/oauth-selector.js +7 -3
  123. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  124. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
  125. package/dist/modes/interactive/components/radius-login-selector.js +2 -1
  126. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
  127. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  128. package/dist/modes/interactive/components/scoped-models-selector.js +9 -1
  129. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  130. package/dist/modes/interactive/components/session-selector.d.ts +2 -0
  131. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  132. package/dist/modes/interactive/components/session-selector.js +18 -4
  133. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  134. package/dist/modes/interactive/components/settings-submenu.d.ts +1 -1
  135. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  136. package/dist/modes/interactive/components/settings-submenu.js +5 -1
  137. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  138. package/dist/modes/interactive/components/themed-text.d.ts +1 -1
  139. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
  140. package/dist/modes/interactive/components/themed-text.js.map +1 -1
  141. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  142. package/dist/modes/interactive/components/thinking-selector.js +5 -1
  143. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  144. package/dist/modes/interactive/components/tool-execution.d.ts +1 -1
  145. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  146. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  147. package/dist/modes/interactive/components/user-message.d.ts +2 -1
  148. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  149. package/dist/modes/interactive/components/user-message.js +9 -3
  150. package/dist/modes/interactive/components/user-message.js.map +1 -1
  151. package/dist/modes/interactive/components/visual-truncate.d.ts +2 -2
  152. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  153. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  154. package/dist/modes/interactive/interactive-mode.d.ts +1 -1
  155. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  156. package/dist/modes/interactive/interactive-mode.js +79 -38
  157. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  158. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  159. package/dist/modes/interactive/theme/theme.js +1 -0
  160. package/dist/modes/interactive/theme/theme.js.map +1 -1
  161. package/dist/modes/print-mode.d.ts.map +1 -1
  162. package/dist/modes/print-mode.js +16 -13
  163. package/dist/modes/print-mode.js.map +1 -1
  164. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  165. package/dist/modes/rpc/rpc-mode.js +15 -23
  166. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  167. package/dist/utils/changelog.d.ts.map +1 -1
  168. package/dist/utils/changelog.js +3 -2
  169. package/dist/utils/changelog.js.map +1 -1
  170. package/dist/utils/flush-stdout.d.ts +8 -0
  171. package/dist/utils/flush-stdout.d.ts.map +1 -0
  172. package/dist/utils/flush-stdout.js +23 -0
  173. package/dist/utils/flush-stdout.js.map +1 -0
  174. package/docs/models-configuration.md +11 -2
  175. package/docs/tui.md +2 -0
  176. package/package.json +9 -9
  177. package/schemas/models.schema.json +1 -1
  178. package/dist/bundle/chunks/chunk-2CHTECAU.js +0 -2
  179. package/dist/bundle/chunks/chunk-3F4OOENR.js +0 -16
  180. package/dist/bundle/chunks/chunk-6WESOD4H.js +0 -31
  181. package/dist/bundle/chunks/chunk-INKDO5TZ.js +0 -30
  182. package/dist/bundle/chunks/openai-codex-responses-JTGQLYC7.js +0 -10
  183. package/dist/utils/deprecation.d.ts +0 -4
  184. package/dist/utils/deprecation.d.ts.map +0 -1
  185. package/dist/utils/deprecation.js +0 -13
  186. package/dist/utils/deprecation.js.map +0 -1
@@ -8,6 +8,6 @@ Searched Git Bash in:
8
8
  ${paths.map(p=>` ${p}`).join(`
9
9
  `)}`)}if(shellPathExists("/bin/bash"))return getBashShellConfig("/bin/bash");let bashOnPath=findExecutableOnPath("bash");return bashOnPath?getBashShellConfig(bashOnPath):{shell:"sh",args:["-c"]}}var POWERSHELL_ARGS=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];function getPowerShellConfig(){if(process.platform!=="win32")throw new Error("The powershell tool is only available on Windows.");let shell=findExecutableOnPath("pwsh.exe"),programFiles=process.env.ProgramFiles;if(!shell&&programFiles){let pwsh7=win32.join(programFiles,"PowerShell","7","pwsh.exe");shellPathExists(pwsh7)&&(shell=pwsh7)}shell??=findExecutableOnPath("powershell.exe");let systemRoot=process.env.SystemRoot;if(!shell&&systemRoot){let windowsPowerShell=win32.join(systemRoot,"System32","WindowsPowerShell","v1.0","powershell.exe");shellPathExists(windowsPowerShell)&&(shell=windowsPowerShell)}if(!shell)throw new Error("No PowerShell executable found. Install PowerShell or add powershell.exe/pwsh.exe to PATH.");return{shell,args:[...POWERSHELL_ARGS]}}function getShellEnv(){let binDir=getBinDir(),pathKey=Object.keys(process.env).find(key=>key.toLowerCase()==="path")??"PATH",currentPath=process.env[pathKey]??"",updatedPath=currentPath.split(delimiter).filter(Boolean).includes(binDir)?currentPath:[binDir,currentPath].filter(Boolean).join(delimiter),env={...process.env,[pathKey]:updatedPath};return delete env.DRAHT_POLYPHASE_DEPTH,delete env.DRAHT_POLYPHASE_SCHEMA_FILE,delete env.DRAHT_POLYPHASE_PERMISSION_BRIDGE,env}function sanitizeBinaryOutput(str){return str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g,"")}var trackedDetachedChildPids=new Set;function trackDetachedChildPid(pid){trackedDetachedChildPids.add(pid)}function untrackDetachedChildPid(pid){trackedDetachedChildPids.delete(pid)}function killTrackedDetachedChildren(){for(let pid of trackedDetachedChildPids)killProcessTree(pid);trackedDetachedChildPids.clear()}function killProcessTree(pid){if(process.platform==="win32")try{spawn(join(process.env.SystemRoot||"C:\\Windows","System32","taskkill.exe"),["/F","/T","/PID",String(pid)],{stdio:"ignore",detached:!0,windowsHide:!0}).once("error",()=>{})}catch{}else{if(process.platform==="darwin")try{process.kill(-pid,"SIGSTOP")}catch{}try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}}var DEFAULT_MAX_LINES=2e3,DEFAULT_MAX_BYTES=51200;function splitLinesForCounting(content){if(content.length===0)return[];let lines=content.split(`
10
10
  `);return content.endsWith(`
11
- `)&&lines.pop(),lines}function formatSize(bytes){return bytes<1024?`${bytes}B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)}KB`:`${(bytes/(1024*1024)).toFixed(1)}MB`}function truncateHead(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};if(Buffer.byteLength(lines[0],"utf-8")>maxBytes)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines,totalBytes,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines";for(let i=0;i<lines.length&&i<maxLines;i++){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(i>0?1:0);if(outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes";break}outputLinesArr.push(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
12
- `),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateTail(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines",lastLinePartial=!1;for(let i=lines.length-1;i>=0&&outputLinesArr.length<maxLines;i--){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(outputLinesArr.length>0?1:0);if(outputBytesCount+lineBytes>maxBytes){if(truncatedBy="bytes",outputLinesArr.length===0){let truncatedLine=truncateStringToBytesFromEnd(line,maxBytes);outputLinesArr.unshift(truncatedLine),outputBytesCount=Buffer.byteLength(truncatedLine,"utf-8"),lastLinePartial=!0}break}outputLinesArr.unshift(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
11
+ `)&&lines.pop(),lines}function isBlankLine(line){return line.trim().length===0}function formatSize(bytes){return bytes<1024?`${bytes}B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)}KB`:`${(bytes/(1024*1024)).toFixed(1)}MB`}function truncateHead(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};if(Buffer.byteLength(lines[0],"utf-8")>maxBytes)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines,totalBytes,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines";for(let i=0;i<lines.length&&i<maxLines;i++){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(i>0?1:0);if(outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes";break}outputLinesArr.push(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
12
+ `),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateTail(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines",lastLinePartial=!1;for(let i=lines.length-1;i>=0&&outputLinesArr.length<maxLines;i--){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(outputLinesArr.length>0?1:0);if(outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes";let remainingBytes=maxBytes-outputBytesCount-(outputLinesArr.length>0?1:0);if(outputLinesArr.length===0||!isBlankLine(line)&&outputLinesArr.every(isBlankLine)&&remainingBytes>0){let truncatedLine=truncateStringToBytesFromEnd(line,remainingBytes);outputLinesArr.unshift(truncatedLine),outputBytesCount+=lineBytes-Buffer.byteLength(line,"utf-8")+Buffer.byteLength(truncatedLine,"utf-8"),lastLinePartial=!0}break}outputLinesArr.unshift(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
13
13
  `),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateStringToBytesFromEnd(str,maxBytes){let buf=Buffer.from(str,"utf-8");if(buf.length<=maxBytes)return str;let start=buf.length-maxBytes;for(;start<buf.length&&(buf[start]&192)===128;)start++;return buf.slice(start).toString("utf-8")}function truncateLine(line,maxChars=500){return line.length<=maxChars?{text:line,wasTruncated:!1}:{text:`${sliceHead(line,maxChars)}... [truncated]`,wasTruncated:!0}}function sliceHead(text,maxUnits){let end=Math.max(0,maxUnits);return isHighSurrogate(text.charCodeAt(end-1))&&isLowSurrogate(text.charCodeAt(end))?text.slice(0,end-1):text.slice(0,end)}function sliceTail(text,maxUnits){if(maxUnits<=0)return"";let start=Math.max(0,text.length-maxUnits);return isLowSurrogate(text.charCodeAt(start))&&isHighSurrogate(text.charCodeAt(start-1))?text.slice(start+1):text.slice(start)}function isHighSurrogate(code){return code>=55296&&code<=56319}function isLowSurrogate(code){return code>=56320&&code<=57343}export{getShellConfig,getPowerShellConfig,getShellEnv,sanitizeBinaryOutput,trackDetachedChildPid,untrackDetachedChildPid,killTrackedDetachedChildren,killProcessTree,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,sliceHead,sliceTail};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- import{clampThinkingLevel}from"./chunk-7HQNDYWE.js";import{getSystemMessageText}from"./chunk-BIXKXDGW.js";var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.type===void 0&&schema.anyOf===void 0&&schema.enum===void 0)throw new UnsupportedStrictJsonSchemaError("schemas without a type are unsupported");if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function prefersJsonSchemaStrictSampling(tool){let config=tool.constrainedSampling;return!!config&&config.type==="json_schema"&&config.strict==="prefer"}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function getGrammarToolInput(toolName,arguments_,inputProperty){let input=arguments_[inputProperty];if(typeof input!="string")throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`);return input}function appendGrammarToolInputJsonDelta(buffer,inputProperty,inputDelta){if(buffer.closed)throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);if(inputDelta.length!==0)return buffer.input+=inputDelta,grammarToolInputJsonStart(buffer,inputProperty)+JSON.stringify(inputDelta).slice(1,-1)}function closeGrammarToolInputJson(buffer,inputProperty,finalInput){if(buffer.closed){if(finalInput===void 0||finalInput===buffer.input)return;throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`)}if(finalInput!==void 0&&!finalInput.startsWith(buffer.input))throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);let rest=finalInput===void 0?"":finalInput.slice(buffer.input.length);return finalInput!==void 0&&(buffer.input=finalInput),buffer.closed=!0,`${grammarToolInputJsonStart(buffer,inputProperty)}${JSON.stringify(rest).slice(1,-1)}"}`}function grammarToolInputJsonStart(buffer,inputProperty){return buffer.started?"":(buffer.started=!0,`{${JSON.stringify(inputProperty)}:"`)}function inferGrammarInputProperty(tool){let schema=tool.parameters;if(schema.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(schema.required)||schema.required.length!==1||typeof schema.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let inputProperty=schema.required[0];if(!schema.properties?.[inputProperty])throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);if(schema.properties[inputProperty]?.type!=="string")throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);return inputProperty}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools){let config=tool.constrainedSampling;if(!config||config.type!=="grammar"||!supportsOpenAIGrammarTools)return;let larkDefinition=config.variants.openai_lark,regexDefinition=config.variants.openai_regex,hasLarkDefinition=typeof larkDefinition=="string"&&larkDefinition.trim().length>0,hasRegexDefinition=typeof regexDefinition=="string"&&regexDefinition.trim().length>0;if(!hasLarkDefinition&&!hasRegexDefinition)throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:hasLarkDefinition?"lark":"regex",definition:hasLarkDefinition?larkDefinition:regexDefinition,inputProperty:inferGrammarInputProperty(tool)}}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`)}}function createGrammarToolInputProperties(tools,supportsOpenAIGrammarTools){let properties=new Map;for(let tool of tools??[]){let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);grammar&&properties.set(tool.name,grammar.inputProperty)}return properties}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:chars+=block.name.length+safeJsonStringify(block.arguments).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i=0;i<messages.length;i++){let message=messages[i];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i=usageInfo.index+1;i<messages.length;i++)trailingTokens+=estimateMessageTokens(messages[i]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify(tools))}var CONTEXT_SAFETY_TOKENS=4096,CONTEXT_SAFETY_RATIO=.15,MIN_OUTPUT_WITH_RATIO_MARGIN=32768,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let input=estimateContextTokens(context).tokens,margin=Math.max(CONTEXT_SAFETY_TOKENS,Math.ceil(input*CONTEXT_SAFETY_RATIO)),room=model.contextWindow-input-margin;return room<MIN_OUTPUT_WITH_RATIO_MARGIN&&(room=Math.min(MIN_OUTPUT_WITH_RATIO_MARGIN,model.contextWindow-input-CONTEXT_SAFETY_TOKENS)),Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,room))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,disableContinuation:options?.disableContinuation,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)",ERROR_TOOL_IMAGE_PLACEHOLDER="(image attached after the tool results)";function splitErrorToolResultImages(msg){if(!msg.isError)return;let images=msg.content.filter(block=>block.type==="image");if(images.length!==0)return{content:replaceImagesWithPlaceholder(msg.content,ERROR_TOOL_IMAGE_PLACEHOLDER),caption:`Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,images}}function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i=0;i<transformed.length;i++){let msg=transformed[i];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b=>b.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}export{prefersJsonSchemaStrictSampling,getJsonSchemaToolParameters,getGrammarToolInput,appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,resolveJsonSchemaStrictSampling,resolveGrammarConstrainedSampling,createGrammarToolInputProperties,clampMaxTokensToContext,resolveSamplingParams,buildBaseOptions,thinkingBudgetForLevel,clampThinkingBudgetToAnswerRoom,adjustMaxTokensForThinking,splitErrorToolResultImages,transformMessages};
2
+ import{clampThinkingLevel}from"./chunk-4MO4FSW4.js";import{getSystemMessageText}from"./chunk-IUK7PQZQ.js";var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.type===void 0&&schema.anyOf===void 0&&schema.enum===void 0)throw new UnsupportedStrictJsonSchemaError("schemas without a type are unsupported");if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function prefersJsonSchemaStrictSampling(tool){let config=tool.constrainedSampling;return!!config&&config.type==="json_schema"&&config.strict==="prefer"}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function getGrammarToolInput(toolName,arguments_,inputProperty){let input=arguments_[inputProperty];if(typeof input!="string")throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`);return input}function appendGrammarToolInputJsonDelta(buffer,inputProperty,inputDelta){if(buffer.closed)throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);if(inputDelta.length!==0)return buffer.input+=inputDelta,grammarToolInputJsonStart(buffer,inputProperty)+JSON.stringify(inputDelta).slice(1,-1)}function closeGrammarToolInputJson(buffer,inputProperty,finalInput){if(buffer.closed){if(finalInput===void 0||finalInput===buffer.input)return;throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`)}if(finalInput!==void 0&&!finalInput.startsWith(buffer.input))throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);let rest=finalInput===void 0?"":finalInput.slice(buffer.input.length);return finalInput!==void 0&&(buffer.input=finalInput),buffer.closed=!0,`${grammarToolInputJsonStart(buffer,inputProperty)}${JSON.stringify(rest).slice(1,-1)}"}`}function grammarToolInputJsonStart(buffer,inputProperty){return buffer.started?"":(buffer.started=!0,`{${JSON.stringify(inputProperty)}:"`)}function inferGrammarInputProperty(tool){let schema=tool.parameters;if(schema.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(schema.required)||schema.required.length!==1||typeof schema.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let inputProperty=schema.required[0];if(!schema.properties?.[inputProperty])throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);if(schema.properties[inputProperty]?.type!=="string")throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);return inputProperty}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools){let config=tool.constrainedSampling;if(!config||config.type!=="grammar"||!supportsOpenAIGrammarTools)return;let larkDefinition=config.variants.openai_lark,regexDefinition=config.variants.openai_regex,hasLarkDefinition=typeof larkDefinition=="string"&&larkDefinition.trim().length>0,hasRegexDefinition=typeof regexDefinition=="string"&&regexDefinition.trim().length>0;if(!hasLarkDefinition&&!hasRegexDefinition)throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:hasLarkDefinition?"lark":"regex",definition:hasLarkDefinition?larkDefinition:regexDefinition,inputProperty:inferGrammarInputProperty(tool)}}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`)}}function createGrammarToolInputProperties(tools,supportsOpenAIGrammarTools){let properties=new Map;for(let tool of tools??[]){let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);grammar&&properties.set(tool.name,grammar.inputProperty)}return properties}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:chars+=block.name.length+safeJsonStringify(block.arguments).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i=0;i<messages.length;i++){let message=messages[i];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i=usageInfo.index+1;i<messages.length;i++)trailingTokens+=estimateMessageTokens(messages[i]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify(tools))}var CONTEXT_SAFETY_TOKENS=4096,CONTEXT_SAFETY_RATIO=.15,MIN_OUTPUT_WITH_RATIO_MARGIN=32768,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let input=estimateContextTokens(context).tokens,margin=Math.max(CONTEXT_SAFETY_TOKENS,Math.ceil(input*CONTEXT_SAFETY_RATIO)),room=model.contextWindow-input-margin;return room<MIN_OUTPUT_WITH_RATIO_MARGIN&&(room=Math.min(MIN_OUTPUT_WITH_RATIO_MARGIN,model.contextWindow-input-CONTEXT_SAFETY_TOKENS)),Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,room))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,disableContinuation:options?.disableContinuation,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)",ERROR_TOOL_IMAGE_PLACEHOLDER="(image attached after the tool results)";function splitErrorToolResultImages(msg){if(!msg.isError)return;let images=msg.content.filter(block=>block.type==="image");if(images.length!==0)return{content:replaceImagesWithPlaceholder(msg.content,ERROR_TOOL_IMAGE_PLACEHOLDER),caption:`Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,images}}function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i=0;i<transformed.length;i++){let msg=transformed[i];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b=>b.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}export{prefersJsonSchemaStrictSampling,getJsonSchemaToolParameters,getGrammarToolInput,appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,resolveJsonSchemaStrictSampling,resolveGrammarConstrainedSampling,createGrammarToolInputProperties,clampMaxTokensToContext,resolveSamplingParams,buildBaseOptions,thinkingBudgetForLevel,clampThinkingBudgetToAnswerRoom,adjustMaxTokensForThinking,splitErrorToolResultImages,transformMessages};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- import{retryProviderRequest}from"./chunk-RCRGGYLW.js";import{headersToRecord,providerHeadersToRecord}from"./chunk-EBVYI75P.js";import{calculateCost}from"./chunk-7HQNDYWE.js";import{getIdentityHeaders}from"./chunk-BIXKXDGW.js";function httpError(label,response,body){let error=new Error(`${label} returned ${response.status}`);return error.status=response.status,error.headers=response.headers,error.body=body,error}function timeoutError(timeoutMs){let error=new Error(`Request timed out after ${timeoutMs}ms`);return error.name="TimeoutError",error.status=void 0,error.headers=void 0,error.body="",error}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function requiredNumber(label,value,field){if(typeof value!="number"||!Number.isFinite(value))throw new Error(`${label} returned an invalid ${field}`);return value}function requestHeaders(model,apiKey,optionsHeaders,identity){return providerHeadersToRecord(getIdentityHeaders(model,identity),{authorization:`Bearer ${apiKey}`,"content-type":"application/json"},model.headers,optionsHeaders)??{}}async function postClassifierRequest(label,url,model,body,options,noRetryStatuses){if(!options?.apiKey)throw new Error(`No API key for provider: ${model.provider}`);let apiKey=options.apiKey,payload=body,transformed=await options.onPayload?.(payload,model);transformed!==void 0&&(payload=transformed);let requestFetch=options.fetch??globalThis.fetch,{response,json}=await retryProviderRequest(async()=>{let timeoutSignal=options.timeoutMs!==void 0?AbortSignal.timeout(options.timeoutMs):void 0,signal=options.signal&&timeoutSignal?AbortSignal.any([options.signal,timeoutSignal]):options.signal??timeoutSignal;try{let next=await requestFetch(url,{method:"POST",headers:requestHeaders(model,apiKey,options.headers,options.identity),body:JSON.stringify(payload),signal});if(!next.ok)throw httpError(label,next,await next.text());return{response:next,json:await next.json()}}catch(error){throw timeoutSignal?.aborted&&!options.signal?.aborted?timeoutError(options.timeoutMs):error}},{maxRetries:options.maxRetries??2,maxRetryDelayMs:options.maxRetryDelayMs,signal:options.signal,noRetryStatuses});return await options.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),json}function tokenCount(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:0}function parseClassifierUsage(value,model){if(!isRecord(value)||value.input_tokens===void 0&&value.output_tokens===void 0)return;let input=tokenCount(value.input_tokens),output=tokenCount(value.output_tokens),usage={input,output,cacheRead:0,cacheWrite:0,totalTokens:input+output,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return calculateCost(model,usage),usage}export{isRecord,requiredNumber,postClassifierRequest,parseClassifierUsage};
2
+ import{retryProviderRequest}from"./chunk-RCRGGYLW.js";import{headersToRecord,providerHeadersToRecord}from"./chunk-EBVYI75P.js";import{calculateCost}from"./chunk-4MO4FSW4.js";import{getIdentityHeaders}from"./chunk-IUK7PQZQ.js";function httpError(label,response,body){let error=new Error(`${label} returned ${response.status}`);return error.status=response.status,error.headers=response.headers,error.body=body,error}function timeoutError(timeoutMs){let error=new Error(`Request timed out after ${timeoutMs}ms`);return error.name="TimeoutError",error.status=void 0,error.headers=void 0,error.body="",error}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function requiredNumber(label,value,field){if(typeof value!="number"||!Number.isFinite(value))throw new Error(`${label} returned an invalid ${field}`);return value}function requestHeaders(model,apiKey,optionsHeaders,identity){return providerHeadersToRecord(getIdentityHeaders(model,identity),{authorization:`Bearer ${apiKey}`,"content-type":"application/json"},model.headers,optionsHeaders)??{}}async function postClassifierRequest(label,url,model,body,options,noRetryStatuses){if(!options?.apiKey)throw new Error(`No API key for provider: ${model.provider}`);let apiKey=options.apiKey,payload=body,transformed=await options.onPayload?.(payload,model);transformed!==void 0&&(payload=transformed);let requestFetch=options.fetch??globalThis.fetch,{response,json}=await retryProviderRequest(async()=>{let timeoutSignal=options.timeoutMs!==void 0?AbortSignal.timeout(options.timeoutMs):void 0,signal=options.signal&&timeoutSignal?AbortSignal.any([options.signal,timeoutSignal]):options.signal??timeoutSignal;try{let next=await requestFetch(url,{method:"POST",headers:requestHeaders(model,apiKey,options.headers,options.identity),body:JSON.stringify(payload),signal});if(!next.ok)throw httpError(label,next,await next.text());return{response:next,json:await next.json()}}catch(error){throw timeoutSignal?.aborted&&!options.signal?.aborted?timeoutError(options.timeoutMs):error}},{maxRetries:options.maxRetries??2,maxRetryDelayMs:options.maxRetryDelayMs,signal:options.signal,noRetryStatuses});return await options.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),json}function tokenCount(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:0}function parseClassifierUsage(value,model){if(!isRecord(value)||value.input_tokens===void 0&&value.output_tokens===void 0)return;let totalInput=tokenCount(value.input_tokens),output=tokenCount(value.output_tokens),details=isRecord(value.input_tokens_details)?value.input_tokens_details:void 0,cacheRead=Math.min(tokenCount(details?.cached_tokens),totalInput),cacheWrite=Math.min(tokenCount(details?.cache_write_tokens),totalInput-cacheRead),usage={input:totalInput-cacheRead-cacheWrite,output,cacheRead,cacheWrite,totalTokens:totalInput+output,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return calculateCost(model,usage),usage}export{isRecord,requiredNumber,postClassifierRequest,parseClassifierUsage};