@maxmo74/pi-coding-agent 1.5.2-max.15 → 1.6.0-max.16

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 (228) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +1 -1
  3. package/dist/bundle/chunks/{anthropic-messages-CA3HHOL3.js → anthropic-messages-WAFIHSF7.js} +3 -3
  4. package/dist/bundle/chunks/{azure-openai-responses-76TWS6DT.js → azure-openai-responses-EB4MRIM4.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
  6. package/dist/bundle/chunks/{chunk-FMPAMX2W.js → chunk-E6LJTZYC.js} +1 -1
  7. package/dist/bundle/chunks/chunk-EEBRZED2.js +44 -0
  8. package/dist/bundle/chunks/chunk-EVSO24NP.js +2 -0
  9. package/dist/bundle/chunks/{chunk-M6TSYZBS.js → chunk-EXXWEFU5.js} +67 -64
  10. package/dist/bundle/chunks/{chunk-ZBIZYD6W.js → chunk-F7LEMV2T.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-VKJQ6CME.js → chunk-I6HYYNH6.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-BAC3QPNW.js → chunk-ILDLA2JW.js} +1 -1
  13. package/dist/bundle/chunks/chunk-INODY4DR.js +2 -0
  14. package/dist/bundle/chunks/{chunk-COKMCNCW.js → chunk-KREOSXD7.js} +1 -1
  15. package/dist/bundle/chunks/chunk-LWG2CUTI.js +31 -0
  16. package/dist/bundle/chunks/{chunk-WL4TUXY7.js → chunk-NRLRGOCX.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-AUUCDC7R.js → chunk-NRY4NBZW.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-4KSTFUIK.js → chunk-NV3NPOPF.js} +3 -2
  19. package/dist/bundle/chunks/{chunk-IQUU5XIT.js → chunk-RCNEHRMW.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-FF6XOTWB.js → chunk-X26YOAEH.js} +11 -10
  21. package/dist/bundle/chunks/chunk-X6RQRO3L.js +16 -0
  22. package/dist/bundle/chunks/{chunk-4UNPP53I.js → chunk-XGGZYFNG.js} +2 -2
  23. package/dist/bundle/chunks/chunk-XJ2YV77J.js +30 -0
  24. package/dist/bundle/chunks/{chunk-RKNK4Y6L.js → chunk-YOWSKVK7.js} +1 -1
  25. package/dist/bundle/chunks/{cli-2MK3TR7P.js → cli-QMJEURSM.js} +1 -1
  26. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-U4J7D646.js → cloudflare-workers-ai-system-one-AMCR7QEI.js} +1 -1
  27. package/dist/bundle/chunks/{easter-egg-3d-GEVPKQF6.js → easter-egg-3d-7CBVPJQ3.js} +1 -1
  28. package/dist/bundle/chunks/{execute-L2EEDV3L.js → execute-XDNPBEMU.js} +1 -1
  29. package/dist/bundle/chunks/github-copilot.js +1 -1
  30. package/dist/bundle/chunks/google-generative-ai-43M4N5LK.js +2 -0
  31. package/dist/bundle/chunks/google-vertex-2B3PASK2.js +2 -0
  32. package/dist/bundle/chunks/{llama-cpp-classify-EJXCQRUQ.js → llama-cpp-classify-XXZYF3RR.js} +1 -1
  33. package/dist/bundle/chunks/{mistral-conversations-S277EKLB.js → mistral-conversations-E3D5ZQKB.js} +2 -2
  34. package/dist/bundle/chunks/openai-codex-responses-MSQDSDUR.js +10 -0
  35. package/dist/bundle/chunks/{openai-completions-HRZOSLBO.js → openai-completions-4IC6AGTR.js} +2 -2
  36. package/dist/bundle/chunks/{openai-decisions-F66BDLOM.js → openai-decisions-LZ2RLVRX.js} +1 -1
  37. package/dist/bundle/chunks/{openai-responses-BAKFWTGE.js → openai-responses-MCO3BHCC.js} +1 -1
  38. package/dist/bundle/chunks/{openrouter-images-VXF5TVIK.js → openrouter-images-SHUJ3VSG.js} +1 -1
  39. package/dist/bundle/chunks/{pi-messages-UBJKNDRN.js → pi-messages-NIKOQ4O7.js} +1 -1
  40. package/dist/bundle/chunks/{runtime-J5ZSBGTX.js → runtime-F3SXQONS.js} +1 -1
  41. package/dist/bundle/chunks/{typesafe-system-one-56TEMIHL.js → typesafe-system-one-R2CDUWNO.js} +1 -1
  42. package/dist/bundle/chunks/{virtual-modules-MRQHQVIQ.js → virtual-modules-2WYTGPJ3.js} +1 -1
  43. package/dist/bundle/cli-runtime.js +1 -1
  44. package/dist/bundle/index.js +1 -1
  45. package/dist/bundle/rpc-entry.js +1 -1
  46. package/dist/cli/args.d.ts.map +1 -1
  47. package/dist/cli/args.js +4 -2
  48. package/dist/cli/args.js.map +1 -1
  49. package/dist/cli/config-selector.d.ts.map +1 -1
  50. package/dist/cli/config-selector.js +9 -6
  51. package/dist/cli/config-selector.js.map +1 -1
  52. package/dist/cli/session-picker.d.ts.map +1 -1
  53. package/dist/cli/session-picker.js +9 -6
  54. package/dist/cli/session-picker.js.map +1 -1
  55. package/dist/cli/startup-ui.d.ts.map +1 -1
  56. package/dist/cli/startup-ui.js +4 -0
  57. package/dist/cli/startup-ui.js.map +1 -1
  58. package/dist/core/agent-session-runtime.d.ts +11 -0
  59. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  60. package/dist/core/agent-session-runtime.js +19 -0
  61. package/dist/core/agent-session-runtime.js.map +1 -1
  62. package/dist/core/agent-session.d.ts +6 -3
  63. package/dist/core/agent-session.d.ts.map +1 -1
  64. package/dist/core/agent-session.js +21 -13
  65. package/dist/core/agent-session.js.map +1 -1
  66. package/dist/core/exec.d.ts +1 -0
  67. package/dist/core/exec.d.ts.map +1 -1
  68. package/dist/core/exec.js +4 -1
  69. package/dist/core/exec.js.map +1 -1
  70. package/dist/core/export-html/ansi-to-html.d.ts +6 -1
  71. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  72. package/dist/core/export-html/ansi-to-html.js +57 -20
  73. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  74. package/dist/core/export-html/template.js +1 -1
  75. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  76. package/dist/core/export-html/tool-renderer.js +2 -3
  77. package/dist/core/export-html/tool-renderer.js.map +1 -1
  78. package/dist/core/extensions/loader.d.ts.map +1 -1
  79. package/dist/core/extensions/loader.js +18 -1
  80. package/dist/core/extensions/loader.js.map +1 -1
  81. package/dist/core/extensions/runner.d.ts.map +1 -1
  82. package/dist/core/extensions/runner.js +5 -0
  83. package/dist/core/extensions/runner.js.map +1 -1
  84. package/dist/core/extensions/types.d.ts +5 -0
  85. package/dist/core/extensions/types.d.ts.map +1 -1
  86. package/dist/core/extensions/types.js.map +1 -1
  87. package/dist/core/model-resolver.d.ts +0 -8
  88. package/dist/core/model-resolver.d.ts.map +1 -1
  89. package/dist/core/model-resolver.js +3 -67
  90. package/dist/core/model-resolver.js.map +1 -1
  91. package/dist/core/package-manager.d.ts +16 -0
  92. package/dist/core/package-manager.d.ts.map +1 -1
  93. package/dist/core/package-manager.js +45 -2
  94. package/dist/core/package-manager.js.map +1 -1
  95. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  96. package/dist/core/remote-catalog-provider.js +7 -0
  97. package/dist/core/remote-catalog-provider.js.map +1 -1
  98. package/dist/core/resource-loader.d.ts +5 -1
  99. package/dist/core/resource-loader.d.ts.map +1 -1
  100. package/dist/core/resource-loader.js +2 -0
  101. package/dist/core/resource-loader.js.map +1 -1
  102. package/dist/core/session-manager.d.ts.map +1 -1
  103. package/dist/core/session-manager.js +45 -36
  104. package/dist/core/session-manager.js.map +1 -1
  105. package/dist/core/session-ownership.js +15 -1
  106. package/dist/core/session-ownership.js.map +1 -1
  107. package/dist/core/tools/find.d.ts.map +1 -1
  108. package/dist/core/tools/find.js +27 -16
  109. package/dist/core/tools/find.js.map +1 -1
  110. package/dist/core/tools/grep.js +1 -1
  111. package/dist/core/tools/grep.js.map +1 -1
  112. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  113. package/dist/core/tools/output-accumulator.js +4 -1
  114. package/dist/core/tools/output-accumulator.js.map +1 -1
  115. package/dist/core/tools/read.d.ts +5 -0
  116. package/dist/core/tools/read.d.ts.map +1 -1
  117. package/dist/core/tools/read.js +10 -15
  118. package/dist/core/tools/read.js.map +1 -1
  119. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  120. package/dist/core/tools/renderers/read.js +6 -2
  121. package/dist/core/tools/renderers/read.js.map +1 -1
  122. package/dist/extensions/llama/provider.d.ts +1 -1
  123. package/dist/extensions/llama/provider.d.ts.map +1 -1
  124. package/dist/extensions/llama/provider.js +6 -4
  125. package/dist/extensions/llama/provider.js.map +1 -1
  126. package/dist/extensions/mcp/index.d.ts.map +1 -1
  127. package/dist/extensions/mcp/index.js +4 -7
  128. package/dist/extensions/mcp/index.js.map +1 -1
  129. package/dist/main.d.ts.map +1 -1
  130. package/dist/main.js +39 -16
  131. package/dist/main.js.map +1 -1
  132. package/dist/modes/diagnostics-stderr.d.ts +4 -0
  133. package/dist/modes/diagnostics-stderr.d.ts.map +1 -0
  134. package/dist/modes/diagnostics-stderr.js +11 -0
  135. package/dist/modes/diagnostics-stderr.js.map +1 -0
  136. package/dist/modes/interactive/components/assistant-message.d.ts +2 -1
  137. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  138. package/dist/modes/interactive/components/assistant-message.js +9 -3
  139. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  140. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  141. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  142. package/dist/modes/interactive/components/config-selector.js +5 -2
  143. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  144. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  145. package/dist/modes/interactive/components/model-selector.js +5 -2
  146. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  147. package/dist/modes/interactive/components/oauth-selector.d.ts +1 -1
  148. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  149. package/dist/modes/interactive/components/oauth-selector.js +7 -3
  150. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  151. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
  152. package/dist/modes/interactive/components/radius-login-selector.js +2 -1
  153. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
  154. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  155. package/dist/modes/interactive/components/scoped-models-selector.js +9 -1
  156. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  157. package/dist/modes/interactive/components/session-selector.d.ts +8 -1
  158. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  159. package/dist/modes/interactive/components/session-selector.js +41 -9
  160. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  161. package/dist/modes/interactive/components/settings-submenu.d.ts +1 -1
  162. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  163. package/dist/modes/interactive/components/settings-submenu.js +5 -1
  164. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  165. package/dist/modes/interactive/components/themed-text.d.ts +1 -1
  166. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
  167. package/dist/modes/interactive/components/themed-text.js.map +1 -1
  168. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  169. package/dist/modes/interactive/components/thinking-selector.js +5 -1
  170. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  171. package/dist/modes/interactive/components/tool-execution.d.ts +1 -1
  172. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  173. package/dist/modes/interactive/components/tool-execution.js +3 -1
  174. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  175. package/dist/modes/interactive/components/user-message.d.ts +2 -1
  176. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  177. package/dist/modes/interactive/components/user-message.js +9 -3
  178. package/dist/modes/interactive/components/user-message.js.map +1 -1
  179. package/dist/modes/interactive/components/visual-truncate.d.ts +2 -2
  180. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  181. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  182. package/dist/modes/interactive/interactive-mode.d.ts +1 -1
  183. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  184. package/dist/modes/interactive/interactive-mode.js +71 -36
  185. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  186. package/dist/modes/interactive/session-share.js +2 -0
  187. package/dist/modes/interactive/session-share.js.map +1 -1
  188. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  189. package/dist/modes/interactive/theme/theme.js +1 -0
  190. package/dist/modes/interactive/theme/theme.js.map +1 -1
  191. package/dist/modes/print-mode.d.ts.map +1 -1
  192. package/dist/modes/print-mode.js +16 -13
  193. package/dist/modes/print-mode.js.map +1 -1
  194. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  195. package/dist/modes/rpc/rpc-mode.js +15 -23
  196. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  197. package/dist/package-manager-cli.d.ts.map +1 -1
  198. package/dist/package-manager-cli.js +14 -1
  199. package/dist/package-manager-cli.js.map +1 -1
  200. package/dist/utils/changelog.d.ts.map +1 -1
  201. package/dist/utils/changelog.js +3 -2
  202. package/dist/utils/changelog.js.map +1 -1
  203. package/dist/utils/flush-stdout.d.ts +8 -0
  204. package/dist/utils/flush-stdout.d.ts.map +1 -0
  205. package/dist/utils/flush-stdout.js +23 -0
  206. package/dist/utils/flush-stdout.js.map +1 -0
  207. package/docs/extensions.md +4 -4
  208. package/docs/models-configuration.md +4 -3
  209. package/docs/nvidia-rtx-llama-cpp.md +5 -5
  210. package/docs/providers.md +4 -2
  211. package/docs/rpc-commands.md +1 -1
  212. package/docs/tui.md +2 -0
  213. package/examples/extensions/gondolin/index.ts +4 -7
  214. package/package.json +10 -10
  215. package/schemas/models.schema.json +2 -2
  216. package/dist/bundle/chunks/chunk-CF5GWZHW.js +0 -31
  217. package/dist/bundle/chunks/chunk-GFUN2N5K.js +0 -2
  218. package/dist/bundle/chunks/chunk-QN4TOIZN.js +0 -16
  219. package/dist/bundle/chunks/chunk-V7SLUK6A.js +0 -44
  220. package/dist/bundle/chunks/chunk-YTPJCXUB.js +0 -30
  221. package/dist/bundle/chunks/chunk-ZGYS4UTC.js +0 -2
  222. package/dist/bundle/chunks/google-generative-ai-D5B6W47J.js +0 -2
  223. package/dist/bundle/chunks/google-vertex-U4H5YDEW.js +0 -2
  224. package/dist/bundle/chunks/openai-codex-responses-TEQRB65N.js +0 -10
  225. package/dist/utils/deprecation.d.ts +0 -4
  226. package/dist/utils/deprecation.d.ts.map +0 -1
  227. package/dist/utils/deprecation.js +0 -13
  228. package/dist/utils/deprecation.js.map +0 -1
@@ -0,0 +1,16 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{shortHash}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-EVSO24NP.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{ToolCallArgumentsStream}from"./chunk-FFMDRXC4.js";import{calculateCost,resolveTranscript,resolveTranscriptTools}from"./chunk-NRY4NBZW.js";import{appendAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import{getSystemMessageText,renderSystemMessageUpdate}from"./chunk-ILDLA2JW.js";function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function convertToolResultOutput(model,content){let textResult=content.filter(c=>c.type==="text").map(c=>c.text).join(`
3
+ `),images=content.filter(c=>c.type==="image"),hasText=textResult.trim().length>0;if(images.length===0||!model.input.includes("image"))return sanitizeSurrogates(hasText?textResult:images.length>0?"(see attached image)":"(no tool output)");let output=[];hasText&&output.push({type:"input_text",text:sanitizeSurrogates(textResult)});for(let image of images)output.push({type:"input_image",detail:"auto",image_url:`data:${image.mimeType};base64,${image.data}`});return output}function getResponsesToolSupport(options){return options.supportsMidConvoSystemMessages&&options.supportsAdditionalTools?"changes":options.supportsToolSearch?"additions":"none"}function renderIncrementalToolsNotice(unavailable){let notice="This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.";return unavailable.size>0?`${notice}
4
+ Still unavailable: ${[...unavailable].join(", ")}.`:notice}function renderToolRemovalNotice(names){return`The following tools are no longer available. Do not call them:
5
+ ${names.map(name=>`- ${name}`).join(`
6
+ `)}`}function convertResponsesMessages(model,context,allowedToolCallProviders,options){let normalizedContext=resolveTranscript(context,options?.supportsMidConvoSystemMessages),messages=[],normalizeIdPart=part=>{let sanitized=part.replace(/[^a-zA-Z0-9_-]/g,"_");return(sanitized.length>64?sanitized.slice(0,64):sanitized).replace(/_+$/,"")},buildForeignResponsesItemId=itemId=>{let normalized=`fc_${shortHash(itemId)}`;return normalized.length>64?normalized.slice(0,64):normalized},normalizeToolCallId=(id,_targetModel,source)=>{if(!allowedToolCallProviders.has(model.provider)||!id.includes("|"))return normalizeIdPart(id);let[callId,itemId]=id.split("|"),normalizedCallId=normalizeIdPart(callId),normalizedItemId=source.provider!==model.provider||source.api!==model.api?buildForeignResponsesItemId(itemId):normalizeIdPart(itemId);return normalizedItemId.startsWith("fc_")||(normalizedItemId=normalizeIdPart(`fc_${normalizedItemId}`)),`${normalizedCallId}|${normalizedItemId}`},transformedMessages=transformMessages(normalizedContext.messages,model,normalizeToolCallId),toolSupport=getResponsesToolSupport(options??{}),transcriptTools=resolveTranscriptTools(normalizedContext.messages,toolSupport),declaredAdditionalTools=!1,unavailableTools=new Set,appendSystemToolAdditions=(message,seed)=>{let tools=message.toolsAdded??[];for(let tool of tools)unavailableTools.delete(tool.name);if(tools.length===0)return;if(toolSupport==="changes"){declaredAdditionalTools&&messages.push({role:instructionRole,content:renderIncrementalToolsNotice(unavailableTools)}),declaredAdditionalTools=!0,messages.push({type:"additional_tools",role:"developer",tools:convertResponsesTools(tools,options?.toolOptions)});return}if(toolSupport!=="additions")return;let names=tools.map(tool=>tool.name),callId=`pi_tool_load_${shortHash(`${seed}:${names.join(",")}`)}`;messages.push({type:"tool_search_call",call_id:callId,execution:"client",status:"completed",arguments:{query:names.join(" "),limit:names.length}}),messages.push({type:"tool_search_output",call_id:callId,execution:"client",status:"completed",tools:convertResponsesTools(tools,{...options?.toolOptions,toolSearchResult:!0})})},pushConfigurationUpdate=effort=>{messages.push({type:"configuration_update",reasoning:{effort}})},compat=model.compat,instructionRole=model.reasoning&&compat?.supportsDeveloperRole!==!1?"developer":"system",msgIndex=0,sourceIndex=0,systemIndex=0;for(let msg of transformedMessages){let isLeadingSystemMessage=sourceIndex++===0&&msg.role==="system";if(msg.role==="system"){let anchorsToolChanges=systemIndex++>=transcriptTools.foldedSystemMessages;anchorsToolChanges&&appendSystemToolAdditions(msg,`system:${msgIndex}`);let parts=[isLeadingSystemMessage?getSystemMessageText(msg):renderSystemMessageUpdate(msg)];if(anchorsToolChanges){let added=new Set((msg.toolsAdded??[]).map(tool=>tool.name)),removed=(msg.toolsRemoved??[]).map(tool=>tool.name).filter(name=>!added.has(name));removed.length>0&&parts.push(renderToolRemovalNotice(removed));for(let name of removed)unavailableTools.add(name)}let text=parts.filter(part=>part.length>0).join(`
7
+
8
+ `);text.length>0&&messages.push({role:instructionRole,content:sanitizeSurrogates(text)})}else if(msg.role==="user")if(typeof msg.content=="string")messages.push({role:"user",content:[{type:"input_text",text:sanitizeSurrogates(msg.content)}]});else{let content=msg.content.map(item=>item.type==="text"?{type:"input_text",text:sanitizeSurrogates(item.text)}:{type:"input_image",detail:"auto",image_url:`data:${item.mimeType};base64,${item.data}`});if(content.length===0)continue;messages.push({role:"user",content})}else if(msg.role==="assistant"){let output=[],assistantMsg=msg,isSameProviderAndApi=assistantMsg.provider===model.provider&&assistantMsg.api===model.api,isSameModel=isSameProviderAndApi&&assistantMsg.model===model.id,isDifferentModel=isSameProviderAndApi&&assistantMsg.model!==model.id,textBlockIndex=0;for(let block of msg.content)if(block.type==="thinking"){if(block.thinkingSignature){let reasoningItem=JSON.parse(block.thinkingSignature);output.push(reasoningItem)}}else if(block.type==="text"){let textBlock=block,parsedSignature=parseTextSignature(textBlock.textSignature),fallbackMessageId=textBlockIndex===0?`msg_pi_${msgIndex}`:`msg_pi_${msgIndex}_${textBlockIndex}`;textBlockIndex++;let msgId=parsedSignature?.id;msgId?msgId.length>64&&(msgId=`msg_${shortHash(msgId)}`):msgId=fallbackMessageId,output.push({type:"message",role:"assistant",content:[{type:"output_text",text:sanitizeSurrogates(textBlock.text),annotations:[]}],status:"completed",id:msgId,phase:parsedSignature?.phase})}else if(block.type==="toolCall"){let toolCall=block,[callId,itemIdRaw]=toolCall.id.split("|"),customInputProperty=options?.grammarToolInputProperties?.get(toolCall.name),itemId=itemIdRaw,itemIdPrefix=customInputProperty===void 0?"fc_":"ctc_";(isDifferentModel||!itemId?.startsWith(itemIdPrefix))&&(itemId=void 0),customInputProperty!==void 0?output.push({type:"custom_tool_call",id:itemId,call_id:callId,name:toolCall.name,input:sanitizeSurrogates(getGrammarToolInput(toolCall.name,toolCall.arguments,customInputProperty)),...isSameModel&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}}):output.push({type:"function_call",id:itemId,call_id:callId,name:toolCall.name,arguments:JSON.stringify(toolCall.arguments),...isSameModel&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}})}if(output.length===0)continue;options?.configurationUpdateEffort!==void 0&&isSameModel&&msg.providerThinkingLevel!==void 0&&pushConfigurationUpdate(msg.providerThinkingLevel),messages.push(...output)}else if(msg.role==="toolResult"){let[callId]=msg.toolCallId.split("|"),output=convertToolResultOutput(model,msg.content);options?.grammarToolInputProperties?.has(msg.toolName)?messages.push({type:"custom_tool_call_output",call_id:callId,output}):messages.push({type:"function_call_output",call_id:callId,output})}isLeadingSystemMessage||msgIndex++}return options?.configurationUpdateEffort!==void 0&&pushConfigurationUpdate(options.configurationUpdateEffort),messages}function convertResponsesTools(tools,options){let defaultStrict=options?.strict===void 0?!1:options.strict,supportsStrictMode=options?.supportsStrictMode??!0,supportsOpenAIGrammarTools=options?.supportsOpenAIGrammarTools??!1;return tools.map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);if(grammar)return{type:"custom",name:tool.name,description:tool.description,format:{type:"grammar",syntax:grammar.format,definition:grammar.definition},...options?.toolSearchResult?{defer_loading:!0}:{}};let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode)??defaultStrict,functionTool={type:"function",name:tool.name,description:tool.description,parameters:getJsonSchemaToolParameters(tool,strict===!0),...options?.toolSearchResult?{defer_loading:!0}:{}};return supportsStrictMode&&(functionTool.strict=strict),functionTool})}async function processResponsesStream(openaiStream,output,stream,model,options){let sawTerminalResponseEvent=!1,outputSlots=new Map,unfinishedToolCalls=new Set,reasoningBlocksById=new Map,applyMessagePhaseStopReason=item=>{item.type==="message"&&item.phase==="final_answer"&&(output.stopReason="stop")},getSlot=(outputIndex,type)=>{let slot=outputSlots.get(outputIndex);return slot?.type===type?slot:void 0},pushToolCallDelta=(slot,delta)=>{delta!==void 0&&stream.push({type:"toolcall_delta",contentIndex:slot.contentIndex,delta,partial:output})},createSlot=(outputIndex,item)=>{if(item.type==="reasoning"){let block={type:"thinking",thinking:""};output.content.push(block);let slot={type:"thinking",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"thinking_start",contentIndex:slot.contentIndex,partial:output}),slot}if(item.type==="message"){applyMessagePhaseStopReason(item);let block={type:"text",text:""};output.content.push(block);let slot={type:"text",block,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot),stream.push({type:"text_start",contentIndex:slot.contentIndex,partial:output}),slot}if(item.type==="function_call"){let args=new ToolCallArgumentsStream,block={type:"toolCall",id:`${item.call_id}|${item.id}`,name:item.name,arguments:item.arguments?args.append(item.arguments):{},...item.namespace!==void 0?{namespace:item.namespace}:{}};output.content.push(block),unfinishedToolCalls.add(block);let slot={type:"toolCall",block,contentIndex:output.content.length-1,input:{kind:"json",arguments:args}};return outputSlots.set(outputIndex,slot),stream.push({type:"toolcall_start",contentIndex:slot.contentIndex,partial:output}),slot}if(item.type==="custom_tool_call"){let inputProperty=options?.grammarToolInputProperties?.get(item.name)??"input",input=item.input||"",block={type:"toolCall",id:`${item.call_id}|${item.id}`,name:item.name,arguments:{[inputProperty]:input},...item.namespace!==void 0?{namespace:item.namespace}:{}};output.content.push(block),unfinishedToolCalls.add(block);let slot={type:"toolCall",block,contentIndex:output.content.length-1,input:customInput(inputProperty,input)};return outputSlots.set(outputIndex,slot),stream.push({type:"toolcall_start",contentIndex:slot.contentIndex,partial:output}),slot}},getOrCreateSlot=(outputIndex,item)=>outputSlots.get(outputIndex)??createSlot(outputIndex,item),backfillReasoningSignatures=responseOutput=>{for(let item of responseOutput){if(item.type!=="reasoning"||!item.encrypted_content)continue;let block=reasoningBlocksById.get(item.id);if(!block?.thinkingSignature)continue;let storedItem=JSON.parse(block.thinkingSignature);storedItem.encrypted_content||(block.thinkingSignature=JSON.stringify({...storedItem,encrypted_content:item.encrypted_content}))}},finalizeResponse=response=>{if(sawTerminalResponseEvent=!0,backfillReasoningSignatures(response.output??[]),appendReasoningRemovals(output,response.input_transformations),response?.id&&(output.responseId=response.id),response?.usage){let inputDetails=response.usage.input_tokens_details,cachedTokens=inputDetails?.cached_tokens||0,cacheWriteTokens=inputDetails?.cache_write_tokens||0;output.usage={input:Math.max(0,(response.usage.input_tokens||0)-cachedTokens-cacheWriteTokens),output:response.usage.output_tokens||0,cacheRead:cachedTokens,cacheWrite:cacheWriteTokens,reasoning:response.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:response.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(calculateCost(model,output.usage),options?.applyServiceTierPricing){let serviceTier=options.resolveServiceTier?options.resolveServiceTier(response?.service_tier,options.serviceTier):response?.service_tier??options.serviceTier;options.applyServiceTierPricing(output.usage,serviceTier)}let status=response?.status,incompleteDetails=response?.incomplete_details,incompleteReason=typeof incompleteDetails?.reason=="string"?incompleteDetails.reason:void 0;output.rawStopReason=incompleteReason?`${status}.${incompleteReason}`:status;let mappedStop=mapStopReason(status,incompleteReason);output.stopReason=mappedStop.stopReason,mappedStop.errorMessage===void 0?delete output.errorMessage:output.errorMessage=mappedStop.errorMessage,output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")};for await(let event of openaiStream)if(await options?.onProviderStreamEvent?.(event,model),event.type==="response.created")output.responseId=event.response.id;else if(event.type==="response.output_item.added")createSlot(event.output_index,event.item);else if(event.type==="response.reasoning_summary_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.reasoning_summary_part.done"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=`
9
+
10
+ `,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:`
11
+
12
+ `,partial:output})}else if(event.type==="response.reasoning_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.output_text.delta"){let slot=getSlot(event.output_index,"text");if(!slot)continue;slot.block.text+=event.delta,stream.push({type:"text_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.refusal.delta"){let slot=getSlot(event.output_index,"text");if(!slot)continue;slot.block.text+=event.delta,stream.push({type:"text_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.function_call_arguments.delta"){let slot=getSlot(event.output_index,"toolCall");if(slot?.input.kind!=="json")continue;slot.block.arguments=slot.input.arguments.append(event.delta),pushToolCallDelta(slot,event.delta)}else if(event.type==="response.function_call_arguments.done"){let slot=getSlot(event.output_index,"toolCall");if(slot?.input.kind!=="json")continue;let replaced=slot.input.arguments.replace(event.arguments);slot.block.arguments=replaced.arguments,replaced.delta&&pushToolCallDelta(slot,replaced.delta)}else if(event.type==="response.custom_tool_call_input.delta"){let slot=getSlot(event.output_index,"toolCall");if(slot?.input.kind!=="custom")continue;pushToolCallDelta(slot,appendCustomInput(slot.block,slot.input,event.delta))}else if(event.type==="response.custom_tool_call_input.done"){let slot=getSlot(event.output_index,"toolCall");if(slot?.input.kind!=="custom")continue;pushToolCallDelta(slot,closeCustomInput(slot.block,slot.input,event.input))}else if(event.type==="response.output_item.done"){let item=event.item;applyMessagePhaseStopReason(item);let slot=getOrCreateSlot(event.output_index,item);if(item.type==="reasoning"&&slot?.type==="thinking"){let summaryText=item.summary?.map(s=>s.text).join(`
13
+
14
+ `)||"",contentText=item.content?.map(c=>c.text).join(`
15
+
16
+ `)||"";slot.block.thinking=summaryText||contentText||slot.block.thinking,slot.block.thinkingSignature=JSON.stringify(item),reasoningBlocksById.set(item.id,slot.block),stream.push({type:"thinking_end",contentIndex:slot.contentIndex,content:slot.block.thinking,partial:output}),outputSlots.delete(event.output_index)}else item.type==="message"&&slot?.type==="text"?(slot.block.text=item.content?.map(c=>c.type==="output_text"?c.text:c.refusal).join("")||"",slot.block.textSignature=encodeTextSignatureV1(item.id,item.phase??void 0),stream.push({type:"text_end",contentIndex:slot.contentIndex,content:slot.block.text,partial:output}),outputSlots.delete(event.output_index)):item.type==="function_call"&&slot?.type==="toolCall"&&slot.input.kind==="json"?(item.arguments&&slot.input.arguments.replace(item.arguments),Object.assign(slot.block,slot.input.arguments.finish()),item.namespace!==void 0&&(slot.block.namespace=item.namespace),unfinishedToolCalls.delete(slot.block),stream.push({type:"toolcall_end",contentIndex:slot.contentIndex,toolCall:slot.block,partial:output}),outputSlots.delete(event.output_index)):item.type==="custom_tool_call"&&slot?.type==="toolCall"&&slot.input.kind==="custom"&&(pushToolCallDelta(slot,closeCustomInput(slot.block,slot.input,item.input)),item.namespace!==void 0&&(slot.block.namespace=item.namespace),unfinishedToolCalls.delete(slot.block),stream.push({type:"toolcall_end",contentIndex:slot.contentIndex,toolCall:slot.block,partial:output}),outputSlots.delete(event.output_index))}else if(event.type==="response.completed"||event.type==="response.incomplete")finalizeResponse(event.response);else{if(event.type==="error")throw new Error(`Error Code ${event.code}: ${event.message}`||"Unknown error");if(event.type==="response.failed"){sawTerminalResponseEvent=!0,output.rawStopReason=event.response?.status;let error=event.response?.error,details=event.response?.incomplete_details,msg=error?`${error.code||"unknown"}: ${error.message||"no message"}`:details?.reason?`incomplete: ${details.reason}`:"Unknown error (no error details in response)";throw new Error(msg)}}if(!sawTerminalResponseEvent)throw new Error("OpenAI Responses stream ended before a terminal response event");if(output.stopReason==="toolUse")for(let toolCall of unfinishedToolCalls)throw new Error(`OpenAI Responses stream completed with an unfinished tool call: ${toolCall.name} (${toolCall.id})`)}function appendReasoningRemovals(output,transformations){if(!Array.isArray(transformations))return;let removals=transformations.filter(transformation=>transformation?.type==="reasoning"&&transformation.action==="removed"&&transformation.reason!=="turn_boundary");removals.length!==0&&appendAssistantMessageDiagnostic(output,{type:"openai_input_transformations",timestamp:Date.now(),details:{transformations:removals.map(({type,id,action,reason})=>({type,id,action,reason}))}})}function customInput(property,initialInput){let buffer={input:"",started:!1,closed:!1};return{kind:"custom",property,buffer,unsent:appendGrammarToolInputJsonDelta(buffer,property,initialInput)??""}}function appendCustomInput(block,input,delta){return sendCustomInput(block,input,appendGrammarToolInputJsonDelta(input.buffer,input.property,delta))}function closeCustomInput(block,input,finalInput){return sendCustomInput(block,input,closeGrammarToolInputJson(input.buffer,input.property,finalInput))}function sendCustomInput(block,input,jsonDelta){if(block.arguments={[input.property]:input.buffer.input},input.unsent==="")return jsonDelta;let sent=input.unsent+(jsonDelta??"");return input.unsent="",sent}function mapStopReason(status,incompleteReason){if(!status)return{stopReason:"stop"};switch(status){case"completed":return{stopReason:"stop"};case"incomplete":return incompleteReason==="max_output_tokens"?{stopReason:"length"}:{stopReason:"error",errorMessage:incompleteReason?`Response incomplete: ${incompleteReason}`:"Response incomplete without a provider reason"};case"failed":case"cancelled":return{stopReason:"error"};case"in_progress":case"queued":return{stopReason:"stop"};default:{let _exhaustive=status;throw new Error(`Unhandled stop reason: ${_exhaustive}`)}}}export{getResponsesToolSupport,convertResponsesMessages,convertResponsesTools,processResponsesStream};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{CodeHighlighter,Container,Spacer,Text,getCapabilities,getImageDimensions,hyperlink,imageFallback,keyHint,truncateToWidth}from"./chunk-FF6XOTWB.js";import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS,typebox_exports}from"./chunk-VKJQ6CME.js";import{sanitizeBinaryOutput}from"./chunk-Y55SJART.js";import{getDocsPath,resolvePath,shortenHomePath}from"./chunk-36QC74V4.js";import{randomBytes}from"node:crypto";import{createWriteStream}from"node:fs";import{writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";var OUTPUT_FILE_MODE=384;function createOutputFilePath(prefix,extension){return join(tmpdir(),`${prefix}-${randomBytes(8).toString("hex")}${extension}`)}async function writeOutputFile(prefix,extension,data){let path=createOutputFilePath(prefix,extension);return await writeFile(path,data,{mode:OUTPUT_FILE_MODE,flag:"wx"}),path}function createOutputFileStream(prefix,extension){let path=createOutputFilePath(prefix,extension);return{path,stream:createWriteStream(path,{mode:OUTPUT_FILE_MODE,flags:"wx"})}}function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{input:first.input+second.input,output:first.output+second.output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total,totalFromProvider:first.cost.totalFromProvider===!0&&second.cost.totalFromProvider===!0}}}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let entry of entries){let key,usage;if(entry.type==="message"&&entry.message.role==="assistant"?(key=`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`,usage=entry.message.usage):entry.type==="usage"?(key=`${entry.provider}/${entry.model}`,usage=entry.usage):entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage?(key="Tools/summaries",usage=entry.message.usage):(entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage&&(key="Tools/summaries",usage=entry.usage),!key||!usage)continue;let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite})).filter(entry=>entry.cost>0||entry.tokens>0).sort((a,b)=>b.cost-a.cost)}function truncateToVisualLines(text,maxVisualLines,width,paddingX=0,keep="end"){if(!text)return{visualLines:[],skippedCount:0};let allVisualLines=new Text(text,paddingX,0).render(width);if(allVisualLines.length<=maxVisualLines)return{visualLines:allVisualLines,skippedCount:0};let truncatedLines=keep==="start"?allVisualLines.slice(0,maxVisualLines):allVisualLines.slice(-maxVisualLines),skippedCount=allVisualLines.length-maxVisualLines;return{visualLines:truncatedLines,skippedCount}}var VisualLinePreview=class{options;cachedWidth;cachedLines;constructor(options){this.options=options}render(width){if(this.cachedLines===void 0||this.cachedWidth!==width){let{text,maxVisualLines,keep,formatHint}=this.options,preview=truncateToVisualLines(text,maxVisualLines,width,0,keep),lines=preview.visualLines;if(preview.skippedCount>0){let hint=truncateToWidth(formatHint(preview.skippedCount),width,"...");this.cachedLines=keep==="start"?[...lines,hint]:[hint,...lines]}else this.cachedLines=lines;this.cachedWidth=width}return this.cachedLines}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}};import{pathToFileURL}from"node:url";var ST="(?:\\u0007|\\u001B\\u005C|\\u009C)",OSC_START="\\u001B\\]",CSI_START="(?:(?:\\u001B\\[|\\u009B)[<=>]|[\\u001B\\u009B][[\\]()#;?]*)(?:\\d{1,4}(?:[;:]\\d{0,4})*)?",CSI_FINAL="[\\dA-PR-TZcf-nq-uy=><~]",ansiRegex=new RegExp(`(?:${OSC_START}[\\s\\S]*?${ST})|${CSI_START}${CSI_FINAL}`,"g"),unfinishedAnsiAtEndRegex=new RegExp(`(?:${OSC_START}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${CSI_START})$`),MAX_PENDING_ANSI_LENGTH=256;function splitIncompleteAnsiSuffix(value){if(!value.includes("\x1B")&&!value.includes("\x9B"))return{complete:value,pending:""};let windowStart=Math.max(0,value.length-MAX_PENDING_ANSI_LENGTH),match=unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));if(!match)return{complete:value,pending:""};let splitAt=windowStart+match.index;return{complete:value.slice(0,splitAt),pending:value.slice(splitAt)}}function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(ansiRegex,"")}function shortenPath(path){return typeof path!="string"?"":shortenHomePath(path)}function linkPath(styledText,rawPath,cwd){if(!getCapabilities().hyperlinks)return styledText;let absolutePath=resolvePath(rawPath,cwd);return hyperlink(styledText,pathToFileURL(absolutePath).href)}function str(value){return typeof value=="string"?value:value==null?"":null}function parseLineNumber(value){return typeof value=="string"&&value.trim()!==""&&(value=Number(value)),typeof value=="number"&&Number.isFinite(value)?value:void 0}function formatReadLineRange(offset,limit){if(offset==null&&limit==null)return"";let start=offset==null?1:parseLineNumber(offset);if(start===void 0)return"";if(limit==null)return`:${start}`;let count=parseLineNumber(limit);if(count===void 0)return"";let end=start+count-1;return`:${start}${end?`-${end}`:""}`}function replaceTabs(text){return text.replace(/\t/g," ")}function normalizeDisplayText(text){return text.replace(/\r/g,"")}function getTextOutput(result,showImages){if(!result)return"";let textBlocks=result.content.filter(c=>c.type==="text"),imageBlocks=result.content.filter(c=>c.type==="image"),output=textBlocks.map(c=>sanitizeBinaryOutput(stripAnsi(c.text||"")).replace(/\r/g,"")).join(`
2
+ import{CodeHighlighter,Container,Spacer,Text,getCapabilities,getImageDimensions,hyperlink,imageFallback,keyHint,truncateToWidth}from"./chunk-X26YOAEH.js";import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS,typebox_exports}from"./chunk-I6HYYNH6.js";import{sanitizeBinaryOutput}from"./chunk-Y55SJART.js";import{getDocsPath,resolvePath,shortenHomePath}from"./chunk-36QC74V4.js";import{randomBytes}from"node:crypto";import{createWriteStream}from"node:fs";import{writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";var OUTPUT_FILE_MODE=384;function createOutputFilePath(prefix,extension){return join(tmpdir(),`${prefix}-${randomBytes(8).toString("hex")}${extension}`)}async function writeOutputFile(prefix,extension,data){let path=createOutputFilePath(prefix,extension);return await writeFile(path,data,{mode:OUTPUT_FILE_MODE,flag:"wx"}),path}function createOutputFileStream(prefix,extension){let path=createOutputFilePath(prefix,extension);return{path,stream:createWriteStream(path,{mode:OUTPUT_FILE_MODE,flags:"wx"})}}function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{input:first.input+second.input,output:first.output+second.output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total,totalFromProvider:first.cost.totalFromProvider===!0&&second.cost.totalFromProvider===!0}}}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let entry of entries){let key,usage;if(entry.type==="message"&&entry.message.role==="assistant"?(key=`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`,usage=entry.message.usage):entry.type==="usage"?(key=`${entry.provider}/${entry.model}`,usage=entry.usage):entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage?(key="Tools/summaries",usage=entry.message.usage):(entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage&&(key="Tools/summaries",usage=entry.usage),!key||!usage)continue;let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite})).filter(entry=>entry.cost>0||entry.tokens>0).sort((a,b)=>b.cost-a.cost)}function truncateToVisualLines(text,maxVisualLines,width,paddingX=0,keep="end"){if(!text)return{visualLines:[],skippedCount:0};let allVisualLines=new Text(text,paddingX,0).render(width);if(allVisualLines.length<=maxVisualLines)return{visualLines:allVisualLines,skippedCount:0};let truncatedLines=keep==="start"?allVisualLines.slice(0,maxVisualLines):allVisualLines.slice(-maxVisualLines),skippedCount=allVisualLines.length-maxVisualLines;return{visualLines:truncatedLines,skippedCount}}var VisualLinePreview=class{options;cachedWidth;cachedLines;constructor(options){this.options=options}render(width){if(this.cachedLines===void 0||this.cachedWidth!==width){let{text,maxVisualLines,keep,formatHint}=this.options,preview=truncateToVisualLines(text,maxVisualLines,width,0,keep),lines=preview.visualLines;if(preview.skippedCount>0){let hint=truncateToWidth(formatHint(preview.skippedCount),width,"...");this.cachedLines=keep==="start"?[...lines,hint]:[hint,...lines]}else this.cachedLines=lines;this.cachedWidth=width}return this.cachedLines}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}};import{pathToFileURL}from"node:url";var ST="(?:\\u0007|\\u001B\\u005C|\\u009C)",OSC_START="\\u001B\\]",CSI_START="(?:(?:\\u001B\\[|\\u009B)[<=>]|[\\u001B\\u009B][[\\]()#;?]*)(?:\\d{1,4}(?:[;:]\\d{0,4})*)?",CSI_FINAL="[\\dA-PR-TZcf-nq-uy=><~]",ansiRegex=new RegExp(`(?:${OSC_START}[\\s\\S]*?${ST})|${CSI_START}${CSI_FINAL}`,"g"),unfinishedAnsiAtEndRegex=new RegExp(`(?:${OSC_START}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${CSI_START})$`),MAX_PENDING_ANSI_LENGTH=256;function splitIncompleteAnsiSuffix(value){if(!value.includes("\x1B")&&!value.includes("\x9B"))return{complete:value,pending:""};let windowStart=Math.max(0,value.length-MAX_PENDING_ANSI_LENGTH),match=unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));if(!match)return{complete:value,pending:""};let splitAt=windowStart+match.index;return{complete:value.slice(0,splitAt),pending:value.slice(splitAt)}}function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(ansiRegex,"")}function shortenPath(path){return typeof path!="string"?"":shortenHomePath(path)}function linkPath(styledText,rawPath,cwd){if(!getCapabilities().hyperlinks)return styledText;let absolutePath=resolvePath(rawPath,cwd);return hyperlink(styledText,pathToFileURL(absolutePath).href)}function str(value){return typeof value=="string"?value:value==null?"":null}function parseLineNumber(value){return typeof value=="string"&&value.trim()!==""&&(value=Number(value)),typeof value=="number"&&Number.isFinite(value)?value:void 0}function formatReadLineRange(offset,limit){if(offset==null&&limit==null)return"";let start=offset==null?1:parseLineNumber(offset);if(start===void 0)return"";if(limit==null)return`:${start}`;let count=parseLineNumber(limit);if(count===void 0)return"";let end=start+count-1;return`:${start}${end?`-${end}`:""}`}function replaceTabs(text){return text.replace(/\t/g," ")}function normalizeDisplayText(text){return text.replace(/\r/g,"")}function getTextOutput(result,showImages){if(!result)return"";let textBlocks=result.content.filter(c=>c.type==="text"),imageBlocks=result.content.filter(c=>c.type==="image"),output=textBlocks.map(c=>sanitizeBinaryOutput(stripAnsi(c.text||"")).replace(/\r/g,"")).join(`
3
3
  `),caps=getCapabilities();if(imageBlocks.length>0&&(!caps.images||!showImages)){let imageIndicators=imageBlocks.map(img=>{let mimeType=img.mimeType??"image/unknown",dims=img.data&&img.mimeType?getImageDimensions(img.data,img.mimeType)??void 0:void 0;return imageFallback(mimeType,dims)}).join(`
4
4
  `);output=output?`${output}
5
5
  ${imageIndicators}`:imageIndicators}return output}var COLLAPSED_ARGS_CHARS=100;function formatToolCallWithArgs(title,args,theme,expanded){let header=theme.fg("toolTitle",theme.bold(title));if(args==null)return header;let entries=typeof args=="object"&&!Array.isArray(args)?Object.entries(args):[["args",args]];if(entries.length===0)return header;if(expanded){let lines=entries.map(([key,value])=>{let text=typeof value=="string"?value:JSON.stringify(value,null,2)??String(value);return` ${key}: ${replaceTabs(text).replace(/\r/g,"").split(`
@@ -30,7 +30,7 @@ Searches over deferred tool metadata with BM25 and exposes matching tools for th
30
30
 
31
31
  Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${TOOL_SEARCH_TOOL_NAME}\`) to search for the required tools. For MCP tool discovery, always use \`${TOOL_SEARCH_TOOL_NAME}\`.`;function createToolSearchToolDefinition(options={}){return{name:TOOL_SEARCH_TOOL_NAME,label:TOOL_SEARCH_TOOL_NAME,description:TOOL_SEARCH_DESCRIPTION,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:toolSearchSchema,exposure:"model-only",reachesTools:()=>"all",async execute(_toolCallId,{query,limit}){if(query.trim()==="")throw new Error("query must not be empty");let max=limit??DEFAULT_TOOL_SEARCH_LIMIT;if(!Number.isInteger(max)||max<=0)throw new Error("limit must be a positive integer");let tools=options.tools?searchAndLoad(options.tools,query,max):[];return{content:[{type:"text",text:tools.length===0?"No matching tools found.":`Loaded ${tools.length} tool${tools.length===1?"":"s"}. They are available from your next call:
32
32
  ${tools.map(tool=>`- ${tool.name}: ${tool.description.trim().split(/\r?\n/)[0]}`).join(`
33
- `)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join2}from"node:path";var SETTINGS_DEFAULTS={transport:"auto",sessionShareDestination:"auto",steeringMode:"one-at-a-time",followUpMode:"one-at-a-time",compaction:{enabled:!0,reserveTokens:16384,keepRecentTokens:2e4},branchSummary:{reserveTokens:16384,skipPrompt:!1},retry:{enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:DEFAULT_MAX_AGENT_RETRY_DELAY_MS,provider:{maxRetryDelayMs:6e4}},hideThinkingBlock:!1,showCacheMissNotices:!1,quietStartup:!1,defaultProjectTrust:"ask",collapseChangelog:!1,enableInstallTelemetry:!0,enableAnalytics:!1,enableSkillCommands:!0,terminal:{showImages:!0,imageWidthCells:60,clearOnShrink:!1,showTerminalProgress:!1},images:{autoResize:!0,blockImages:!1},doubleEscapeAction:"tree",treeFilterMode:"default",editorPaddingX:0,outputPad:1,autocompleteMaxVisible:5,markdown:{codeBlockIndent:" ",mermaid:"streaming"},warnings:{anthropicExtraUsage:!0},codemode:{mode:"on",inlineBudget:3e3},cacheWarming:"idle",tuiMode:"fullscreen",fullscreenExitOutput:"transcript",fullscreenScrollbar:"auto",fullscreenCopyOnSelect:!0,fullscreenWheelScrollLines:"auto"};function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-L2EEDV3L.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS2=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme,hidden,noun){return`${theme.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(2):cost.toPrecision(2)}`}function statusIcon(call,theme){switch(call.status){case"running":return theme.fg("warning","\u2026");case"ok":return theme.fg("success","\u2713");case"error":return theme.fg("error","\u2717");case"cancelled":return theme.fg("muted","\u2298")}}function formatCall(call,theme,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS2?`${call.args.slice(0,COLLAPSED_ARGS_CHARS2-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme)} ${theme.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme.fg("muted",args)}`),duration&&(line+=` ${theme.fg("dim",duration)}`),call.cost&&(line+=` ${theme.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
33
+ `)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join2}from"node:path";var SETTINGS_DEFAULTS={transport:"auto",sessionShareDestination:"auto",steeringMode:"one-at-a-time",followUpMode:"one-at-a-time",compaction:{enabled:!0,reserveTokens:16384,keepRecentTokens:2e4},branchSummary:{reserveTokens:16384,skipPrompt:!1},retry:{enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:DEFAULT_MAX_AGENT_RETRY_DELAY_MS,provider:{maxRetryDelayMs:6e4}},hideThinkingBlock:!1,showCacheMissNotices:!1,quietStartup:!1,defaultProjectTrust:"ask",collapseChangelog:!1,enableInstallTelemetry:!0,enableAnalytics:!1,enableSkillCommands:!0,terminal:{showImages:!0,imageWidthCells:60,clearOnShrink:!1,showTerminalProgress:!1},images:{autoResize:!0,blockImages:!1},doubleEscapeAction:"tree",treeFilterMode:"default",editorPaddingX:0,outputPad:1,autocompleteMaxVisible:5,markdown:{codeBlockIndent:" ",mermaid:"streaming"},warnings:{anthropicExtraUsage:!0},codemode:{mode:"on",inlineBudget:3e3},cacheWarming:"idle",tuiMode:"fullscreen",fullscreenExitOutput:"transcript",fullscreenScrollbar:"auto",fullscreenCopyOnSelect:!0,fullscreenWheelScrollLines:"auto"};function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-XDNPBEMU.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS2=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme,hidden,noun){return`${theme.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(2):cost.toPrecision(2)}`}function statusIcon(call,theme){switch(call.status){case"running":return theme.fg("warning","\u2026");case"ok":return theme.fg("success","\u2713");case"error":return theme.fg("error","\u2717");case"cancelled":return theme.fg("muted","\u2298")}}function formatCall(call,theme,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS2?`${call.args.slice(0,COLLAPSED_ARGS_CHARS2-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme)} ${theme.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme.fg("muted",args)}`),duration&&(line+=` ${theme.fg("dim",duration)}`),call.cost&&(line+=` ${theme.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
34
34
  ${theme.fg("error",call.error.split(`
35
35
  `).join(`
36
36
  `))}`),line}var codemodeRenderers={renderCall(args,theme,context){startToolTimer(context);let code=str(args?.code),title=theme.fg("toolTitle",theme.bold("codemode")),component=context.lastComponent??new Container;if(component.clear(),code===null)return component.addChild(new Text(`${title} ${theme.fg("error","[invalid arg]")}`,0,0)),component;if(component.addChild(new Text(title,0,0)),code){let state=context.state;state.scriptHighlighter??=new CodeHighlighter;let highlighted=state.scriptHighlighter.highlight(replaceTabs(code.replace(/\r/g,"").trimEnd()),"javascript").join(`