@humain/humain-code 0.6.1 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/bundle/agent-monitor.js +1 -1
  3. package/dist/bundle/chunks/{anthropic-messages-FGFIMZUF.js → anthropic-messages-MNISFDZA.js} +2 -2
  4. package/dist/bundle/chunks/{azure-openai-responses-6JNTC7KO.js → azure-openai-responses-IV74M5OR.js} +3 -3
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +4 -5
  6. package/dist/bundle/chunks/{chunk-CVC2GV26.js → chunk-2HZ2V3HS.js} +610 -611
  7. package/dist/bundle/chunks/{chunk-IJYVMOB4.js → chunk-2PZ46FSM.js} +3 -3
  8. package/dist/bundle/chunks/{chunk-I6AQOITY.js → chunk-3LP543EX.js} +6 -6
  9. package/dist/bundle/chunks/{chunk-FDGW5ZTG.js → chunk-4J6BGNX2.js} +6 -6
  10. package/dist/bundle/chunks/{chunk-EDONIPUJ.js → chunk-4SQUP6IR.js} +7 -7
  11. package/dist/bundle/chunks/{chunk-P4P7OZ7R.js → chunk-5L4JG6PO.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-GICL5V54.js → chunk-6PD3T2EF.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-CFHOPLW5.js → chunk-75CQYZ63.js} +56 -54
  14. package/dist/bundle/chunks/{chunk-DHW3REC5.js → chunk-A2VPLMF2.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-AOH2O5CP.js → chunk-DCPACGLH.js} +575 -538
  16. package/dist/bundle/chunks/{chunk-M4CHQBAI.js → chunk-DLCBSLHW.js} +1 -1
  17. package/dist/bundle/chunks/chunk-F77J5EQZ.js +3 -0
  18. package/dist/bundle/chunks/{chunk-T3KDZFM4.js → chunk-FHLLDO7U.js} +7 -6
  19. package/dist/bundle/chunks/{chunk-AHSNQWZU.js → chunk-FLVBQ6GS.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-ONR6Q3II.js → chunk-JCTQQ3DX.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-YRUIJ5AH.js → chunk-JEAM6N22.js} +6 -5
  22. package/dist/bundle/chunks/{chunk-LDGCU6PD.js → chunk-K7SDY3VJ.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-IADQJFNH.js → chunk-KM4GQ2BU.js} +5 -4
  24. package/dist/bundle/chunks/{chunk-JFE52VSN.js → chunk-NCC2FAJN.js} +23 -22
  25. package/dist/bundle/chunks/{chunk-RO5YPAJH.js → chunk-PS2FJ7M4.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-HW6HMUXS.js → chunk-SFMDIVZ4.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-B7NJMF7B.js → chunk-WEFEQEIQ.js} +4 -4
  28. package/dist/bundle/chunks/{chunk-6DE7LJKV.js → chunk-WW4SILXG.js} +24 -19
  29. package/dist/bundle/chunks/{cli-BNCWK54K.js → cli-N7KOVPLB.js} +1 -1
  30. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-KI6W3USX.js → cloudflare-workers-ai-system-one-KRMHG2L3.js} +1 -1
  31. package/dist/bundle/chunks/codemode-worker.js +10 -4
  32. package/dist/bundle/chunks/{compat-I5VPOXFT.js → compat-MXAZPYDN.js} +9 -9
  33. package/dist/bundle/chunks/{dist-SKBR3C7C.js → dist-3V7ZSLER.js} +29 -26
  34. package/dist/bundle/chunks/dist-66CW64M2.js +8 -0
  35. package/dist/bundle/chunks/{easter-egg-3d-673VRP6Y.js → easter-egg-3d-O2GG2XIG.js} +1 -1
  36. package/dist/bundle/chunks/{execute-PIUR5MUV.js → execute-LMBACTKA.js} +28 -23
  37. package/dist/bundle/chunks/{extract-4O5Z5725.js → extract-CXXLVFC5.js} +7 -7
  38. package/dist/bundle/chunks/{google-generative-ai-635YZEHN.js → google-generative-ai-SBL77OXO.js} +4 -4
  39. package/dist/bundle/chunks/{google-vertex-I3ZJ3SB2.js → google-vertex-NZBNNXMK.js} +6 -6
  40. package/dist/bundle/chunks/{host-OQOEIWHK.js → host-SCZ4IKWR.js} +1 -1
  41. package/dist/bundle/chunks/{mistral-conversations-OKG5GKXR.js → mistral-conversations-DX4YKJSO.js} +14 -13
  42. package/dist/bundle/chunks/{openai-codex-responses-6JYZIFT4.js → openai-codex-responses-LZWBQYVP.js} +38 -37
  43. package/dist/bundle/chunks/{openai-completions-YBNI6CAP.js → openai-completions-7NWH423P.js} +2 -2
  44. package/dist/bundle/chunks/{openai-decisions-5G5YBFRQ.js → openai-decisions-ALJROWBE.js} +1 -1
  45. package/dist/bundle/chunks/{openai-responses-C3APJ6MK.js → openai-responses-5YOLHMCF.js} +3 -3
  46. package/dist/bundle/chunks/{pi-messages-UHYZYEOC.js → pi-messages-NHTQQOPW.js} +1 -1
  47. package/dist/bundle/chunks/{runtime-KE3HDSRT.js → runtime-UVPDE4CX.js} +1 -1
  48. package/dist/bundle/chunks/{typesafe-system-one-VYVAMWQV.js → typesafe-system-one-BHJYAZ6E.js} +1 -1
  49. package/dist/bundle/chunks/virtual-modules-YQPK57CW.js +23 -0
  50. package/dist/bundle/cli-runtime.js +3 -3
  51. package/dist/bundle/index.js +6 -6
  52. package/dist/bundle/rpc-entry.js +2 -2
  53. package/dist/coordination/adapter/commands-integration.d.ts +2 -2
  54. package/dist/coordination/adapter/commands-integration.d.ts.map +1 -1
  55. package/dist/coordination/adapter/commands-integration.js +14 -10
  56. package/dist/coordination/adapter/commands-integration.js.map +1 -1
  57. package/dist/coordination/adapter/delivery.d.ts +3 -0
  58. package/dist/coordination/adapter/delivery.d.ts.map +1 -1
  59. package/dist/coordination/adapter/delivery.js +4 -1
  60. package/dist/coordination/adapter/delivery.js.map +1 -1
  61. package/dist/coordination/adapter/index.d.ts.map +1 -1
  62. package/dist/coordination/adapter/index.js +26 -2
  63. package/dist/coordination/adapter/index.js.map +1 -1
  64. package/dist/coordination/adapter/integration-notices.d.ts +2 -2
  65. package/dist/coordination/adapter/integration-notices.d.ts.map +1 -1
  66. package/dist/coordination/adapter/integration-notices.js +5 -3
  67. package/dist/coordination/adapter/integration-notices.js.map +1 -1
  68. package/dist/coordination/adapter/integration-tool.d.ts +2 -1
  69. package/dist/coordination/adapter/integration-tool.d.ts.map +1 -1
  70. package/dist/coordination/adapter/integration-tool.js +11 -10
  71. package/dist/coordination/adapter/integration-tool.js.map +1 -1
  72. package/dist/coordination/adapter/peer-label.d.ts +5 -0
  73. package/dist/coordination/adapter/peer-label.d.ts.map +1 -0
  74. package/dist/coordination/adapter/peer-label.js +38 -0
  75. package/dist/coordination/adapter/peer-label.js.map +1 -0
  76. package/dist/coordination/adapter/render.d.ts +19 -0
  77. package/dist/coordination/adapter/render.d.ts.map +1 -0
  78. package/dist/coordination/adapter/render.js +107 -0
  79. package/dist/coordination/adapter/render.js.map +1 -0
  80. package/dist/coordination/adapter/tool.d.ts +12 -3
  81. package/dist/coordination/adapter/tool.d.ts.map +1 -1
  82. package/dist/coordination/adapter/tool.js +69 -32
  83. package/dist/coordination/adapter/tool.js.map +1 -1
  84. package/dist/coordination/broker/broker.d.ts +4 -1
  85. package/dist/coordination/broker/broker.d.ts.map +1 -1
  86. package/dist/coordination/broker/broker.js +146 -60
  87. package/dist/coordination/broker/broker.js.map +1 -1
  88. package/dist/coordination/client/client.d.ts.map +1 -1
  89. package/dist/coordination/client/client.js +10 -2
  90. package/dist/coordination/client/client.js.map +1 -1
  91. package/dist/coordination/transport/discovery.d.ts +4 -0
  92. package/dist/coordination/transport/discovery.d.ts.map +1 -1
  93. package/dist/coordination/transport/discovery.js +14 -0
  94. package/dist/coordination/transport/discovery.js.map +1 -1
  95. package/dist/coordination/transport/protocol.d.ts.map +1 -1
  96. package/dist/coordination/transport/protocol.js +3 -0
  97. package/dist/coordination/transport/protocol.js.map +1 -1
  98. package/dist/coordination/transport/types.d.ts +5 -1
  99. package/dist/coordination/transport/types.d.ts.map +1 -1
  100. package/dist/coordination/transport/types.js.map +1 -1
  101. package/dist/core/agent-session.d.ts.map +1 -1
  102. package/dist/core/agent-session.js +6 -2
  103. package/dist/core/agent-session.js.map +1 -1
  104. package/dist/core/bash-executor.d.ts.map +1 -1
  105. package/dist/core/bash-executor.js +13 -36
  106. package/dist/core/bash-executor.js.map +1 -1
  107. package/dist/core/bedrock-account-reporting.d.ts.map +1 -1
  108. package/dist/core/bedrock-account-reporting.js +2 -1
  109. package/dist/core/bedrock-account-reporting.js.map +1 -1
  110. package/dist/core/cache-warmer.d.ts.map +1 -1
  111. package/dist/core/cache-warmer.js +2 -2
  112. package/dist/core/cache-warmer.js.map +1 -1
  113. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  114. package/dist/core/compaction/branch-summarization.js +3 -2
  115. package/dist/core/compaction/branch-summarization.js.map +1 -1
  116. package/dist/core/compaction/compaction.d.ts.map +1 -1
  117. package/dist/core/compaction/compaction.js +2 -2
  118. package/dist/core/compaction/compaction.js.map +1 -1
  119. package/dist/core/extensions/runner.d.ts.map +1 -1
  120. package/dist/core/extensions/runner.js +2 -0
  121. package/dist/core/extensions/runner.js.map +1 -1
  122. package/dist/core/model-runtime.d.ts +2 -0
  123. package/dist/core/model-runtime.d.ts.map +1 -1
  124. package/dist/core/model-runtime.js +7 -7
  125. package/dist/core/model-runtime.js.map +1 -1
  126. package/dist/core/sdk.d.ts.map +1 -1
  127. package/dist/core/sdk.js +8 -0
  128. package/dist/core/sdk.js.map +1 -1
  129. package/dist/core/session-manager.d.ts +6 -0
  130. package/dist/core/session-manager.d.ts.map +1 -1
  131. package/dist/core/session-manager.js +27 -6
  132. package/dist/core/session-manager.js.map +1 -1
  133. package/dist/core/tools/bash.d.ts +2 -1
  134. package/dist/core/tools/bash.d.ts.map +1 -1
  135. package/dist/core/tools/bash.js +39 -3
  136. package/dist/core/tools/bash.js.map +1 -1
  137. package/dist/core/tools/index.d.ts +1 -1
  138. package/dist/core/tools/index.d.ts.map +1 -1
  139. package/dist/core/tools/index.js.map +1 -1
  140. package/dist/core/tools/output-accumulator.d.ts +5 -1
  141. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  142. package/dist/core/tools/output-accumulator.js +45 -16
  143. package/dist/core/tools/output-accumulator.js.map +1 -1
  144. package/dist/core/tools/render-utils.d.ts.map +1 -1
  145. package/dist/core/tools/render-utils.js +2 -2
  146. package/dist/core/tools/render-utils.js.map +1 -1
  147. package/dist/core/tools/renderers/write.js +2 -2
  148. package/dist/core/tools/renderers/write.js.map +1 -1
  149. package/dist/core/tools/subagent.d.ts +22 -0
  150. package/dist/core/tools/subagent.d.ts.map +1 -1
  151. package/dist/core/tools/subagent.js +46 -7
  152. package/dist/core/tools/subagent.js.map +1 -1
  153. package/dist/core/trace-client/credential-store.d.ts.map +1 -1
  154. package/dist/core/trace-client/credential-store.js +2 -0
  155. package/dist/core/trace-client/credential-store.js.map +1 -1
  156. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  157. package/dist/extensions/codemode/execute.js +3 -12
  158. package/dist/extensions/codemode/execute.js.map +1 -1
  159. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +10 -6
  160. package/dist/humain/gateway/secret-store.d.ts.map +1 -1
  161. package/dist/humain/gateway/secret-store.js +26 -12
  162. package/dist/humain/gateway/secret-store.js.map +1 -1
  163. package/dist/humain/gateway/session-store.d.ts +2 -2
  164. package/dist/humain/gateway/session-store.d.ts.map +1 -1
  165. package/dist/humain/gateway/session-store.js +13 -3
  166. package/dist/humain/gateway/session-store.js.map +1 -1
  167. package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
  168. package/dist/humain/web-access/vendor/extract.js +4 -2
  169. package/dist/humain/web-access/vendor/extract.js.map +1 -1
  170. package/dist/humain/web-access/vendor/page-query.d.ts.map +1 -1
  171. package/dist/humain/web-access/vendor/page-query.js +2 -1
  172. package/dist/humain/web-access/vendor/page-query.js.map +1 -1
  173. package/dist/humain/web-access/vendor/query-rewrite.d.ts.map +1 -1
  174. package/dist/humain/web-access/vendor/query-rewrite.js +2 -1
  175. package/dist/humain/web-access/vendor/query-rewrite.js.map +1 -1
  176. package/dist/humain/web-access/vendor/storage.d.ts +2 -0
  177. package/dist/humain/web-access/vendor/storage.d.ts.map +1 -1
  178. package/dist/humain/web-access/vendor/storage.js +71 -9
  179. package/dist/humain/web-access/vendor/storage.js.map +1 -1
  180. package/dist/humain/web-access/vendor/summary-review.d.ts.map +1 -1
  181. package/dist/humain/web-access/vendor/summary-review.js +2 -1
  182. package/dist/humain/web-access/vendor/summary-review.js.map +1 -1
  183. package/dist/index.d.ts +1 -1
  184. package/dist/index.d.ts.map +1 -1
  185. package/dist/index.js.map +1 -1
  186. package/dist/main.d.ts.map +1 -1
  187. package/dist/main.js +3 -3
  188. package/dist/main.js.map +1 -1
  189. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  190. package/dist/modes/interactive/components/mermaid.js +71 -34
  191. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  192. package/dist/utils/child-process.d.ts.map +1 -1
  193. package/dist/utils/child-process.js +16 -0
  194. package/dist/utils/child-process.js.map +1 -1
  195. package/docs/coordination.md +6 -2
  196. package/docs/development.md +4 -0
  197. package/docs/extensions.md +2 -0
  198. package/docs/providers.md +12 -2
  199. package/examples/extensions/gondolin/index.ts +1 -1
  200. package/examples/extensions/ssh.ts +34 -5
  201. package/npm-shrinkwrap.json +2 -2
  202. package/package.json +1 -1
  203. package/src/coordination/UPSTREAM.md +17 -0
  204. package/src/humain/web-access/UPSTREAM.md +11 -0
  205. package/dist/bundle/chunks/chunk-L6Z6JKKC.js +0 -3
  206. package/dist/bundle/chunks/dist-TVRQXUY6.js +0 -8
  207. package/dist/bundle/chunks/virtual-modules-KDUZIB3W.js +0 -23
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
2
  var FifoQueue=class{incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(value){this.incoming.push(value)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},EventStream=class{queue=new FifoQueue;waiting=new FifoQueue;sink;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(isComplete,extractResult){this.isComplete=isComplete,this.extractResult=
3
3
  extractResult,this.finalResultPromise=new Promise(resolve=>{this.resolveFinalResult=resolve})}push(event){if(this.done)return;if(this.isComplete(event)&&(this.done=!0,this.resolveFinalResult(this.extractResult(event))),this.sink){this.sink(event);return}let waiter=this.waiting.dequeue();waiter?waiter({value:event,done:!1}):this.queue.enqueue(event)}end(result){for(this.done=!0,result!==void 0&&this.resolveFinalResult(result);this.waiting.length>0;)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.
4
- asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let result=await new Promise(resolve=>this.waiting.enqueue(resolve));if(result.done)return;yield result.value}}}result(){return this.finalResultPromise}forwardTo(sink){for(;this.queue.length>0;)sink(this.queue.dequeue());this.sink=sink}},AssistantMessageEventStream=class extends EventStream{#startedAt=Date.now();#startedAtMonotonic=performance.now();constructor(){super(event=>event.type==="done"||
5
- event.type==="error",event=>{if(event.type==="done")return event.message;if(event.type==="error")return event.error;throw new Error("Unexpected event type for final result")})}push(event){event.type==="done"?this.#time(event.message):event.type==="error"&&this.#time(event.error),super.push(event)}end(result){result!==void 0&&this.#time(result),super.end(result)}#time(message){this.done||message.durationMs!==void 0||message.timestamp<this.#startedAt||(message.durationMs=Math.max(0,Math.round(performance.
6
- now()-this.#startedAtMonotonic)))}};function createAssistantMessageEventStream(){return new AssistantMessageEventStream}export{EventStream,AssistantMessageEventStream,createAssistantMessageEventStream};
4
+ asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let result=await new Promise(resolve=>this.waiting.enqueue(resolve));if(result.done)return;yield result.value}}}result(){return this.finalResultPromise}forwardTo(sink){for(;this.queue.length>0;)sink(this.queue.dequeue());this.sink=sink}};async function drainStream(stream){if(stream[Symbol.asyncIterator]===EventStream.prototype[Symbol.asyncIterator])stream.forwardTo(()=>{});else for await(let _event of stream)
5
+ ;return stream.result()}var AssistantMessageEventStream=class extends EventStream{#startedAt=Date.now();#startedAtMonotonic=performance.now();constructor(){super(event=>event.type==="done"||event.type==="error",event=>{if(event.type==="done")return event.message;if(event.type==="error")return event.error;throw new Error("Unexpected event type for final result")})}push(event){event.type==="done"?this.#time(event.message):event.type==="error"&&this.#time(event.error),super.push(event)}end(result){
6
+ result!==void 0&&this.#time(result),super.end(result)}#time(message){this.done||message.durationMs!==void 0||message.timestamp<this.#startedAt||(message.durationMs=Math.max(0,Math.round(performance.now()-this.#startedAtMonotonic)))}};function createAssistantMessageEventStream(){return new AssistantMessageEventStream}export{EventStream,drainStream,AssistantMessageEventStream,createAssistantMessageEventStream};
@@ -1,5 +1,5 @@
1
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-T3KDZFM4.js";import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{ToolCallArgumentsStream}from"./chunk-NN53K2QQ.js";import{calculateCost,resolveTranscript,resolveTranscriptTools}from"./chunk-EDONIPUJ.js";
2
+ import{shortHash}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta,closeGrammarToolInputJson,getGrammarToolInput,getJsonSchemaToolParameters,prepareJsonSchemaTool,resolveGrammarConstrainedSampling,transformMessages}from"./chunk-FHLLDO7U.js";import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{ToolCallArgumentsStream}from"./chunk-NN53K2QQ.js";import{calculateCost,resolveTranscript,resolveTranscriptTools}from"./chunk-4SQUP6IR.js";
3
3
  import{getSystemMessageText,renderSystemMessageUpdate,reportContentProgress}from"./chunk-XMZGB3H4.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.
4
4
  filter(c=>c.type==="text").map(c=>c.text).join(`
5
5
  `),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){
@@ -20,11 +20,11 @@ ser",content})}else if(msg.role==="assistant"){let output=[],assistantMsg=msg,is
20
20
  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)),
21
21
  ...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===
22
22
  "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?.
23
- 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(
24
- 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,reasoningProgressById=new Map,
25
- 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:"\
26
- 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.
27
- 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.
23
+ 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 prepared=prepareJsonSchemaTool(tool,supportsStrictMode),
24
+ strict=prepared.strict??defaultStrict,functionTool={type:"function",name:tool.name,description:tool.description,parameters:prepared.strict===!0?prepared.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,
25
+ reasoningProgressById=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.
26
+ 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}),
27
+ 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.
28
28
  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.
29
29
  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||
30
30
  (block.thinkingSignature=JSON.stringify({...storedItem,encrypted_content:item.encrypted_content}),item.encrypted_content!==reasoningProgressById.get(item.id)&&(reasoningProgressById.set(item.id,item.encrypted_content),reportContentProgress(options?.signal)))}},finalizeResponse=response=>{if(sawTerminalResponseEvent=!0,backfillReasoningSignatures(response.output??[]),response?.id&&(output.responseId=response.id),response?.usage){let inputDetails=response.usage.input_tokens_details,cachedTokens=inputDetails?.
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{retryProviderRequest}from"./chunk-BQ3TMEWD.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-T3KDZFM4.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-EDONIPUJ.js";import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=
2
+ import{retryProviderRequest}from"./chunk-BQ3TMEWD.js";import{prepareJsonSchemaTool,transformMessages}from"./chunk-FHLLDO7U.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-4SQUP6IR.js";import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=
3
3
  null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;
4
4
  var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2.
5
5
  _timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){
@@ -1994,8 +1994,8 @@ isSameProviderAndModel,block.thoughtSignature),part={functionCall:{name:block.na
1994
1994
  name:msg.toolName,response:msg.isError?{error:responseValue}:{output:responseValue},...hasImages&&modelSupportsMultimodalFunctionResponse&&{parts:imageParts},...includeId?{id:msg.toolCallId}:{}}},lastContent=contents[contents.length-1];lastContent?.role==="user"&&lastContent.parts?.some(p=>p.functionResponse)?lastContent.parts.push(functionResponsePart):contents.push({role:"user",parts:[functionResponsePart]}),hasImages&&!modelSupportsMultimodalFunctionResponse&&contents.push({role:"user",parts:[
1995
1995
  {text:"Tool result image:"},...imageParts]})}return contents}var JSON_SCHEMA_META_DECLARATIONS=new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function sanitizeForOpenApi(schema){if(typeof schema!="object"||schema===null||Array.isArray(schema))return schema;let result={};for(let[key,value]of Object.entries(schema))JSON_SCHEMA_META_DECLARATIONS.has(key)||(result[key]=sanitizeForOpenApi(value));return result}var JSON_SCHEMA_NAME_MAPS=new Set(["p\
1996
1996
  roperties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]),JSON_SCHEMA_SUBSCHEMAS=new Set(["additionalProperties","unevaluatedProperties","propertyNames","items","prefixItems","additionalItems","unevaluatedItems","contains","allOf","anyOf","oneOf","not","if","then","else","contentSchema"]);function rewriteConstAsEnum(schema,isNameMap=!1){if(Array.isArray(schema))return schema.map(item=>rewriteConstAsEnum(item));if(typeof schema!="object"||schema===null)return schema;
1997
- let result=Object.fromEntries(Object.entries(schema).map(([key,value])=>isNameMap||JSON_SCHEMA_SUBSCHEMAS.has(key)?[key,rewriteConstAsEnum(value)]:JSON_SCHEMA_NAME_MAPS.has(key)?[key,rewriteConstAsEnum(value,!0)]:[key,value]));if(!isNameMap&&"const"in result&&result.enum===void 0){let value=result.const;(typeof value=="string"||typeof value=="number")&&(delete result.const,result.enum=[value])}return result}function convertTools(tools,useParameters=!1,supportsStrictMode=!0){if(tools.length!==0)return[
1998
- {functionDeclarations:tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode),parameters=getJsonSchemaToolParameters(tool,strict);return{name:tool.name,description:tool.description,...useParameters?{parameters:sanitizeForOpenApi(parameters)}:{parametersJsonSchema:rewriteConstAsEnum(parameters)}}})}]}function supportsGoogleStrictToolSampling(modelId){let majorVersion=getGeminiMajorVersion(modelId);return majorVersion!==void 0&&majorVersion>=3}function mapToolChoice(choice){
1999
- switch(choice){case"auto":return FunctionCallingConfigMode.AUTO;case"none":return FunctionCallingConfigMode.NONE;case"any":return FunctionCallingConfigMode.ANY;default:return FunctionCallingConfigMode.AUTO}}function resolveGoogleFunctionCallingMode(tools,toolChoice,supportsStrictMode){let useStrictMode=tools.some(tool=>resolveJsonSchemaStrictSampling(tool,supportsStrictMode)===!0);return toolChoice==="none"||toolChoice==="any"?mapToolChoice(toolChoice):useStrictMode?FunctionCallingConfigMode.VALIDATED:
2000
- toolChoice?mapToolChoice(toolChoice):void 0}function mapStopReason(reason){switch(reason){case FinishReason.STOP:return"stop";case FinishReason.MAX_TOKENS:case FinishReason.CONTINUATION:return"length";case FinishReason.BLOCKLIST:case FinishReason.PROHIBITED_CONTENT:case FinishReason.SPII:case FinishReason.SAFETY:case FinishReason.IMAGE_SAFETY:case FinishReason.IMAGE_PROHIBITED_CONTENT:case FinishReason.IMAGE_RECITATION:case FinishReason.IMAGE_OTHER:case FinishReason.RECITATION:case FinishReason.
2001
- FINISH_REASON_UNSPECIFIED:case FinishReason.OTHER:case FinishReason.LANGUAGE:case FinishReason.MALFORMED_FUNCTION_CALL:case FinishReason.UNEXPECTED_TOOL_CALL:case FinishReason.TOO_MANY_TOOL_CALLS:case FinishReason.NO_IMAGE:case FinishReason.MALFORMED_RESPONSE:return"error";default:{let _exhaustive=reason;throw new Error(`Unhandled stop reason: ${_exhaustive}`)}}}function retryGoogleRequest(request,options){return retryProviderRequest(async()=>{try{return await request()}catch(error){throw error instanceof Error&&"status"in error&&!("headers"in error)&&(error.headers=void 0),error}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal})}export{ResourceScope,GoogleGenAI2 as GoogleGenAI,resolveGoogleThinkingLevel,usesGoogleThinkingLevel,toGoogleThinkingLevel,toGoogleSdkThinkingLevel,getDisabledGoogleThinkingConfig,isThinkingPart,retainThoughtSignature,convertMessages,convertTools,supportsGoogleStrictToolSampling,resolveGoogleFunctionCallingMode,mapStopReason,retryGoogleRequest};
1997
+ let result=Object.fromEntries(Object.entries(schema).map(([key,value])=>isNameMap||JSON_SCHEMA_SUBSCHEMAS.has(key)?[key,rewriteConstAsEnum(value)]:JSON_SCHEMA_NAME_MAPS.has(key)?[key,rewriteConstAsEnum(value,!0)]:[key,value]));if(!isNameMap&&"const"in result&&result.enum===void 0){let value=result.const;(typeof value=="string"||typeof value=="number")&&(delete result.const,result.enum=[value])}return result}function convertTools(tools,useParameters=!1,supportsStrictMode=!0){let hasStrictTools=!1,
1998
+ functionDeclarations=tools.map(tool=>{let{strict,parameters}=prepareJsonSchemaTool(tool,supportsStrictMode);return strict===!0&&(hasStrictTools=!0),{name:tool.name,description:tool.description,...useParameters?{parameters:sanitizeForOpenApi(parameters)}:{parametersJsonSchema:rewriteConstAsEnum(parameters)}}});return{tools:tools.length>0?[{functionDeclarations}]:void 0,hasStrictTools}}function supportsGoogleStrictToolSampling(modelId){let majorVersion=getGeminiMajorVersion(modelId);return majorVersion!==
1999
+ void 0&&majorVersion>=3}function mapToolChoice(choice){switch(choice){case"auto":return FunctionCallingConfigMode.AUTO;case"none":return FunctionCallingConfigMode.NONE;case"any":return FunctionCallingConfigMode.ANY;default:return FunctionCallingConfigMode.AUTO}}function resolveGoogleFunctionCallingMode(hasStrictTools,toolChoice){return toolChoice==="none"||toolChoice==="any"?mapToolChoice(toolChoice):hasStrictTools?FunctionCallingConfigMode.VALIDATED:toolChoice?mapToolChoice(toolChoice):void 0}function mapStopReason(reason){
2000
+ switch(reason){case FinishReason.STOP:return"stop";case FinishReason.MAX_TOKENS:case FinishReason.CONTINUATION:return"length";case FinishReason.BLOCKLIST:case FinishReason.PROHIBITED_CONTENT:case FinishReason.SPII:case FinishReason.SAFETY:case FinishReason.IMAGE_SAFETY:case FinishReason.IMAGE_PROHIBITED_CONTENT:case FinishReason.IMAGE_RECITATION:case FinishReason.IMAGE_OTHER:case FinishReason.RECITATION:case FinishReason.FINISH_REASON_UNSPECIFIED:case FinishReason.OTHER:case FinishReason.LANGUAGE:case FinishReason.
2001
+ MALFORMED_FUNCTION_CALL:case FinishReason.UNEXPECTED_TOOL_CALL:case FinishReason.TOO_MANY_TOOL_CALLS:case FinishReason.NO_IMAGE:case FinishReason.MALFORMED_RESPONSE:return"error";default:{let _exhaustive=reason;throw new Error(`Unhandled stop reason: ${_exhaustive}`)}}}function retryGoogleRequest(request,options){return retryProviderRequest(async()=>{try{return await request()}catch(error){throw error instanceof Error&&"status"in error&&!("headers"in error)&&(error.headers=void 0),error}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal})}export{ResourceScope,GoogleGenAI2 as GoogleGenAI,resolveGoogleThinkingLevel,usesGoogleThinkingLevel,toGoogleThinkingLevel,toGoogleSdkThinkingLevel,getDisabledGoogleThinkingConfig,isThinkingPart,retainThoughtSignature,convertMessages,convertTools,supportsGoogleStrictToolSampling,resolveGoogleFunctionCallingMode,mapStopReason,retryGoogleRequest};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{AssistantMessageEventStream,EventStream}from"./chunk-IJYVMOB4.js";import{contentText,createAssistantMessageDiagnostic,formatThrownValue,getOpenCodeSessionHeaders,getSystemMessageText,mergeClientIdentity,ownedSlice,streamProgress,streamProgressKey}from"./chunk-XMZGB3H4.js";import{__export}from"./chunk-JXWJOIH4.js";function abortReason(signal){if(signal.reason!==void 0)return signal.reason;let error=new Error("The operation was aborted");return error.name="AbortError",error}function operationSignal(signal){return signal??new AbortController().signal}function raceWithAbortSignal(operation,signal){return signal.aborted?(operation.catch(()=>{}),Promise.reject(abortReason(signal))):new Promise((resolve,reject)=>{let settled=!1,cleanup=()=>signal.removeEventListener("abort",onAbort),onAbort=()=>{settled||(settled=
2
+ import{AssistantMessageEventStream,EventStream,drainStream}from"./chunk-2PZ46FSM.js";import{contentText,createAssistantMessageDiagnostic,formatThrownValue,getOpenCodeSessionHeaders,getSystemMessageText,mergeClientIdentity,ownedSlice,streamProgress,streamProgressKey}from"./chunk-XMZGB3H4.js";import{__export}from"./chunk-JXWJOIH4.js";function abortReason(signal){if(signal.reason!==void 0)return signal.reason;let error=new Error("The operation was aborted");return error.name="AbortError",error}function operationSignal(signal){return signal??new AbortController().signal}function raceWithAbortSignal(operation,signal){return signal.aborted?(operation.catch(()=>{}),Promise.reject(abortReason(signal))):new Promise((resolve,reject)=>{let settled=!1,cleanup=()=>signal.removeEventListener("abort",onAbort),onAbort=()=>{settled||(settled=
3
3
  !0,cleanup(),reject(abortReason(signal)))};signal.addEventListener("abort",onAbort,{once:!0}),operation.then(value=>{settled||(settled=!0,cleanup(),resolve(value))},error=>{settled||(settled=!0,cleanup(),reject(error))}),signal.aborted&&onAbort()})}function createSetupErrorMessage(model2,error,timestamp){return{role:"assistant",content:[],api:model2.api,provider:model2.provider,model:model2.id,usage:{usageIncomplete:!0,input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:error instanceof Error?error.message:String(error),timestamp}}function hasResult(source){return typeof source.result=="function"}async function forwardStream(target,source,observer,observeResult){
4
4
  if(source instanceof EventStream&&source[Symbol.asyncIterator]===EventStream.prototype[Symbol.asyncIterator]){source.forwardTo(event=>{target.push(event),observer?.onEvent?.(event)});let forwardedResult=await source.result();target.end(forwardedResult),observeResult(forwardedResult);return}let result;for await(let event of source)target.push(event),observer?.onEvent?.(event),event.type==="done"?result=event.message:event.type==="error"&&(result=event.error);hasResult(source)&&(result=await source.
5
5
  result()),target.end(result),observeResult(result)}function lazyStream(model2,setup,observer){let startedAt=Date.now(),outer=new AssistantMessageEventStream,observedResult=!1,observeResult=result=>{observedResult||(observedResult=!0,observer?.onResult?.(result))};return setup().then(inner=>forwardStream(outer,inner,observer,observeResult)).catch(error=>{let message=createSetupErrorMessage(model2,error,startedAt),event={type:"error",reason:"error",error:message};outer.push(event),observer?.onEvent?.(
@@ -66,12 +66,12 @@ if(!method?.login)throw new ModelsError("auth",`${provider2.name} does not suppo
66
66
  new ModelsError("auth",`Credential store delete failed for ${providerId}`,{cause:error})}}requireProvider(model2){let provider2=this.providers.get(model2.provider);if(!provider2)throw new ModelsError("provider",`Unknown provider: ${model2.provider}`);return provider2}requireChatProvider(model2){return assertChatModel(model2),this.requireProvider(model2)}async applyAuth(model2,options){this.requireProvider(model2);let resolution=await this.getAuth(model2,{apiKey:options?.apiKey,env:options?.env,signal:options?.
67
67
  signal});if(options?.signal?.throwIfAborted(),!resolution)throw new ModelsError("auth",`Provider is not configured: ${model2.provider}`);let auth=resolution.auth,apiKey=options?.apiKey??auth.apiKey,requestModel=auth.baseUrl?{...model2,baseUrl:auth.baseUrl}:model2,sessionId=options&&"sessionId"in options&&typeof options.sessionId=="string"?options.sessionId:void 0,headers=mergeHeaders(mergeHeaders(getOpenCodeSessionHeaders(requestModel,sessionId),auth.headers),options?.headers);options?.transformHeaders&&
68
68
  (headers=await options.transformHeaders(headers??{}),options.signal?.throwIfAborted());let env=resolution.env||options?.env?{...resolution.env??{},...options?.env??{}}:void 0,identity=mergeClientIdentity(this.identity,options?.identity),{transformHeaders:_transformHeaders,...providerOptions}=options??{},requestOptions={...providerOptions,apiKey,headers,env,...identity===void 0?{}:{identity}};return{requestModel,requestOptions}}stream(model2,context,options){let transcript=normalizeContext(context);
69
- return streamWithProgressTimeout(model2,async signal=>{let provider2=this.requireChatProvider(model2),{requestModel,requestOptions}=await this.applyAuth(model2,{...options,signal});return signal.throwIfAborted(),provider2.stream(requestModel,transcript,requestOptions)},options,observeModelRequest(model2,options,!1))}async complete(model2,context,options){return this.stream(model2,context,options).result()}streamSimple(model2,context,options){let transcript=normalizeContext(context);return streamWithProgressTimeout(
70
- model2,async signal=>{let provider2=this.requireChatProvider(model2),{requestModel,requestOptions}=await this.applyAuth(model2,{...options,signal});return signal.throwIfAborted(),provider2.streamSimple(requestModel,transcript,requestOptions)},options,observeModelRequest(model2,options,!1))}async completeSimple(model2,context,options){return this.streamSimple(model2,context,options).result()}streamDeferred(model2,handle,options){return lazyStream(model2,async()=>{let provider2=this.requireChatProvider(
71
- model2);if(!provider2.fetchDeferred)throw new ModelsError("provider",`Provider ${model2.provider} does not support deferred responses`);let{requestModel,requestOptions}=await this.applyAuth(model2,options);return provider2.fetchDeferred(requestModel,handle,requestOptions)},observeModelRequest(model2,options,!0))}async fetchDeferred(model2,handle,options){return this.streamDeferred(model2,handle,options).result()}async cancelDeferred(model2,handle,options){let provider2=this.requireChatProvider(model2);
72
- if(!provider2.cancelDeferred)throw new ModelsError("provider",`Provider ${model2.provider} does not support deferred responses`);let{requestModel,requestOptions}=await this.applyAuth(model2,options);await provider2.cancelDeferred(requestModel,handle,requestOptions)}async generateImages(model2,context,options){try{assertImageModel(model2);let provider2=this.requireProvider(model2);if(!provider2.generateImages)throw new ModelsError("provider",`Provider ${model2.provider} does not support image gen\
73
- eration`);let{requestModel,requestOptions}=await this.applyAuth(model2,options);return await provider2.generateImages(requestModel,context,requestOptions)}catch(error){return imageErrorResult(model2,error,options?.signal?.aborted)}}async classify(model2,context,options){try{assertClassifierModel(model2),assertClassifierInputSupported(model2,context);let provider2=this.requireProvider(model2);if(!provider2.classify)throw new ModelsError("provider",`Provider ${model2.provider} does not support cla\
74
- ssification`);let{requestModel,requestOptions}=await this.applyAuth(model2,options);return await provider2.classify(requestModel,context,requestOptions)}catch(error){return classifierErrorResult(model2,error,options?.signal?.aborted)}}};async function commitLoginCredential(credentials,providerId,credential,signal){let mutationStarted=!1,markMutationStarted,started=new Promise(resolve=>{markMutationStarted=resolve}),mutation=credentials.modify(providerId,async()=>(mutationStarted=!0,markMutationStarted?.(),
69
+ return streamWithProgressTimeout(model2,async signal=>{let provider2=this.requireChatProvider(model2),{requestModel,requestOptions}=await this.applyAuth(model2,{...options,signal});return signal.throwIfAborted(),provider2.stream(requestModel,transcript,requestOptions)},options,observeModelRequest(model2,options,!1))}async complete(model2,context,options){return drainStream(this.stream(model2,context,options))}streamSimple(model2,context,options){let transcript=normalizeContext(context);return streamWithProgressTimeout(
70
+ model2,async signal=>{let provider2=this.requireChatProvider(model2),{requestModel,requestOptions}=await this.applyAuth(model2,{...options,signal});return signal.throwIfAborted(),provider2.streamSimple(requestModel,transcript,requestOptions)},options,observeModelRequest(model2,options,!1))}async completeSimple(model2,context,options){return drainStream(this.streamSimple(model2,context,options))}streamDeferred(model2,handle,options){return lazyStream(model2,async()=>{let provider2=this.requireChatProvider(
71
+ model2);if(!provider2.fetchDeferred)throw new ModelsError("provider",`Provider ${model2.provider} does not support deferred responses`);let{requestModel,requestOptions}=await this.applyAuth(model2,options);return provider2.fetchDeferred(requestModel,handle,requestOptions)},observeModelRequest(model2,options,!0))}async fetchDeferred(model2,handle,options){return drainStream(this.streamDeferred(model2,handle,options))}async cancelDeferred(model2,handle,options){let provider2=this.requireChatProvider(
72
+ model2);if(!provider2.cancelDeferred)throw new ModelsError("provider",`Provider ${model2.provider} does not support deferred responses`);let{requestModel,requestOptions}=await this.applyAuth(model2,options);await provider2.cancelDeferred(requestModel,handle,requestOptions)}async generateImages(model2,context,options){try{assertImageModel(model2);let provider2=this.requireProvider(model2);if(!provider2.generateImages)throw new ModelsError("provider",`Provider ${model2.provider} does not support i\
73
+ mage generation`);let{requestModel,requestOptions}=await this.applyAuth(model2,options);return await provider2.generateImages(requestModel,context,requestOptions)}catch(error){return imageErrorResult(model2,error,options?.signal?.aborted)}}async classify(model2,context,options){try{assertClassifierModel(model2),assertClassifierInputSupported(model2,context);let provider2=this.requireProvider(model2);if(!provider2.classify)throw new ModelsError("provider",`Provider ${model2.provider} does not sup\
74
+ port classification`);let{requestModel,requestOptions}=await this.applyAuth(model2,options);return await provider2.classify(requestModel,context,requestOptions)}catch(error){return classifierErrorResult(model2,error,options?.signal?.aborted)}}};async function commitLoginCredential(credentials,providerId,credential,signal){let mutationStarted=!1,markMutationStarted,started=new Promise(resolve=>{markMutationStarted=resolve}),mutation=credentials.modify(providerId,async()=>(mutationStarted=!0,markMutationStarted?.(),
75
75
  credential),{signal});mutation.catch(()=>{});try{await new Promise((resolve,reject)=>{let onAbort=()=>{mutationStarted||reject(signal.reason)};signal.addEventListener("abort",onAbort,{once:!0}),Promise.race([started,mutation]).then(()=>{signal.removeEventListener("abort",onAbort),resolve()},error=>{signal.removeEventListener("abort",onAbort),reject(error)}),signal.aborted&&onAbort()}),await mutation}catch(error){throw signal.throwIfAborted(),new ModelsError("auth",`Credential store modify failed\
76
76
  for ${providerId}`,{cause:error})}}function createModels(options){return new ModelsImpl(options)}function createProvider(input){let single=input.api&&typeof input.api.stream=="function"?input.api:void 0,byApi=single||!input.api?void 0:input.api,images=input.images,classifiers=input.classifiers,streams=single?[single]:Object.values(byApi??{}).filter(entry=>entry!==void 0),imageImplementations=Object.values(images??{}).filter(entry=>entry!==void 0),classifierImplementations=Object.values(classifiers??
77
77
  {}).filter(entry=>entry!==void 0);if(streams.length===0&&imageImplementations.length===0&&classifierImplementations.length===0)throw new Error(`Provider ${input.id}: at least one of "api", "images", or "classifiers" is required.`);let baselineModels=Object.getOwnPropertyDescriptor(input,"models")?.get?void 0:input.models,dynamicModels=[],fetchModels=input.fetchModels,currentModels=()=>{baselineModels??=input.models;let merged=[...baselineModels];for(let model2 of dynamicModels){let index=merged.
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{FileAuthStorageBackend,JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isObject,mcpNamespace,oauthErrorHtml,oauthSuccessHtml,require_proper_lockfile,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-6DE7LJKV.js";import{APP_TITLE,ENV_MCP_CLIENT_METADATA_URL,VERSION,getAgentDir}from"./chunk-IADQJFNH.js";import{__toESM}from"./chunk-JXWJOIH4.js";import{homedir}from"node:os";import{basename,join as join2,resolve}from"node:path";import{setTimeout as sleep}from"node:timers/promises";import{pathToFileURL}from"node:url";import{createServer}from"node:http";var ALLOWED_ERROR_CODES=new Set(["invalid_request","invalid_client","invalid_grant","unauthorized_client","unsupported_grant_type","invalid_scope","access_denied","unsupported_response_type","server_error","temporarily_unavailable","invalid_token","insufficient_scope","authorization_pending","slow_down","expired_token","invalid_redirect_uri","invalid_client_metadata","invalid_software_statement","unapproved_software_statement"]);function isAllowedOAuthErrorCode(value){return ALLOWED_ERROR_CODES.
2
+ import{FileAuthStorageBackend,JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isObject,mcpNamespace,oauthErrorHtml,oauthSuccessHtml,require_proper_lockfile,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-WW4SILXG.js";import{APP_TITLE,ENV_MCP_CLIENT_METADATA_URL,VERSION,getAgentDir}from"./chunk-KM4GQ2BU.js";import{__toESM}from"./chunk-JXWJOIH4.js";import{homedir}from"node:os";import{basename,join as join2,resolve}from"node:path";import{setTimeout as sleep}from"node:timers/promises";import{pathToFileURL}from"node:url";import{createServer}from"node:http";var ALLOWED_ERROR_CODES=new Set(["invalid_request","invalid_client","invalid_grant","unauthorized_client","unsupported_grant_type","invalid_scope","access_denied","unsupported_response_type","server_error","temporarily_unavailable","invalid_token","insufficient_scope","authorization_pending","slow_down","expired_token","invalid_redirect_uri","invalid_client_metadata","invalid_software_statement","unapproved_software_statement"]);function isAllowedOAuthErrorCode(value){return ALLOWED_ERROR_CODES.
3
3
  has(value)}function sanitizeOAuthErrorCode(value,fallback="server_error"){return value&&ALLOWED_ERROR_CODES.has(value)?value:fallback}var OAuthError=class extends Error{code;errorUri;constructor(code,message,errorUri){super(message||code),this.name="OAuthError",this.code=code,this.errorUri=errorUri}},OAuthIssuerMismatchError=class extends Error{expected;received;constructor(expected,received){let format=issuer=>issuer===void 0?"none":JSON.stringify(issuer);super(`OAuth issuer mismatch: expected ${format(
4
4
  expected)}, received ${format(received)}`),this.name="OAuthIssuerMismatchError",this.expected=expected,this.received=received}},OAuthInsecureEndpointError=class extends Error{endpoint;constructor(endpoint){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`),this.name="OAuthInsecureEndpointError",this.endpoint=endpoint}},OAuthRedirectError=class extends Error{constructor(){super("OAuth endpoint redirected; refusing to follow the redirect"),this.name="OAuthRedirectError"}},
5
5
  OAuthRegistrationError=class extends Error{status;code;constructor(status,code){super(`OAuth dynamic client registration failed with status ${status}${code?`: ${code}`:""}`),this.name="OAuthRegistrationError",this.status=status,this.code=code}},McpOAuthAuthorizationRequiredError=class extends Error{constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}};function plainText(page){return page.ok?"Authorization complete. You may close this window.":page.details?`${page.message}
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{retryProviderRequest}from"./chunk-BQ3TMEWD.js";import{createRequestObserver,headersToRecord,providerHeadersToRecord}from"./chunk-5JSLXC2A.js";import{calculateCost}from"./chunk-EDONIPUJ.js";import{getIdentityHeaders}from"./chunk-XMZGB3H4.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){
2
+ import{retryProviderRequest}from"./chunk-BQ3TMEWD.js";import{createRequestObserver,headersToRecord,providerHeadersToRecord}from"./chunk-5JSLXC2A.js";import{calculateCost}from"./chunk-4SQUP6IR.js";import{getIdentityHeaders}from"./chunk-XMZGB3H4.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){
3
3
  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.
4
4
  provider}`);let apiKey=options.apiKey,payload=body,transformed=await options.onPayload?.(payload,model);transformed!==void 0&&(payload=transformed);let requestFetch=options.fetch??globalThis.fetch,observe=createRequestObserver(options,{api:model.api,provider:model.provider,model:model.id,operation:"classifier"}),{response,json}=await retryProviderRequest(async()=>{let timeoutSignal=options.timeoutMs!==void 0?AbortSignal.timeout(options.timeoutMs):void 0,signal=options.signal&&timeoutSignal?AbortSignal.
5
5
  any([options.signal,timeoutSignal]):options.signal??timeoutSignal;try{let requestBody=JSON.stringify(payload);await observe(requestBody);let next=await requestFetch(url,{method:"POST",headers:requestHeaders(model,apiKey,options.headers,options.identity),body:requestBody,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.
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{source_default}from"./chunk-XQRYOCHA.js";import{require_core}from"./chunk-DNGJMRJW.js";import{getCustomThemesDir,getThemesDir,stripBom}from"./chunk-IADQJFNH.js";import{__export,__toESM}from"./chunk-JXWJOIH4.js";var ambiguousRanges=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,
2
+ import{source_default}from"./chunk-XQRYOCHA.js";import{require_core}from"./chunk-DNGJMRJW.js";import{getCustomThemesDir,getThemesDir,stripBom}from"./chunk-KM4GQ2BU.js";import{__export,__toESM}from"./chunk-JXWJOIH4.js";var ambiguousRanges=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,
3
3
  1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,
4
4
  8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,
5
5
  9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],fullwidthMinimalCodePoint=12288,fullwidthMaximumCodePoint=65510,fullwidthRanges=[12288,12288,65281,65376,65504,65510];var wideMinimalCodePoint=4352,wideMaximumCodePoint=262141,wideRanges=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,
@@ -732,11 +732,12 @@ b.italic&&a3.strikethrough===b.strikethrough&&a3.underline===b.underline&&a3.pre
732
732
  "\r")&&source2[previous.source.length]===`
733
733
  `?1:0):0,tail=source2.slice(start).replace(/\r\n|\r/g,`
734
734
  `).replace(/\t/g," "),added=grows?ownString(tail):tail,input={source:source2,text:grows?previous.text+added:added},from=grows?previous.lexed?.deref():void 0;return{input,...from?{extended:{from,added}}:{}}}function codeSourceTail(tokens,shared,source2){if(shared===0)return source2;let length=0;for(let index=shared;index<tokens.length;index++)length+=tokens[index].raw.length;let start=source2.length;for(;length>0&&start>0;)start--,length-=source2[start]===" "?3:1,source2[start]===`
735
- `&&source2[start-1]==="\r"&&start--;return ownString(source2.slice(start))}function normalizedCodeSource(source2){let offsets=[];for(let original=0;original<source2.length;original++){for(let count=source2[original]===" "?3:1;count>0;count--)offsets.push(original);source2[original]==="\r"&&source2[original+1]===`
735
+ `&&source2[start-1]==="\r"&&start--;return ownString(source2.slice(start))}function normalizedCodeSource(source2){if(!/\t|\r\n/.test(source2))return{text:source2.replace(/\r/g,`
736
+ `)};let offsets=[];for(let original=0;original<source2.length;original++){for(let count=source2[original]===" "?3:1;count>0;count--)offsets.push(original);source2[original]==="\r"&&source2[original+1]===`
736
737
  `&&original++}return offsets.push(source2.length),{text:source2.replace(/\r\n|\r/g,`
737
- `).replace(/\t/g," "),offsets}}function stripCodeContainerPrefixes(source2,prefixes){let{text,offsets}=normalizedCodeSource(source2),result="",cursor=0;for(let match of text.matchAll(prefixes)){let end=match.index+match[0].length,remaining=0;if(offsets[end]===offsets[end-1])for(;offsets[end+remaining]===offsets[end];)remaining++;result+=source2.slice(cursor,offsets[match.index])+" ".repeat(remaining),cursor=offsets[end+remaining]}return result+source2.slice(cursor)}function fencedCodeTokens(tokens){
738
- let blocks=[];for(let token of tokens)if(token.type==="code"&&token.codeBlockStyle!=="indented")blocks.push(token);else if(token.type==="blockquote")blocks.push(...fencedCodeTokens(token.tokens??[]));else if(token.type==="list")for(let item of token.items)blocks.push(...fencedCodeTokens(item.tokens));return blocks}function fencedCodeContents(raw){let opening=/^ {0,3}(`{3,}|~{3,})[^\r\n]*(?:\r\n|\n|\r|$)/.exec(raw);if(!opening)return;let body=raw.slice(opening[0].length),fence=opening[1],closing=new RegExp(
739
- `^ {0,3}${fence[0]}{${fence.length},}[ \\t]*(?:\\r\\n|\\n|\\r|$)`,"m").exec(body);return{text:closing?body.slice(0,closing.index):body,fence}}var Markdown=class{text;rawText;sanitized;grown;facts;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;codeComponents=new WeakMap;codeSources=new WeakMap;lastRenderWidth=80;codeSourceText;codeOriginalText;codeSourceTransformed=!1;codeSourceTokens;codeInput;originalCodeInput;originalCodeSources=new WeakMap;codeOriginalSources=new WeakMap;codeBlockRevision=0;cachedText;cachedWidth;cachedLines;cachedTokens;blocks;blockHighlightedCode;wraps;nextWraps;paddedLines=new Map;nextPaddedLines=new Map;paddingGeneration=-1;paddingBackground;live={
738
+ `).replace(/\t/g," "),offsets}}function stripCodeContainerPrefixes(source2,prefixes){let{text,offsets}=normalizedCodeSource(source2),result="",cursor=0;for(let match of text.matchAll(prefixes)){let end=match.index+match[0].length,remaining=0;if(offsets&&offsets[end]===offsets[end-1])for(;offsets[end+remaining]===offsets[end];)remaining++;result+=source2.slice(cursor,offsets?.[match.index]??match.index)+" ".repeat(remaining),cursor=offsets?.[end+remaining]??end+remaining}return result+source2.slice(
739
+ cursor)}function fencedCodeTokens(tokens){let blocks=[];for(let token of tokens)if(token.type==="code"&&token.codeBlockStyle!=="indented")blocks.push(token);else if(token.type==="blockquote")blocks.push(...fencedCodeTokens(token.tokens??[]));else if(token.type==="list")for(let item of token.items)blocks.push(...fencedCodeTokens(item.tokens));return blocks}function fencedCodeContents(raw){let opening=/^ {0,3}(`{3,}|~{3,})[^\r\n]*(?:\r\n|\n|\r|$)/.exec(raw);if(!opening)return;let body=raw.slice(opening[0].
740
+ length),fence=opening[1],closing=new RegExp(`^ {0,3}${fence[0]}{${fence.length},}[ \\t]*(?:\\r\\n|\\n|\\r|$)`,"m").exec(body);return{text:closing?body.slice(0,closing.index):body,fence}}var Markdown=class{text;rawText;sanitized;grown;facts;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;codeComponents=new WeakMap;codeSources=new WeakMap;lastRenderWidth=80;codeSourceText;codeOriginalText;codeSourceTransformed=!1;codeSourceTokens;codeInput;originalCodeInput;originalCodeSources=new WeakMap;codeOriginalSources=new WeakMap;codeBlockRevision=0;cachedText;cachedWidth;cachedLines;cachedTokens;blocks;blockHighlightedCode;wraps;nextWraps;paddedLines=new Map;nextPaddedLines=new Map;paddingGeneration=-1;paddingBackground;live={
740
741
  array:new LiveLineArray,ends:[],substituted:!1};constructor(text,paddingX,paddingY,theme2,defaultTextStyle,options){this.text=sanitizeTerminalText(text),options?.renderCodeBlock&&(this.rawText=text),this.paddingX=paddingX,this.paddingY=paddingY,this.theme=theme2,this.defaultTextStyle=defaultTextStyle,this.options=options?{...options}:{}}setText(text){this.options.renderCodeBlock&&(this.rawText=text);let before=this.text;this.sanitized=sanitizeTerminalTextFrom(text,this.sanitized),this.text=this.
741
742
  sanitized.text;let added=this.sanitized.added;this.grown!==void 0&&(added===void 0?this.grown=void 0:this.grown.added+=added);let facts=this.facts;this.facts=facts!==void 0&&added!==void 0&&facts.text===before?{text:this.text,visible:facts.visible||/\S/.test(added),tabs:facts.tabs||added.includes(" ")}:void 0,this.clearRenderCache()}invalidate(){this.clearRenderCache(),this.blocks=void 0,this.defaultStylePrefix=void 0,invalidateRenderedMarkdown()}clearRenderCache(){this.cachedText=void 0,this.cachedWidth=
742
743
  void 0,this.cachedLines=void 0,reportRenderChange(this)}renderSettings(width){let style=this.defaultTextStyle;return{generation:renderedMarkdownGeneration(),width,paddingX:this.options.renderCodeBlock?Math.min(this.paddingX,Math.max(0,Math.floor((width-1)/2))):this.paddingX,theme:this.theme,color:style?.color,bgColor:style?.bgColor,bold:style?.bold,italic:style?.italic,strikethrough:style?.strikethrough,underline:style?.underline,preserveOrderedListMarkers:this.options.preserveOrderedListMarkers,
@@ -757,10 +758,10 @@ normalized2.input;let originalFrom=lexedFrom.get(originalTokens),originalShared=
757
758
  originalCodeSources,used=new Set,matched=new Map;for(let block of renderedBlocks2){let candidates=originals===renderedBlocks2?[block]:originals.filter(candidate=>!used.has(candidate)&&sanitizeTerminalText(candidate.lang??"")===(block.lang??"")&&sanitizeTerminalText(candidate.text)===block.text),original=candidates[0];original&&candidates.every(candidate=>sourceMap.get(candidate)===sourceMap.get(original))&&(used.add(original),matched.set(block,original))}let unmatched=originals.filter(original=>!used.
758
759
  has(original));for(let[index,block]of renderedBlocks2.entries()){let original=matched.get(block)??(unmatched.length===1&&originals.length===renderedBlocks2.length&&unmatched[0]?.lang===block.lang?unmatched[0]:void 0),source2=appended&&block!==growingBlock&&this.codeOriginalSources.has(block)?this.codeOriginalSources.get(block):original?sourceMap.get(original):void 0,previous=previousBlocks[index];if((this.codeOriginalSources.has(block)&&this.codeOriginalSources.get(block)!==source2||previous?.raw===
759
760
  block.raw&&(this.codeOriginalSources.get(previous)!==source2||this.codeSources.get(previous)!==this.codeSources.get(block)))&&(this.codeComponents.delete(block),this.codeBlockRevision++),!this.codeComponents.has(block)&&previous&&this.codeOriginalSources.get(previous)===source2&&this.codeSources.get(previous)===this.codeSources.get(block)&&sameTokens(previous,block)){let component=this.codeComponents.get(previous);component&&this.codeComponents.set(block,component)}this.codeOriginalSources.set(block,
760
- source2)}this.codeSourceText=text,this.codeOriginalText=originalText,this.codeSourceTransformed=transformed,this.codeSourceTokens=new WeakRef(tokens)}return{tokens,contentWidth}}rememberCodeSources(tokens,source2,sources=this.codeSources){let{text:normalized,offsets}=normalizedCodeSource(source2),cursor=0;for(let token of tokens){let start=normalized.indexOf(token.raw,cursor),raw=start<0?token.raw:source2.slice(offsets[start],offsets[start+token.raw.length]);if(start>=0&&(cursor=start+token.raw.
761
- length),token.type==="code")sources===this.codeSources&&sources.has(token)&&sources.get(token)!==raw&&(this.codeComponents.delete(token),this.codeBlockRevision++),start>=0?sources.set(token,raw):sources.delete(token);else if(token.type==="blockquote")this.rememberCodeSources(token.tokens??[],stripCodeContainerPrefixes(raw,/^ {0,3}> ?/gm),sources);else if(token.type==="list"){let listSource=normalizedCodeSource(raw),itemCursor=0;for(let item of token.items){let marker=/^( {0,3}(?:[-+*]|\d+[.)])[ \t]+)/.
762
- exec(item.raw)?.[0]??"",itemStart=listSource.text.indexOf(item.raw,itemCursor),itemSource=itemStart<0?item.raw:raw.slice(listSource.offsets[itemStart],listSource.offsets[itemStart+item.raw.length]);itemStart>=0&&(itemCursor=itemStart+item.raw.length);let unindented=stripCodeContainerPrefixes(itemSource,new RegExp(`^ {0,3}(?:[-+*]|\\d+[.)]) +|(?<=\\n) {1,${Math.max(1,marker.length)}}`,"g"));this.rememberCodeSources(item.tokens,unindented,sources)}}}}codeComponent(token){if(!this.options.renderCodeBlock||
763
- token.codeBlockStyle==="indented")return;let component=this.codeComponents.get(token);if(component)return component;let raw=this.codeSources.get(token)??token.raw,contents=fencedCodeContents(raw);if(!contents)return;let{text,fence}=contents,original=fencedCodeContents(this.codeOriginalSources.get(token)??raw),lastLine=text.slice(text.lastIndexOf(`
761
+ source2)}this.codeSourceText=text,this.codeOriginalText=originalText,this.codeSourceTransformed=transformed,this.codeSourceTokens=new WeakRef(tokens)}return{tokens,contentWidth}}rememberCodeSources(tokens,source2,sources=this.codeSources){let{text:normalized,offsets}=normalizedCodeSource(source2),cursor=0;for(let token of tokens){let start=normalized.indexOf(token.raw,cursor),raw=start<0?token.raw:source2.slice(offsets?.[start]??start,offsets?.[start+token.raw.length]??start+token.raw.length);if(start>=
762
+ 0&&(cursor=start+token.raw.length),token.type==="code")sources===this.codeSources&&sources.has(token)&&sources.get(token)!==raw&&(this.codeComponents.delete(token),this.codeBlockRevision++),start>=0?sources.set(token,raw):sources.delete(token);else if(token.type==="blockquote")this.rememberCodeSources(token.tokens??[],stripCodeContainerPrefixes(raw,/^ {0,3}> ?/gm),sources);else if(token.type==="list"){let listSource=normalizedCodeSource(raw),itemCursor=0;for(let item of token.items){let marker=/^( {0,3}(?:[-+*]|\d+[.)])[ \t]+)/.
763
+ exec(item.raw)?.[0]??"",itemStart=listSource.text.indexOf(item.raw,itemCursor),itemSource=itemStart<0?item.raw:raw.slice(listSource.offsets?.[itemStart]??itemStart,listSource.offsets?.[itemStart+item.raw.length]??itemStart+item.raw.length);itemStart>=0&&(itemCursor=itemStart+item.raw.length);let unindented=stripCodeContainerPrefixes(itemSource,new RegExp(`^ {0,3}(?:[-+*]|\\d+[.)]) +|(?<=\\n) {1,${Math.max(1,marker.length)}}`,"g"));this.rememberCodeSources(item.tokens,unindented,sources)}}}}codeComponent(token){
764
+ if(!this.options.renderCodeBlock||token.codeBlockStyle==="indented")return;let component=this.codeComponents.get(token);if(component)return component;let raw=this.codeSources.get(token)??token.raw,contents=fencedCodeContents(raw);if(!contents)return;let{text,fence}=contents,original=fencedCodeContents(this.codeOriginalSources.get(token)??raw),lastLine=text.slice(text.lastIndexOf(`
764
765
  `)+1),partialFence=this.options.complete===!1&&lastLine.length>0&&lastLine.length<fence.length&&lastLine===fence[0].repeat(lastLine.length),originalText=ownString(original?.text??text),displayText=partialFence?text.slice(0,-lastLine.length):text;return component=this.options.renderCodeBlock({wrapLine:(line,width)=>this.wrapLine(line,width),text:originalText,language:token.lang,displayText:displayText===originalText?void 0:ownString(displayText),copyUnavailable:this.codeOriginalSources.get(token)===
765
766
  void 0}),this.codeComponents.set(token,component),component}getCodeBlockComponents(){let prepared=this.tokensFor(this.lastRenderWidth);return prepared?fencedCodeTokens(prepared.tokens).flatMap(token=>{let component=this.codeComponent(token);return component?[component]:[]}):[]}handleMouse(event){if(!this.options.renderCodeBlock)return;let prepared=this.tokensFor(event.width);if(!prepared)return;let settings=this.renderSettings(event.width),y=this.paddingY;for(let index=0;index<prepared.tokens.length;index++){
766
767
  let lines=this.renderBlock(prepared.tokens[index],prepared.tokens[index+1]?.type,settings,prepared.contentWidth);for(let region of codeBlockRegions.get(lines)??[]){let localY=event.y-y-region.y,localX=event.x-region.x;if(localX>=0&&localX<region.width&&localY>=0&&localY<region.height)return dispatchMouseEvent(region.component,{...event,x:localX,y:localY,width:region.width,height:region.height})}y+=lines.length}}textFacts(){let text=this.text,facts=this.facts;return facts?.text!==text&&(facts={text,
@@ -868,13 +869,14 @@ destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeL
868
869
  l",(this.keyboardProtocolPushed||this._kittyProtocolActive)&&(sequence+="\x1B[<u"),this._modifyOtherKeysActive&&(sequence+="\x1B[>4;0m"),sequence+=after;try{fs.writeSync(process.stdout.fd,sequence)}catch{}}write(data){if(process.stdout.write(data),this.writeLogPath)try{fs.appendFileSync(this.writeLogPath,data,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(lines){lines>
869
870
  0?process.stdout.write(`\x1B[${lines}B`):lines<0&&process.stdout.write(`\x1B[${-lines}A`)}hideCursor(){process.stdout.write("\x1B[?25l")}showCursor(){process.stdout.write("\x1B[?25h")}clearLine(){process.stdout.write("\x1B[K")}clearFromCursor(){process.stdout.write("\x1B[J")}clearScreen(){process.stdout.write("\x1B[2J\x1B[H")}setTitle(title){process.stdout.write(`\x1B]0;${replaceControlCharacters(title)}\x07`)}setProgramStatus(status){this.programStatus=status.state==="clear"?void 0:status,this.
870
871
  programStatusSupported&&process.stdout.write(formatProgramStatus(status))}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus(this.programStatus))}setProgress(active){active?(process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){
871
- return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var PRINTABLE_ASCII=/^[\x20-\x7e]*$/;function buildSearchCorpus(lines){let chunks=[],spans=[],textLength=0,pendingSeparator=!1,appendSeparator=()=>{pendingSeparator&&(chunks.push(" "),textLength+=1,pendingSeparator=!1)};for(let row=0;row<lines.length;row++){let line=stripTerminalSequences(lines[row]??""),column=0;if(PRINTABLE_ASCII.test(line)){let index=0;for(;index<line.length;){if(line.charCodeAt(index)===32){textLength>0&&(pendingSeparator=!0),column+=1,index+=1;continue}let end=index+1;for(;end<
872
- line.length&&line.charCodeAt(end)!==32;)end+=1;appendSeparator();let text=line.slice(index,end);chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+text.length,linearColumns:!0}),textLength+=text.length,column+=text.length,index=end}}else for(let grapheme of getGraphemeSegmenter().segment(line)){let text=grapheme.segment,width=visibleWidth(text);if(/^\s+$/u.test(text)){textLength>0&&(pendingSeparator=!0),column+=width;continue}appendSeparator(),
873
- chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+width,linearColumns:!1}),textLength+=text.length,column+=width}textLength>0&&(pendingSeparator=!0)}return{text:chunks.join(""),spans}}function normalizeQuery(query){return query.replace(/\s+/gu," ").trim()}function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function findSearchCorpusMatches(corpus,normalizedQuery){if(!normalizedQuery)return[];let expression=new RegExp(
874
- escapeRegExp(normalizedQuery),"giu"),matches=[],spanIndex=0;for(let match of corpus.text.matchAll(expression)){let start=match.index,end=start+match[0].length;for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=start;)spanIndex+=1;let segments=[];for(let index=spanIndex;index<corpus.spans.length;index++){let span=corpus.spans[index];if(span.textStart>=end)break;if(span.textEnd<=start)continue;let startCol=span.linearColumns?span.startCol+Math.max(start,span.textStart)-span.textStart:
875
- span.startCol,endCol=span.linearColumns?span.startCol+Math.min(end,span.textEnd)-span.textStart:span.endCol,previous=segments[segments.length-1];previous&&previous.row===span.row&&startCol<=previous.endCol?previous.endCol=Math.max(previous.endCol,endCol):segments.push({row:span.row,startCol,endCol})}for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=end;)spanIndex+=1;segments.length>0&&matches.push({segments})}return matches}var AltScreenSearchIndex=class{sourceLines;corpus;normalizedQuery;matches=[];search(lines,query){
876
- let sourceChanged=this.sourceLines?.length!==lines.length;if(!sourceChanged&&this.sourceLines){for(let index=0;index<lines.length;index++)if(this.sourceLines[index]!==lines[index]){sourceChanged=!0;break}}(sourceChanged||!this.corpus)&&(this.sourceLines=Array.from(lines),this.corpus=buildSearchCorpus(lines));let normalizedQuery=normalizeQuery(query),changed=sourceChanged||normalizedQuery!==this.normalizedQuery;return changed&&(this.normalizedQuery=normalizedQuery,this.matches=findSearchCorpusMatches(
877
- this.corpus,normalizedQuery)),{matches:this.matches,changed}}};function getAltScreenSearchMatchKey(match){let first=match.segments[0],last=match.segments[match.segments.length-1];return first&&last?`${first.row}:${first.startCol}:${last.row}:${last.endCol}`:""}var AltScreenSearchComponent=class{input=new Input({prompt:" ",placeholder:"Find in transcript",placeholderStyle:text=>`\x1B[2m${text}\x1B[22m`});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(onQueryChange,navigationButtonStyle=text=>text){
872
+ return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var PRINTABLE_ASCII=/^[\x20-\x7e]*$/;function buildSearchCorpus(lines,corpus={text:"",spans:[],rowTextStarts:[],rowSpanStarts:[]},startRow=0){let textLength=corpus.rowTextStarts[startRow]??corpus.text.length,chunks=[corpus.text.slice(0,textLength)],spans=corpus.spans;spans.length=corpus.rowSpanStarts[startRow]??spans.length,corpus.rowTextStarts.length=startRow,corpus.rowSpanStarts.length=startRow;let pendingSeparator=textLength>0,appendSeparator=()=>{pendingSeparator&&(chunks.push(" "),textLength+=
873
+ 1,pendingSeparator=!1)};for(let row=startRow;row<lines.length;row++){corpus.rowTextStarts.push(textLength),corpus.rowSpanStarts.push(spans.length);let line=stripTerminalSequences(lines[row]??""),column=0;if(PRINTABLE_ASCII.test(line)){let index=0;for(;index<line.length;){if(line.charCodeAt(index)===32){textLength>0&&(pendingSeparator=!0),column+=1,index+=1;continue}let end=index+1;for(;end<line.length&&line.charCodeAt(end)!==32;)end+=1;appendSeparator();let text=line.slice(index,end);chunks.push(
874
+ text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+text.length,linearColumns:!0}),textLength+=text.length,column+=text.length,index=end}}else for(let grapheme of getGraphemeSegmenter().segment(line)){let text=grapheme.segment,width=visibleWidth(text);if(/^\s+$/u.test(text)){textLength>0&&(pendingSeparator=!0),column+=width;continue}appendSeparator(),chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,
875
+ endCol:column+width,linearColumns:!1}),textLength+=text.length,column+=width}textLength>0&&(pendingSeparator=!0)}return corpus.text=chunks.join(""),corpus}function normalizeQuery(query){return query.replace(/\s+/gu," ").trim()}function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function findSearchCorpusMatches(corpus,normalizedQuery){if(!normalizedQuery)return[];let expression=new RegExp(escapeRegExp(normalizedQuery),"giu"),matches=[],spanIndex=0;for(let match of corpus.
876
+ text.matchAll(expression)){let start=match.index,end=start+match[0].length;for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=start;)spanIndex+=1;let segments=[];for(let index=spanIndex;index<corpus.spans.length;index++){let span=corpus.spans[index];if(span.textStart>=end)break;if(span.textEnd<=start)continue;let startCol=span.linearColumns?span.startCol+Math.max(start,span.textStart)-span.textStart:span.startCol,endCol=span.linearColumns?span.startCol+Math.min(end,span.textEnd)-
877
+ span.textStart:span.endCol,previous=segments[segments.length-1];previous&&previous.row===span.row&&startCol<=previous.endCol?previous.endCol=Math.max(previous.endCol,endCol):segments.push({row:span.row,startCol,endCol})}for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=end;)spanIndex+=1;segments.length>0&&matches.push({segments})}return matches}var AltScreenSearchIndex=class{sourceLines;live;revision=-1;corpus;normalizedQuery;matches=[];search(lines,query,live){let changedFrom=0;
878
+ if(live)changedFrom=live===this.live?live.changedSince(this.revision):0,this.sourceLines=void 0;else{let sourceChanged2=this.sourceLines?.length!==lines.length;if(!sourceChanged2&&this.sourceLines){for(let index=0;index<lines.length;index++)if(this.sourceLines[index]!==lines[index]){sourceChanged2=!0;break}}sourceChanged2?this.sourceLines=Array.from(lines):changedFrom=Number.POSITIVE_INFINITY}let sourceChanged=changedFrom!==Number.POSITIVE_INFINITY;if(!this.corpus||changedFrom===0)this.corpus=buildSearchCorpus(
879
+ lines);else if(sourceChanged){let startRow=Math.min(changedFrom,this.corpus.rowTextStarts.length,lines.length);this.corpus=buildSearchCorpus(lines,this.corpus,startRow)}this.live=live,this.revision=live?.revision??-1;let normalizedQuery=normalizeQuery(query),changed=sourceChanged||normalizedQuery!==this.normalizedQuery;return changed&&(this.normalizedQuery=normalizedQuery,this.matches=findSearchCorpusMatches(this.corpus,normalizedQuery)),{matches:this.matches,changed}}};function getAltScreenSearchMatchKey(match){let first=match.segments[0],last=match.segments[match.segments.length-1];return first&&last?`${first.row}:${first.startCol}:${last.row}:${last.endCol}`:""}var AltScreenSearchComponent=class{input=new Input({prompt:" ",placeholder:"Find in transcript",placeholderStyle:text=>`\x1B[2m${text}\x1B[22m`});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(onQueryChange,navigationButtonStyle=text=>text){
878
880
  this.onQueryChange=onQueryChange,this.navigationButtonStyle=navigationButtonStyle}get focused(){return this._focused}set focused(value){this._focused=value,this.input.focused=value}setResult(index,count){this.resultIndex=index,this.resultCount=count}getNavigationDirectionAt(row,column){if(row===2){if(column>=this.previousButtonStart&&column<this.previousButtonEnd)return-1;if(column>=this.nextButtonStart&&column<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(direction){return direction===
879
881
  this.hoveredNavigationDirection?!1:(this.hoveredNavigationDirection=direction,!0)}handleInput(data){let previous=this.input.getValue();this.input.handleInput(data);let query=this.input.getValue();query!==previous&&this.onQueryChange(query)}invalidate(){this.input.invalidate()}render(width){let safeWidth=Math.max(1,width),innerWidth=Math.max(0,safeWidth-2),formatKey=key=>key?key.split("+").map(part=>process.platform==="darwin"&&part.toLowerCase()==="alt"?"Option":part.charAt(0).toUpperCase()+part.
880
882
  slice(1)).join("+"):"Unbound",keybindings=getKeybindings(),previousKey=formatKey(keybindings.getKeys("tui.altScreen.searchPrevious")[0]),nextKey=formatKey(keybindings.getKeys("tui.altScreen.searchNext")[0]),result=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",resultSpace=Math.max(0,innerWidth-3),visibleResult=truncateToWidth(result,resultSpace,""),resultText=visibleResult?`\x1B[2m ${visibleResult} \x1B[22m`:"",inputWidth=Math.max(0,innerWidth-
@@ -882,42 +884,42 @@ visibleWidth(resultText)),inputLine=truncateToWidth(this.input.render(Math.max(1
882
884
  controlsWidth>availableControlsWidth&&(previousButton="\u2191",nextButton="\u2193",separator=" ",controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton));let showButtons=controlsWidth<=availableControlsWidth,renderedButtons=showButtons?this.navigationButtonStyle(previousButton,this.hoveredNavigationDirection===-1)+separator+this.navigationButtonStyle(nextButton,this.hoveredNavigationDirection===1):"",outerGapsWidth=showButtons?outerGapWidth*2:0,rightRuleWidth=renderedButtons&&
883
885
  innerWidth>controlsWidth+outerGapsWidth?1:0,leftRuleWidth=Math.max(0,innerWidth-(showButtons?controlsWidth:0)-outerGapsWidth-rightRuleWidth),previousStart=1+leftRuleWidth+outerGapWidth;return this.previousButtonStart=showButtons?previousStart:-1,this.previousButtonEnd=showButtons?previousStart+visibleWidth(previousButton):-1,this.nextButtonStart=showButtons?this.previousButtonEnd+visibleWidth(separator):-1,this.nextButtonEnd=showButtons?this.nextButtonStart+visibleWidth(nextButton):-1,safeWidth===
884
886
  1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(innerWidth)}\u2510`,`\u2502${content}\u2502`,`\u2514${"\u2500".repeat(leftRuleWidth)}${renderedButtons?" ":""}${renderedButtons}${renderedButtons?" ":""}${"\u2500".repeat(rightRuleWidth)}\u2518`]}};var DEFAULT_DURATION_MS=1e3,AltScreenFlashContainer=class{entries=[];nextId=0;requestRender;constructor(requestRender){this.requestRender=requestRender}flash(message,durationMs=DEFAULT_DURATION_MS){let id=this.nextId++,timer=setTimeout(()=>{let index=this.entries.findIndex(entry=>entry.id===id);index!==-1&&(this.entries.splice(index,1),this.requestRender())},Math.max(0,durationMs));timer.unref(),this.entries.push({id,message,timer}),this.requestRender()}dispose(){for(let entry of this.entries)clearTimeout(
885
- entry.timer);this.entries.length=0}invalidate(){}render(width){return this.entries.map(entry=>`\x1B[7m${truncateToWidth(` ${entry.message} `,width,"")}\x1B[27m`)}};var OSC133_ZONE_PREFIX=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function intersect(a3,b){let x2=Math.max(a3.x,b.x),y=Math.max(a3.y,b.y),right=Math.min(a3.x+a3.width,b.x+b.width),bottom=Math.min(a3.y+a3.height,b.y+b.height);return{x:x2,y,width:Math.max(0,right-x2),height:Math.max(0,bottom-y)}}function renderCached(context,component,width){let safeWidth=Math.max(1,Math.floor(width)),known=context.renderCache.get(component);if(known!==void 0){if(known.width===safeWidth)return known.lines;let other=known.
886
- others?.get(safeWidth);if(other!==void 0)return other}let lines=renderLiveLines(component,safeWidth)?.lines??renderSharedLines(component,safeWidth);return known===void 0?context.renderCache.set(component,{width:safeWidth,lines}):(known.others??=new Map,known.others.set(safeWidth,lines)),lines}function measureHeight(context,component,width){return component instanceof VStack&&component.render===VStack.prototype.render?component.measureHeight(Math.max(1,Math.floor(width)),context.heightOf):renderCached(
887
- context,component,width).length}function measureWidth(context,component,width){return renderCached(context,component,width).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)}function withParent(box,parent){return box.parent=parent,box}function translateBox(box,deltaY){box.rect.y+=deltaY;let children=box.children;for(let i=0;i<children.length;i++)translateBox(children[i],deltaY)}function updateClips(box,parentClip){box.clip=intersect(parentClip,box.rect);let children=box.children;for(let i=0;i<
888
- children.length;i++)updateClips(children[i],box.clip)}function layoutComponent(context,component,x2,y,width,height,clip){let safeWidth=Math.max(1,Math.floor(width)),node=getLayoutNode(component);if(!node){let lines=renderCached(context,component,safeWidth),allocatedHeight2=height===void 0?lines.length:Math.max(0,Math.floor(height)),lineOffset=0;if(lines.length>allocatedHeight2&&allocatedHeight2>0){let cursorLine=lines.findIndex(line=>line.includes(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=
889
- cursorLine-allocatedHeight2+1)}return{component,rect:{x:x2,y,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x:x2,y,width:safeWidth,height:allocatedHeight2}),children:[],lines,lineOffset,layer:0}}if(node.type==="scroll"){let previousScrollTop=node.state.scrollTop,contentWidth=node.state.getContentWidth(safeWidth),childBox=layoutComponent(context,node.component,x2,y-previousScrollTop,contentWidth,void 0,clip),contentHeight=childBox.rect.height,viewportHeight=height===void 0?contentHeight:
890
- Math.max(0,Math.floor(height));node.state.updateLayout(contentHeight,viewportHeight,context.requestRender),translateBox(childBox,previousScrollTop-node.state.scrollTop);let scrollView=node.state;(node.state.primary||!context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x:x2,y,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),box2={component,rect:rect2,clip:childClip,children:[childBox],scrollView,scrollContentLines:renderCached(context,node.component,
891
- contentWidth),layer:0};return childBox.parent=box2,updateClips(childBox,childClip),box2}let entries=visibleStackEntries(node.entries,context.viewport),gapTotal=Math.max(0,entries.length-1)*node.gap;if(node.type==="vstack"){let intrinsicHeights2=new Array(entries.length);for(let index=0;index<entries.length;index++){let entry=entries[index];intrinsicHeights2[index]=typeof entry.basis=="number"?entry.basis:measureHeight(context,entry.component,safeWidth)}let sizes=allocateStackSizes(entries,intrinsicHeights2,
892
- height,node.gap),sizesTotal=0;for(let index=0;index<sizes.length;index++)sizesTotal+=sizes[index];let naturalHeight=sizesTotal+gapTotal,allocatedHeight2=height===void 0?naturalHeight:Math.max(0,Math.floor(height)),rect2={x:x2,y,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y;for(let index=0;index<entries.length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x2,childY,safeWidth,sizes[index],
893
- box2.clip),box2)),childY+=sizes[index]+node.gap;return box2}let intrinsicWidths=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureWidth(context,entry.component,safeWidth)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,node.gap),intrinsicHeights=entries.map((entry,index)=>measureHeight(context,entry.component,Math.max(1,widths[index]))),allocatedHeight=height===void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,
894
- y,width:safeWidth,height:allocatedHeight},box={component,rect,clip:intersect(clip,rect),children:[],layer:0},childX=x2;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y;node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/2):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.
895
- push({component:entries[index].component,rect:{x:childX,y:childY,width:0,height:childHeight},clip:{x:childX,y:childY,width:0,height:0},children:[],parent:box,layer:0}):box.children.push(withParent(layoutComponent(context,entries[index].component,childX,childY,childWidth,childHeight,box.clip),box)),childX+=childWidth+node.gap}return box}function replaceScrollbarCell(line,column,totalWidth,replacement,preserveTargetBackground){if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(
896
- line,column),start=graphemeRange?.start??column,end=graphemeRange?.end??column+1,before=sliceByColumn(line,0,start,!0),target=sliceByColumn(line,start,end-start,!0),after=sliceByColumn(line,end,Math.max(0,totalWidth-end),!0),targetPrefix="",targetIndex=0;for(;targetIndex<target.length;){let ansi=extractAnsiCode(target,targetIndex);if(!ansi)break;targetPrefix+=ansi.code,targetIndex+=ansi.length}let beforePadding=" ".repeat(Math.max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.
897
- max(0,column-start)),cellPaddingAfter=" ".repeat(Math.max(0,end-column-1)),targetStyle=`\x1B[0m\x1B]8;;\x07${preserveTargetBackground?getActiveBackgroundAnsi(targetPrefix):""}`;return`${before}${beforePadding}${targetStyle}${cellPaddingBefore}${replacement}${cellPaddingAfter}${after}`}function getScrollbarGeometry(box,includeHiddenAuto=!1){if(!box.scrollView||box.rect.width<=0||box.rect.height<=0)return;let contentHeight=box.children[0]?.rect.height??box.scrollContentLines?.length??0,trackHeight=box.
898
- rect.height,canRevealHiddenAuto=includeHiddenAuto&&box.scrollView.scrollbar==="auto"&&contentHeight>trackHeight;if(!box.scrollView.isScrollbarVisible&&!canRevealHiddenAuto)return;let minThumbHeight=Math.min(2,trackHeight),thumbHeight=Math.max(minThumbHeight,Math.min(trackHeight,Math.round(trackHeight*trackHeight/contentHeight))),maxScrollTop=Math.max(0,contentHeight-trackHeight),maxThumbTop=trackHeight-thumbHeight,thumbOffset=maxScrollTop===0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),
899
- column=box.rect.x+box.rect.width-1;if(!(column<box.clip.x||column>=box.clip.x+box.clip.width))return{column,trackTop:box.rect.y,trackHeight,thumbTop:box.rect.y+thumbOffset,thumbHeight,maxScrollTop}}function paintScrollbar(box,screen,totalWidth){let geometry=getScrollbarGeometry(box);if(!(!geometry||!box.scrollView))for(let offset=0;offset<geometry.trackHeight;offset++){let row=geometry.trackTop+offset;if(row<box.clip.y||row>=box.clip.y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=
900
- geometry.thumbTop&&row<geometry.thumbTop+geometry.thumbHeight?box.scrollView.scrollbarThumbStyle(box.scrollView.isScrollbarActive?"\u2588":"\u2503"):box.scrollView.scrollbarTrackStyle("\u2502");screen[row]=replaceScrollbarCell(screen[row]??"",geometry.column,totalWidth,replacement,box.scrollView.scrollbar!=="always")}}function paintBox(box,screen,totalWidth){if(box.lines){let offset=box.lineOffset??0,firstRow=Math.max(box.rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.
901
- y+box.clip.height,screen.length);for(let row=firstRow;row<lastRow;row++){let sourceLine=box.lines[offset+row-box.rect.y];if(sourceLine===void 0)continue;let line=sourceLine.charCodeAt(0)===27&&sourceLine.startsWith("\x1B]133;")?sourceLine.replace(OSC133_ZONE_PREFIX,""):sourceLine,imageMetadata=getKittyImageMetadata(line);if(imageMetadata){let clipBottom=Math.min(screen.length,box.clip.y+box.clip.height),visibleRows=Math.min(imageMetadata.rows,clipBottom-row);visibleRows<imageMetadata.rows&&(line=
902
- cropKittyImageLine(line,0,visibleRows))}box.rect.x===0&&box.rect.width>=totalWidth&&(!screen[row]||isImageLine(line))?screen[row]=line:screen[row]=compositeTuiLine(screen[row]??"",line,box.rect.x,box.rect.width,totalWidth)}}let children=box.children;for(let i=0;i<children.length;i++)paintBox(children[i],screen,totalWidth);if(box.scrollView&&box.scrollContentLines&&box.scrollView.scrollTop>0&&box.rect.height>0){let scrollTop=box.scrollView.scrollTop,minRow=Math.max(0,scrollTop-getMaxKittyImageRows());
903
- for(let imageRow=scrollTop-1;imageRow>=minRow;imageRow--){let imageLine=box.scrollContentLines[imageRow]??"";if(!isImageLine(imageLine))continue;let metadata=getKittyImageMetadata(imageLine);if(!metadata)continue;let hiddenRows=scrollTop-imageRow;if(hiddenRows<metadata.rows){let visibleRows=Math.min(box.rect.height,metadata.rows-hiddenRows),cropped=cropKittyImageLine(imageLine,hiddenRows,visibleRows);box.rect.x===0&&box.rect.width>=totalWidth&&(screen[box.rect.y]=cropped)}break}}paintScrollbar(box,
904
- screen,totalWidth)}function renderLayoutFrame(root,width,height,requestRender){let safeWidth=Math.max(1,Math.floor(width)),safeHeight=Math.max(1,Math.floor(height)),context={viewport:{width:safeWidth,height:safeHeight},renderCache:new Map,heightOf:(component,width2)=>measureHeight(context,component,width2),requestRender,primaryScrollView:void 0},rootBox=layoutComponent(context,root,0,0,safeWidth,safeHeight,{x:0,y:0,width:safeWidth,height:safeHeight}),lines=[];for(let row=0;row<safeHeight;row++)lines.
905
- push("");return paintBox(rootBox,lines,safeWidth),{root:rootBox,width:safeWidth,height:safeHeight,lines,...context.primaryScrollView===void 0?{}:{primaryScrollView:context.primaryScrollView}}}function containsPoint(rect,x2,y){return x2>=rect.x&&x2<rect.x+rect.width&&y>=rect.y&&y<rect.y+rect.height}function getLayoutBoxesAt(frame,x2,y){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y)){result.push({box,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.
906
- root,0),result.sort((a3,b)=>b.box.layer-a3.box.layer||b.depth-a3.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===scrollView)return box;for(let child of box.children){let match=visit(child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x2,y){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y)){box.scrollView&&containsPoint(box.rect,x2,y)&&result.push({scrollView:box.scrollView,depth});
907
- for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a3,b)=>b.depth-a3.depth),result.map(entry=>entry.scrollView)}function terminalAcceleratesWheel(){let env=process.env;return process.platform==="darwin"&&env.SSH_CONNECTION===void 0&&env.SSH_CLIENT===void 0&&env.SSH_TTY===void 0}var WheelScrollAccelerator=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.isFinite(
887
+ entry.timer);this.entries.length=0}invalidate(){}render(width){return this.entries.map(entry=>`\x1B[7m${truncateToWidth(` ${entry.message} `,width,"")}\x1B[27m`)}};var OSC133_ZONE_PREFIX=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function intersect(a3,b){let x2=Math.max(a3.x,b.x),y=Math.max(a3.y,b.y),right=Math.min(a3.x+a3.width,b.x+b.width),bottom=Math.min(a3.y+a3.height,b.y+b.height);return{x:x2,y,width:Math.max(0,right-x2),height:Math.max(0,bottom-y)}}function renderCached(context,component,width){let safeWidth=Math.max(1,Math.floor(width)),known=context.renderCache.get(component);if(known!==void 0){if(known.width===safeWidth)return known;let other=known.others?.
888
+ get(safeWidth);if(other!==void 0)return other}let live=renderLiveLines(component,safeWidth),lines=live?.lines??renderSharedLines(component,safeWidth),rendered={width:safeWidth,lines,live};return known===void 0?context.renderCache.set(component,rendered):(known.others??=new Map,known.others.set(safeWidth,rendered)),rendered}function measureHeight(context,component,width){return component instanceof VStack&&component.render===VStack.prototype.render?component.measureHeight(Math.max(1,Math.floor(width)),
889
+ context.heightOf):renderCached(context,component,width).lines.length}function measureWidth(context,component,width){return renderCached(context,component,width).lines.reduce((max,line)=>Math.max(max,visibleWidth(line)),0)}function withParent(box,parent){return box.parent=parent,box}function translateBox(box,deltaY){box.rect.y+=deltaY;let children=box.children;for(let i=0;i<children.length;i++)translateBox(children[i],deltaY)}function updateClips(box,parentClip){box.clip=intersect(parentClip,box.
890
+ rect);let children=box.children;for(let i=0;i<children.length;i++)updateClips(children[i],box.clip)}function layoutComponent(context,component,x2,y,width,height,clip){let safeWidth=Math.max(1,Math.floor(width)),node=getLayoutNode(component);if(!node){let lines=renderCached(context,component,safeWidth).lines,allocatedHeight2=height===void 0?lines.length:Math.max(0,Math.floor(height)),lineOffset=0;if(lines.length>allocatedHeight2&&allocatedHeight2>0){let cursorLine=lines.findIndex(line=>line.includes(
891
+ CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x:x2,y,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x:x2,y,width:safeWidth,height:allocatedHeight2}),children:[],lines,lineOffset,layer:0}}if(node.type==="scroll"){let previousScrollTop=node.state.scrollTop,contentWidth=node.state.getContentWidth(safeWidth),childBox=layoutComponent(context,node.component,x2,y-previousScrollTop,contentWidth,void 0,clip),contentHeight=childBox.
892
+ rect.height,viewportHeight=height===void 0?contentHeight:Math.max(0,Math.floor(height));node.state.updateLayout(contentHeight,viewportHeight,context.requestRender),translateBox(childBox,previousScrollTop-node.state.scrollTop);let scrollView=node.state;(node.state.primary||!context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x:x2,y,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),content=renderCached(context,node.component,contentWidth),box2={component,
893
+ rect:rect2,clip:childClip,children:[childBox],scrollView,scrollContentLines:content.lines,scrollContentLive:content.live,layer:0};return childBox.parent=box2,updateClips(childBox,childClip),box2}let entries=visibleStackEntries(node.entries,context.viewport),gapTotal=Math.max(0,entries.length-1)*node.gap;if(node.type==="vstack"){let intrinsicHeights2=new Array(entries.length);for(let index=0;index<entries.length;index++){let entry=entries[index];intrinsicHeights2[index]=typeof entry.basis=="numbe\
894
+ r"?entry.basis:measureHeight(context,entry.component,safeWidth)}let sizes=allocateStackSizes(entries,intrinsicHeights2,height,node.gap),sizesTotal=0;for(let index=0;index<sizes.length;index++)sizesTotal+=sizes[index];let naturalHeight=sizesTotal+gapTotal,allocatedHeight2=height===void 0?naturalHeight:Math.max(0,Math.floor(height)),rect2={x:x2,y,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y;for(let index=0;index<entries.
895
+ length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x2,childY,safeWidth,sizes[index],box2.clip),box2)),childY+=sizes[index]+node.gap;return box2}let intrinsicWidths=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureWidth(context,entry.component,safeWidth)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,node.gap),intrinsicHeights=entries.map((entry,index)=>measureHeight(context,entry.component,Math.max(1,widths[index]))),allocatedHeight=height===
896
+ void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,y,width:safeWidth,height:allocatedHeight},box={component,rect,clip:intersect(clip,rect),children:[],layer:0},childX=x2;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y;node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/2):
897
+ node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.push({component:entries[index].component,rect:{x:childX,y:childY,width:0,height:childHeight},clip:{x:childX,y:childY,width:0,height:0},children:[],parent:box,layer:0}):box.children.push(withParent(layoutComponent(context,entries[index].component,childX,childY,childWidth,childHeight,box.clip),box)),childX+=childWidth+node.gap}return box}function replaceScrollbarCell(line,column,totalWidth,replacement,preserveTargetBackground){
898
+ if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(line,column),start=graphemeRange?.start??column,end=graphemeRange?.end??column+1,before=sliceByColumn(line,0,start,!0),target=sliceByColumn(line,start,end-start,!0),after=sliceByColumn(line,end,Math.max(0,totalWidth-end),!0),targetPrefix="",targetIndex=0;for(;targetIndex<target.length;){let ansi=extractAnsiCode(target,targetIndex);if(!ansi)break;targetPrefix+=ansi.code,targetIndex+=ansi.length}let beforePadding=" ".repeat(Math.
899
+ max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.max(0,column-start)),cellPaddingAfter=" ".repeat(Math.max(0,end-column-1)),targetStyle=`\x1B[0m\x1B]8;;\x07${preserveTargetBackground?getActiveBackgroundAnsi(targetPrefix):""}`;return`${before}${beforePadding}${targetStyle}${cellPaddingBefore}${replacement}${cellPaddingAfter}${after}`}function getScrollbarGeometry(box,includeHiddenAuto=!1){if(!box.scrollView||box.rect.width<=0||box.rect.height<=0)return;let contentHeight=box.children[0]?.
900
+ rect.height??box.scrollContentLines?.length??0,trackHeight=box.rect.height,canRevealHiddenAuto=includeHiddenAuto&&box.scrollView.scrollbar==="auto"&&contentHeight>trackHeight;if(!box.scrollView.isScrollbarVisible&&!canRevealHiddenAuto)return;let minThumbHeight=Math.min(2,trackHeight),thumbHeight=Math.max(minThumbHeight,Math.min(trackHeight,Math.round(trackHeight*trackHeight/contentHeight))),maxScrollTop=Math.max(0,contentHeight-trackHeight),maxThumbTop=trackHeight-thumbHeight,thumbOffset=maxScrollTop===
901
+ 0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),column=box.rect.x+box.rect.width-1;if(!(column<box.clip.x||column>=box.clip.x+box.clip.width))return{column,trackTop:box.rect.y,trackHeight,thumbTop:box.rect.y+thumbOffset,thumbHeight,maxScrollTop}}function paintScrollbar(box,screen,totalWidth){let geometry=getScrollbarGeometry(box);if(!(!geometry||!box.scrollView))for(let offset=0;offset<geometry.trackHeight;offset++){let row=geometry.trackTop+offset;if(row<box.clip.y||row>=box.clip.
902
+ y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=geometry.thumbTop&&row<geometry.thumbTop+geometry.thumbHeight?box.scrollView.scrollbarThumbStyle(box.scrollView.isScrollbarActive?"\u2588":"\u2503"):box.scrollView.scrollbarTrackStyle("\u2502");screen[row]=replaceScrollbarCell(screen[row]??"",geometry.column,totalWidth,replacement,box.scrollView.scrollbar!=="always")}}function paintBox(box,screen,totalWidth){if(box.lines){let offset=box.lineOffset??0,firstRow=Math.max(box.
903
+ rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.y+box.clip.height,screen.length);for(let row=firstRow;row<lastRow;row++){let sourceLine=box.lines[offset+row-box.rect.y];if(sourceLine===void 0)continue;let line=sourceLine.charCodeAt(0)===27&&sourceLine.startsWith("\x1B]133;")?sourceLine.replace(OSC133_ZONE_PREFIX,""):sourceLine,imageMetadata=getKittyImageMetadata(line);if(imageMetadata){let clipBottom=Math.min(screen.length,box.clip.y+box.clip.height),visibleRows=Math.min(
904
+ imageMetadata.rows,clipBottom-row);visibleRows<imageMetadata.rows&&(line=cropKittyImageLine(line,0,visibleRows))}box.rect.x===0&&box.rect.width>=totalWidth&&(!screen[row]||isImageLine(line))?screen[row]=line:screen[row]=compositeTuiLine(screen[row]??"",line,box.rect.x,box.rect.width,totalWidth)}}let children=box.children;for(let i=0;i<children.length;i++)paintBox(children[i],screen,totalWidth);if(box.scrollView&&box.scrollContentLines&&box.scrollView.scrollTop>0&&box.rect.height>0){let scrollTop=box.
905
+ scrollView.scrollTop,minRow=Math.max(0,scrollTop-getMaxKittyImageRows());for(let imageRow=scrollTop-1;imageRow>=minRow;imageRow--){let imageLine=box.scrollContentLines[imageRow]??"";if(!isImageLine(imageLine))continue;let metadata=getKittyImageMetadata(imageLine);if(!metadata)continue;let hiddenRows=scrollTop-imageRow;if(hiddenRows<metadata.rows){let visibleRows=Math.min(box.rect.height,metadata.rows-hiddenRows),cropped=cropKittyImageLine(imageLine,hiddenRows,visibleRows);box.rect.x===0&&box.rect.
906
+ width>=totalWidth&&(screen[box.rect.y]=cropped)}break}}paintScrollbar(box,screen,totalWidth)}function renderLayoutFrame(root,width,height,requestRender){let safeWidth=Math.max(1,Math.floor(width)),safeHeight=Math.max(1,Math.floor(height)),context={viewport:{width:safeWidth,height:safeHeight},renderCache:new Map,heightOf:(component,width2)=>measureHeight(context,component,width2),requestRender,primaryScrollView:void 0},rootBox=layoutComponent(context,root,0,0,safeWidth,safeHeight,{x:0,y:0,width:safeWidth,
907
+ height:safeHeight}),lines=[];for(let row=0;row<safeHeight;row++)lines.push("");return paintBox(rootBox,lines,safeWidth),{root:rootBox,width:safeWidth,height:safeHeight,lines,...context.primaryScrollView===void 0?{}:{primaryScrollView:context.primaryScrollView}}}function containsPoint(rect,x2,y){return x2>=rect.x&&x2<rect.x+rect.width&&y>=rect.y&&y<rect.y+rect.height}function getLayoutBoxesAt(frame,x2,y){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y)){result.push({box,depth});for(let child of box.
908
+ children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a3,b)=>b.box.layer-a3.box.layer||b.depth-a3.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===scrollView)return box;for(let child of box.children){let match=visit(child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x2,y){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y)){box.scrollView&&containsPoint(box.rect,x2,
909
+ y)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a3,b)=>b.depth-a3.depth),result.map(entry=>entry.scrollView)}function terminalAcceleratesWheel(){let env=process.env;return process.platform==="darwin"&&env.SSH_CONNECTION===void 0&&env.SSH_CLIENT===void 0&&env.SSH_TTY===void 0}var WheelScrollAccelerator=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.isFinite(
908
910
  this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let gap=now-this.lastTime,sameGesture=direction===this.lastDirection&&gap<=200;if(this.lastTime=now,this.lastDirection=direction,!sameGesture)return this.averageGap=void 0,this.carry=0,1;if(gap<5)return 1;this.averageGap=this.averageGap===void 0?gap:(this.averageGap+gap)/2;let lines=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,whole=Math.floor(lines);return this.carry=lines-whole,whole}reset(){this.lastTime=Number.
909
911
  NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var ENTER_ALT_SCREEN="\x1B[?1049h",EXIT_ALT_SCREEN="\x1B[?1049l",DISABLE_AUTOWRAP="\x1B[?7l",ENABLE_AUTOWRAP="\x1B[?7h",ENABLE_BUTTON_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",ENABLE_ALL_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",DISABLE_MOUSE="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",FOCUS_IN="\x1B[I",FOCUS_OUT="\x1B[O",BEGIN_SYNCHRONIZED_OUTPUT="\x1B[?2026h",END_SYNCHRONIZED_OUTPUT="\x1B[?2026l",MIN_ROWS_SAVED_BY_SCROLLING=3,OSC133_ZONE_PREFIX2=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,
910
912
  OSC133_PROMPT_START=/^\x1b\]133;A(?:\x07|\x1b\\)/,PAGE_SCROLL_OVERLAP=4,ALT_WHEEL_SCROLL_MULTIPLIER=5,MAX_CACHED_OFFSCREEN_KITTY_IMAGES=16,MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES=32*1024*1024,MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES=64*1024*1024,DOUBLE_CLICK_INTERVAL_MS=500,COPY_ERROR_FLASH_DURATION_MS=5e3,TERMINAL_WORD_SELECTION_JOINERS=new Set(["/","-","+","\\","~","_","."]),TuiAltScreen=class extends TuiBase{mode="fullscreen";[VIEWPORT_TUI]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;finishedRows=new Map;finishedRowsWidth=0;imageRows=new Set;resolvedRows=new Map;resolvedRowsCursor=!1;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="\
911
913
  character";selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScroll;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(terminal,showHardwareCursor,logDirectory,options={}){
912
- super(terminal,showHardwareCursor,logDirectory),this.implicitDocument={render:width=>super.renderShared(width),handleMouse:event=>super.handleMouse(event),invalidate:()=>{for(let child of this.children)child.invalidate()}},this.implicitScrollView=new ScrollView(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new AltScreenFlashContainer(()=>this.requestRender()),this.wheelScroll=new WheelScrollAccelerator(options.wheelScrollLines??1),this.mouseEnabled=options.mouse??!0,this.searchMatchStyle=
913
- options.searchMatchStyle??(text=>`\x1B[4m${text}\x1B[24m`),this.searchCurrentMatchStyle=options.searchCurrentMatchStyle??(text=>`\x1B[1;7m${text}\x1B[22;27m`),this.searchNavigationButtonStyle=options.searchNavigationButtonStyle??(text=>text),this.scrollToEndIndicator=options.scrollToEndIndicator,this.openUrl=options.openUrl,this.onRightClickPaste=options.onRightClickPaste,this.copyOnSelect=options.copyOnSelect??!0,this.copySelection=options.copySelection,this.addInputListener(data=>this.handleViewportInput(
914
- data))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(lines){this.wheelScroll.setLines(lines)}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(enabled){this.copyOnSelect=enabled}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}resetTextSelection(){
915
- this.clearTextSelection(),this.lastClick=void 0}getScreenLines(){return[...this.previousScreen]}setLayoutRoot(component){this.layoutRoot!==component&&(this.layoutRoot=component,this.currentLayout=void 0,this.requestRender())}render(width){return this.layoutRoot?.render(width)??super.render(width)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),
916
- this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let capabilities=getCapabilities();this.imageProtocol=capabilities.images,this.uploadedKittyImages.clear(),capabilities.images==="iterm2"&&(this.savedCapabilities=capabilities,setCapabilities({...capabilities,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=
917
- void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let term=process.env.TERM?.toLowerCase()??"",mouseSequence=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||term.startsWith("tmux")||term.startsWith("screen")?ENABLE_BUTTON_MOTION_MOUSE:ENABLE_ALL_MOTION_MOUSE;this.terminal.write(`${ENTER_ALT_SCREEN}${DISABLE_AUTOWRAP}${this.mouseEnabled?mouseSequence:
918
- ""}\x1B[2J\x1B[H\x1B[?25l`)}beforeTerminalStop(_options){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${this.deleteKittyImages()}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${END_SYNCHRONIZED_OUTPUT}`),this.uploadedKittyImages.clear())}afterTerminalStop(options){if(this.altScreenActive){
919
- if(this.altScreenActive=!1,options.preserveScreen)this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`);else{let width=Math.max(1,this.terminal.columns),documentLines=this.resolveFakeCursors(this.render(width)).map(line=>line.replace(OSC133_ZONE_PREFIX2,""));this.lastDocument=this.applyLineResets(documentLines.map(line=>line.replaceAll(CURSOR_MARKER,""))).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));
920
- let buffer=`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
914
+ super(terminal,showHardwareCursor,logDirectory),this.implicitDocument={render:width=>super.renderShared(width),handleMouse:event=>super.handleMouse(event),invalidate:()=>{for(let child of this.children)child.invalidate()}},markLiveRender(this.implicitDocument.render,width=>Container.renderLive(this,width)),this.implicitScrollView=new ScrollView(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new AltScreenFlashContainer(()=>this.requestRender()),this.wheelScroll=new WheelScrollAccelerator(
915
+ options.wheelScrollLines??1),this.mouseEnabled=options.mouse??!0,this.searchMatchStyle=options.searchMatchStyle??(text=>`\x1B[4m${text}\x1B[24m`),this.searchCurrentMatchStyle=options.searchCurrentMatchStyle??(text=>`\x1B[1;7m${text}\x1B[22;27m`),this.searchNavigationButtonStyle=options.searchNavigationButtonStyle??(text=>text),this.scrollToEndIndicator=options.scrollToEndIndicator,this.openUrl=options.openUrl,this.onRightClickPaste=options.onRightClickPaste,this.copyOnSelect=options.copyOnSelect??
916
+ !0,this.copySelection=options.copySelection,this.addInputListener(data=>this.handleViewportInput(data))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(lines){this.wheelScroll.setLines(lines)}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(enabled){this.copyOnSelect=enabled}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){
917
+ let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}resetTextSelection(){this.clearTextSelection(),this.lastClick=void 0}getScreenLines(){return[...this.previousScreen]}setLayoutRoot(component){this.layoutRoot!==component&&(this.layoutRoot=component,this.currentLayout=void 0,this.requestRender())}render(width){return this.layoutRoot?.render(width)??super.render(width)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){
918
+ return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let capabilities=getCapabilities();this.imageProtocol=capabilities.images,this.uploadedKittyImages.clear(),capabilities.images==="iterm2"&&(this.savedCapabilities=capabilities,setCapabilities({...capabilities,images:null}),this.invalidate()),this.lastDocument=
919
+ [],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let term=process.env.TERM?.toLowerCase()??"",mouseSequence=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||term.startsWith("tmux")||term.startsWith("screen")?ENABLE_BUTTON_MOTION_MOUSE:
920
+ ENABLE_ALL_MOTION_MOUSE;this.terminal.write(`${ENTER_ALT_SCREEN}${DISABLE_AUTOWRAP}${this.mouseEnabled?mouseSequence:""}\x1B[2J\x1B[H\x1B[?25l`)}beforeTerminalStop(_options){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${this.deleteKittyImages()}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${END_SYNCHRONIZED_OUTPUT}`),
921
+ this.uploadedKittyImages.clear())}afterTerminalStop(options){if(this.altScreenActive){if(this.altScreenActive=!1,options.preserveScreen)this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`);else{let width=Math.max(1,this.terminal.columns),documentLines=this.resolveFakeCursors(this.render(width)).map(line=>line.replace(OSC133_ZONE_PREFIX2,""));this.lastDocument=this.applyLineResets(documentLines.map(line=>line.replaceAll(CURSOR_MARKER,""))).map(line=>isImageLine(
922
+ line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let buffer=`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
921
923
  `),buffer+=`\r\x1B[2K${this.lastDocument[row]??""}`;buffer+=`\x1B[0m${ENABLE_AUTOWRAP}\r
922
924
  \x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}getExitRestorePrefix(){let prefix=super.getExitRestorePrefix();return this.altScreenActive?`${END_SYNCHRONIZED_OUTPUT}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${prefix}`:prefix}getExitRestoreSuffix(){return`${super.getExitRestoreSuffix()}${this.altScreenActive?`${EXIT_ALT_SCREEN}\x1B[?25h`:""}`}deleteKittyImages(){return this.
923
925
  imageProtocol==="kitty"?deleteAllKittyImages():""}prepareKittyScreen(screen){let visibleImageIds=new Set,lines=screen.map(line=>{let placement=getKittyImagePlacement(line);if(!placement)return line;visibleImageIds.add(placement.imageId);let cachedImage=this.uploadedKittyImages.get(placement.imageId),nextCachedImage={transmissionGeneration:placement.transmissionGeneration,transmissionBytes:placement.transmissionBytes,estimatedDecodedBytes:placement.estimatedDecodedBytes};return cachedImage&&this.
@@ -929,12 +931,12 @@ query=>this.updateSearchQuery(query),this.searchNavigationButtonStyle),search={c
929
931
  activeSearch;if(!search||query===search.query)return;let selected=search.matches[search.selectedIndex];search.anchorRow=selected?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,search.query=query,search.selectionMode="query",search.component.setResult(-1,0),this.requestRender()}navigateSearch(direction){let search=this.activeSearch;search?.query&&(search.selectionMode=direction<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(x2,y){let search=this.activeSearch,bounds=search?.
930
932
  overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||y<bounds.row||y>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y-bounds.row,x2-bounds.col)}handleSearchMouseEvent(event){let search=this.activeSearch;if(!search)return!1;let direction=this.getSearchNavigationDirectionAt(event.x,event.y);return search.component.setHoveredNavigationDirection(direction)&&this.requestRender(),direction===void 0||event.release||(event.button&32)!==0||
931
933
  (event.button&3)!==0?!1:(this.navigateSearch(direction),!0)}refreshSearch(layout){let search=this.activeSearch;if(!search)return!1;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView),lines=box?.scrollContentLines;if(!lines||!search.query.trim())return search.matches=[],search.selectedIndex=-1,search.selectedKey=void 0,search.selectionMode="retain",search.component.setResult(-1,0),!1;let shouldRevealSelection=search.selectionMode!=="retain",result=search.
932
- index.search(lines,search.query),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;if(matches.length>0)if(search.selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].segments[0]?.row??0)<search.anchorRow?
933
- low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else selectedIndex=exactIndex>=0?exactIndex:
934
- Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||!lastSegment||scrollView.viewportHeight<=
935
- 0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==before}flash(message,durationMs){this.flashes.flash(message,durationMs)}shouldDeferViewportInput(){return this.getFocusedComponent()?.capturesViewportInput?!0:this.isOverlayFocused()&&this.activeSearch?.
936
- overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&
937
- this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(data);if(wheelEvent){let lines=this.
934
+ index.search(lines,search.query,box?.scrollContentLive),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;if(matches.length>0)if(search.selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].segments[0]?.
935
+ row??0)<search.anchorRow?low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else selectedIndex=
936
+ exactIndex>=0?exactIndex:Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||!lastSegment||
937
+ scrollView.viewportHeight<=0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==before}flash(message,durationMs){this.flashes.flash(message,durationMs)}shouldDeferViewportInput(){return this.getFocusedComponent()?.capturesViewportInput?!0:this.isOverlayFocused()&&
938
+ this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(
939
+ void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(data);if(wheelEvent){let lines=this.
938
940
  wheelScroll.next(wheelEvent.direction,performance.now()),wheelDelta=wheelEvent.direction*((wheelEvent.button&8)!==0?lines*ALT_WHEEL_SCROLL_MULTIPLIER:lines),event=this.createMouseEvent("wheel",wheelEvent.button,wheelEvent.x,wheelEvent.y,{wheelDelta}),overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));return result?(this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):(this.routeWheel(wheelEvent,wheelDelta),
939
941
  {consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.navigateSearch(1),{consume:!0};if(keybindings.
940
942
  matches(data,"tui.altScreen.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInput()){if(keybindings.matches(data,"tui.altScreen.pageUp"))return isRelease||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.pageDown"))return isRelease||this.scrollBy(
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-GICL5V54.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEOMXMW6.js";var IMAGE_OPT_IN_HEADERS={"TypeSafe-Danger-Zone-Images":"true"};function probabilities(label,value,id){if(!isRecord(value))throw new Error(`${label} returned invalid probabilities for ${id}`);return Object.fromEntries(Object.entries(value).map(([key,probability])=>[key,requiredNumber(label,probability,`probability for ${id}.${key}`)]))}function parseAnswers(label,value,context){if(!isRecord(value))throw new Error(`${label} returned an unexpected response`);let answers=[];for(let[id,question]of Object.
2
+ import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-6PD3T2EF.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEOMXMW6.js";var IMAGE_OPT_IN_HEADERS={"TypeSafe-Danger-Zone-Images":"true"};function probabilities(label,value,id){if(!isRecord(value))throw new Error(`${label} returned invalid probabilities for ${id}`);return Object.fromEntries(Object.entries(value).map(([key,probability])=>[key,requiredNumber(label,probability,`probability for ${id}.${key}`)]))}function parseAnswers(label,value,context){if(!isRecord(value))throw new Error(`${label} returned an unexpected response`);let answers=[];for(let[id,question]of Object.
3
3
  entries(context.questions)){let answer=value[id];if(!isRecord(answer))throw new Error(`${label} did not return an answer for ${id}`);if(question.type==="choice"){if(answer.type!=="choice"||typeof answer.choice!="string")throw new Error(`${label} did not return a choice answer for ${id}`);answers.push([id,{type:"choice",choice:answer.choice,probabilities:probabilities(label,answer.probabilities,id),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else if(question.type===
4
4
  "score"){if(answer.type!=="score")throw new Error(`${label} did not return a score answer for ${id}`);answers.push([id,{type:"score",score:requiredNumber(label,answer.score,`score for ${id}`),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else{if(answer.type!=="noul")throw new Error(`${label} did not return a bool answer for ${id}`);answers.push([id,{type:"bool",probability:requiredNumber(label,answer.noul,`probability for ${id}`)}])}}return Object.fromEntries(answers)}
5
5
  var ASSET_FORMATS={"image/png":"png","image/jpeg":"jpeg"},DATA_URL_TYPES=new Set(["image/png","image/jpeg","image/webp"]),MAX_DATA_URL_IMAGES=4;function addImages(label,model,input,images,request){if(input==="images"){if(images.length>MAX_DATA_URL_IMAGES)throw new Error(`${label} accepts at most ${MAX_DATA_URL_IMAGES} images per request, got ${images.length}`);request.images=images.map(image=>{if(!DATA_URL_TYPES.has(image.mimeType))throw new Error(`${label} accepts PNG, JPEG, and WebP images for\