dal-code 1.0.54 → 1.0.55

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 (140) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/NOTICE +11 -0
  3. package/dist/bundle/chunks/{anthropic-messages-UHE6F2IE.js → anthropic-messages-LJWWEQIU.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-EK4W2MKL.js → azure-openai-responses-GK4VH6GM.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  6. package/dist/bundle/chunks/{chunk-K4B5ABCQ.js → chunk-2XX4WZT6.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-CSZTBJOE.js → chunk-3ANBT7AT.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-SCYK4XNE.js → chunk-44EXLOHK.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-3ZHZINH3.js → chunk-5TGFM4KW.js} +2 -2
  10. package/dist/bundle/chunks/{chunk-RKLUP6JT.js → chunk-6U37J6E7.js} +343 -343
  11. package/dist/bundle/chunks/{chunk-EH7SFF47.js → chunk-AL3DFAIM.js} +2 -2
  12. package/dist/bundle/chunks/{chunk-356BFRU3.js → chunk-D3HKK2ZD.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-IDZ3QKHZ.js → chunk-DBT5OS5V.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-VIS5PYQO.js → chunk-DWMC4U2M.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-K7VBBYTT.js → chunk-F5SIUTR7.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-O7G23ELK.js → chunk-GX37DI5S.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-FE533CCR.js → chunk-KSF7BFGS.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-L3RBW36Y.js → chunk-NMU45EFT.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-2C7JTP5O.js → chunk-PRBATF6B.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-4DMD6C65.js → chunk-SCSGNIU5.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-33MCYYJ3.js → chunk-SMPERFJU.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-XRF4A4KI.js → chunk-SNBVCTMQ.js} +2 -2
  23. package/dist/bundle/chunks/{chunk-R7FBN5UP.js → chunk-YDOF6JVP.js} +2 -2
  24. package/dist/bundle/chunks/{chunk-B5GJW7C2.js → chunk-ZYP3V3TD.js} +1 -1
  25. package/dist/bundle/chunks/{cli-XOLEGZVC.js → cli-VKNCK5P5.js} +1 -1
  26. package/dist/bundle/chunks/{cli-YJV3WN2N.js → cli-Z44UHMMU.js} +1 -1
  27. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-KNGB64NR.js → cloudflare-workers-ai-system-one-G4E4L26A.js} +1 -1
  28. package/dist/bundle/chunks/{easter-egg-3d-5TFBCTIS.js → easter-egg-3d-W2F3ROZ6.js} +1 -1
  29. package/dist/bundle/chunks/{execute-6PNQ63VS.js → execute-3FWM3EMV.js} +1 -1
  30. package/dist/bundle/chunks/{google-generative-ai-YJN7TGWU.js → google-generative-ai-HVFDKPI3.js} +1 -1
  31. package/dist/bundle/chunks/{google-vertex-3BVJFMMZ.js → google-vertex-6E4HATAC.js} +1 -1
  32. package/dist/bundle/chunks/{llama-cpp-classify-JVUWNG3E.js → llama-cpp-classify-3HAEJDKO.js} +1 -1
  33. package/dist/bundle/chunks/{mcp-PC3Y3FBI.js → mcp-SGBPG7LV.js} +1 -1
  34. package/dist/bundle/chunks/{mistral-conversations-O6YIQAS5.js → mistral-conversations-6UC2WYUC.js} +1 -1
  35. package/dist/bundle/chunks/{office-AXLGVCMO.js → office-2F4B572E.js} +1 -1
  36. package/dist/bundle/chunks/{openai-codex-responses-YQ5NNPTG.js → openai-codex-responses-WPSZR4EE.js} +1 -1
  37. package/dist/bundle/chunks/{openai-completions-R4I3PKBD.js → openai-completions-2RGIFVKJ.js} +1 -1
  38. package/dist/bundle/chunks/{openai-decisions-IUHMKKHZ.js → openai-decisions-BLZVYNRQ.js} +1 -1
  39. package/dist/bundle/chunks/{openai-responses-E2PHOQF4.js → openai-responses-N65DO7MB.js} +1 -1
  40. package/dist/bundle/chunks/{openrouter-images-NCMLTKZW.js → openrouter-images-LQ4VP5P7.js} +1 -1
  41. package/dist/bundle/chunks/{pi-messages-GLTSGLSO.js → pi-messages-VYTRLMVB.js} +1 -1
  42. package/dist/bundle/chunks/{review-KXWT7T3V.js → review-MKITXKSI.js} +1 -1
  43. package/dist/bundle/chunks/{router-26PXJ7YH.js → router-RL7OYANY.js} +1 -1
  44. package/dist/bundle/chunks/{runtime-LJBCO7CX.js → runtime-KB5ZUQB6.js} +1 -1
  45. package/dist/bundle/chunks/{sdk-6GP346VB.js → sdk-C5BAFGNR.js} +1 -1
  46. package/dist/bundle/chunks/sync-AQUDRXHM.js +7 -0
  47. package/dist/bundle/chunks/{typesafe-system-one-GQFHU7SQ.js → typesafe-system-one-6ZFGVJMV.js} +1 -1
  48. package/dist/bundle/chunks/{usage-MY7HTXQB.js → usage-CK3QZLTW.js} +1 -1
  49. package/dist/bundle/chunks/{virtual-modules-BEBLHRXC.js → virtual-modules-GRXCAWTO.js} +1 -1
  50. package/dist/bundle/cli-runtime.js +1 -1
  51. package/dist/bundle/index.js +1 -1
  52. package/dist/bundle/rpc-entry.js +1 -1
  53. package/dist/core/extensions/index.d.ts +1 -1
  54. package/dist/core/extensions/types.d.ts +9 -5
  55. package/dist/core/tools/bash.js +1 -1
  56. package/dist/core/tools/edit.js +2 -3
  57. package/dist/core/tools/renderers/bash.js +1 -1
  58. package/dist/core/tools/renderers/edit.js +2 -2
  59. package/dist/modes/interactive/components/assistant-message.d.ts +3 -0
  60. package/dist/modes/interactive/components/assistant-message.js +2 -2
  61. package/dist/modes/interactive/components/diff.d.ts +22 -0
  62. package/dist/modes/interactive/components/diff.js +4 -3
  63. package/dist/modes/interactive/components/keybinding-hints.js +1 -1
  64. package/dist/modes/interactive/components/panel-line.js +1 -0
  65. package/dist/modes/interactive/components/status-indicator.d.ts +23 -1
  66. package/dist/modes/interactive/components/status-indicator.js +1 -1
  67. package/dist/modes/interactive/components/tool-execution.d.ts +2 -2
  68. package/dist/modes/interactive/components/tool-execution.js +5 -5
  69. package/dist/modes/interactive/interactive-mode.d.ts +3 -0
  70. package/dist/modes/interactive/interactive-mode.js +18 -18
  71. package/dist/modes/interactive/theme/dark.json +4 -0
  72. package/dist/modes/interactive/theme/light.json +4 -0
  73. package/dist/modes/interactive/theme/system-theme.js +1 -1
  74. package/dist/modes/interactive/theme/theme-tokens.d.ts +10 -0
  75. package/dist/modes/interactive/theme/theme-tokens.js +1 -1
  76. package/dist/modes/rpc/rpc-types.d.ts +2 -6
  77. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  78. package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
  79. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  80. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  81. package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
  82. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  83. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  84. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  85. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  86. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  87. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  88. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  89. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  90. package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
  91. package/dist/node_modules/@dalcode/dal-learn/src/engine.js +2 -2
  92. package/dist/node_modules/@dalcode/dal-learn/src/index.js +14 -14
  93. package/dist/node_modules/@dalcode/dal-learn/src/lessons.js +4 -4
  94. package/dist/node_modules/@dalcode/dal-learn/src/safety.js +2 -2
  95. package/dist/node_modules/@dalcode/dal-lsp/package.json +4 -4
  96. package/dist/node_modules/@dalcode/dal-mcp/package.json +6 -6
  97. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  98. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
  99. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  100. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +2 -2
  101. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  102. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  103. package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
  104. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  105. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  106. package/dist/node_modules/@dalcode/dal-router/package.json +6 -6
  107. package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
  108. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  109. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  110. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  111. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  112. package/dist/node_modules/@dalcode/dal-sync/package.json +4 -4
  113. package/dist/node_modules/@dalcode/dal-telemetry/package.json +4 -4
  114. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  115. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  116. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  117. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  118. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  119. package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +4 -4
  120. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  121. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  122. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  123. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  124. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -1
  125. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -1
  126. package/dist/node_modules/@earendil-works/pi-ai/package.json +3 -3
  127. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  128. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  129. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  130. package/dist/node_modules/@earendil-works/pi-schema/package.json +1 -1
  131. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  132. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  133. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  134. package/examples/extensions/gondolin/package-lock.json +2 -2
  135. package/examples/extensions/gondolin/package.json +1 -1
  136. package/examples/extensions/with-deps/package-lock.json +2 -2
  137. package/examples/extensions/with-deps/package.json +1 -1
  138. package/npm-shrinkwrap.json +2 -2
  139. package/package.json +1 -1
  140. package/dist/bundle/chunks/sync-ONQZCAYG.js +0 -7
@@ -123,7 +123,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
123
123
  `);ut.writeFileSync(M,P)}T.flush(),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=A,this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length),this.previousViewportTop=Math.max(n,A-t+1),this.positionHardwareCursor(d,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=e,this.previousHeight=t}positionHardwareCursor(e,t){if(!e||t<=0){this.terminal.hideCursor();return}let i=Math.max(0,Math.min(e.row,t-1)),r=Math.max(0,e.col),s=i-this.hardwareCursorRow,n="";s>0?n+=`\x1B[${s}B`:s<0&&(n+=`\x1B[${-s}A`),n+=`\x1B[${r+1}G`,n&&this.terminal.write(n),this.hardwareCursorRow=i,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}};import*as fe from"node:fs";import*as dt from"node:path";import{watch as Gp}from"node:fs";var Yp=5e3;function Qr(e){if(e)try{e.close()}catch{}}h(Qr,"closeWatcher");function Bo(e,t,i){try{let r=Gp(e,t);return r.on("error",i),r}catch{return i(),null}}h(Bo,"watchWithErrorHandler");var Ht=W(la(),1),Xp=W(sa(),1),Qp=W(na(),1),Zp=W(oa(),1),Jp=W(aa(),1),ef=W(ha(),1),tf=W(ua(),1),rf=W(ca(),1),sf=W(da(),1),nf=W(pa(),1),lf=W(fa(),1),of=W(ga(),1),af=W(ma(),1),hf=W(xa(),1),uf=W(ba(),1),cf=W(ya(),1),df=W(ka(),1),pf=W(wa(),1),ff=W(Sa(),1),gf=W(Ca(),1),mf=W(va(),1),xf=W(Ta(),1);function Io(e){if(!(!Number.isInteger(e)||e<0||e>1114111))return String.fromCodePoint(e)}h(Io,"decodeCodePoint");function bf(e){switch(e){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'"}if(e.startsWith("#x")||e.startsWith("#X"))return Io(Number.parseInt(e.slice(2),16));if(e.startsWith("#"))return Io(Number.parseInt(e.slice(1),10))}h(bf,"decodeHtmlEntity");function yf(e,t){let i=e.indexOf(";",t+1);if(i===-1||i-t>16)return;let r=e.slice(t+1,i),s=bf(r);if(s!==void 0)return{text:s,length:i-t+1}}h(yf,"decodeHtmlEntityAt");var kf={python:df.default,java:sf.default,go:tf.default,javascript:nf.default,json:lf.default,cpp:Zp.default,typescript:xf.default,php:cf.default,ruby:pf.default,c:Qp.default,csharp:Jp.default,nix:hf.default,bash:Xp.default,rust:ff.default,scala:gf.default,kotlin:of.default,swift:mf.default,dart:ef.default,groovy:rf.default,perl:uf.default,lua:af.default};for(let[e,t]of Object.entries(kf))Ht.default.registerLanguage(e,t);var Zr;function wf(){return Zr||(Zr=new Promise(e=>{setImmediate(()=>{import("./lib-4AVRLBHM.js").then(()=>e(),()=>{e()})})})),Zr}h(wf,"loadAllHighlightLanguages");var Ro="</span>",Lo="hljs-";function Sf(e){let t=/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(e),i=t?.[1]??t?.[2];if(i){for(let r of i.split(/\s+/))if(r.startsWith(Lo))return r.slice(Lo.length)}}h(Sf,"getScopeFromSpanTag");function Cf(e,t){let i=t[e];if(i)return i;let r=e.indexOf(".");if(r!==-1){let n=t[e.slice(0,r)];if(n)return n}let s=e.indexOf("-");if(s!==-1){let n=t[e.slice(0,s)];if(n)return n}}h(Cf,"getScopeFormatter");function vf(e,t){for(let i=e.length-1;i>=0;i--){let r=e[i];if(!r)continue;let s=Cf(r,t);if(s)return s}return t.default}h(vf,"getActiveFormatter");function Tf(e,t){if(!e.startsWith("<span",t))return!1;let i=e[t+5];return i===">"||i===" "||i===" "||i===`
124
124
  `||i==="\r"}h(Tf,"isSpanOpenTagStart");function Mf(e,t={}){let i="",r="",s=[],n=h(()=>{if(!r)return;let o=vf(s,t);i+=o?r.split(`
125
125
  `).map(a=>a&&o(a)).join(`
126
- `):r,r=""},"flushText"),l=0;for(;l<e.length;){if(Tf(e,l)){let o=e.indexOf(">",l+5);if(o!==-1){n();let a=e.slice(l,o+1),u=Sf(a);s.push(u),l=o+1;continue}}if(e.startsWith(Ro,l)){n(),s.length>0&&s.pop(),l+=Ro.length;continue}if(e[l]==="&"){let o=yf(e,l);if(o){r+=o.text,l+=o.length;continue}}r+=e[l],l++}return n(),i}h(Mf,"renderHighlightedHtml");function Af(e,t={}){let i=t.language?Ht.default.highlight(e,{language:t.language,ignoreIllegals:t.ignoreIllegals}).value:Ht.default.highlightAuto(e,t.languageSubset).value;return Mf(i,t.theme)}h(Af,"highlight");function Bf(e){return Ht.default.getLanguage(e)!==void 0}h(Bf,"supportsLanguage");function If(){return Ht.default.listLanguages().length}h(If,"getHighlightLanguageCount");var X="system",Rf="light/dark",Jr={neutral:{hue:231.49,saturation:{min:.02,max:.08},slot:8},blue:{hue:231.49,saturation:{min:.1,max:.68},slot:4},green:{hue:158.68,saturation:{min:.1,max:.76},slot:2},red:{hue:20,saturation:{min:.1,max:.92},slot:1},yellow:{hue:82.36,saturation:{min:.5,max:1},slot:3},orange:{hue:52,saturation:{min:.12,max:.85},slot:3},violet:{hue:295,saturation:{min:.2,max:.6},slot:5},calamine:{hue:202.43,saturation:{min:.1,max:.74},slot:6},thinkingSlate:{hue:231.49,saturation:{min:.08,max:.2},slot:4},thinkingBlue:{hue:231.49,saturation:{min:.2,max:.45},slot:4},thinkingPeriwinkle:{hue:263.25,saturation:{min:.3,max:.6},slot:6},thinkingViolet:{hue:295,saturation:{min:.4,max:.75},slot:5},thinkingMagenta:{hue:337.5,saturation:{min:.5,max:.85},slot:13},thinkingRed:{hue:20,saturation:{min:.95,max:1},slot:1}},es={selectedBg:"blue",searchMatchBg:"orange",userMessageBg:"blue",customMessageBg:"violet",toolPendingBg:"neutral",toolSuccessBg:"green",toolErrorBg:"red",text:"neutral",userMessageText:"neutral",customMessageText:"neutral",toolTitle:"neutral",syntaxOperator:"neutral",syntaxPunctuation:"neutral",muted:"neutral",dim:"neutral",thinkingText:"neutral",toolOutput:"neutral",mdLinkUrl:"neutral",mdQuote:"neutral",mdQuoteBorder:"neutral",mdHr:"neutral",mdCodeBlockBorder:"neutral",toolDiffContext:"neutral",syntaxComment:"neutral",scrollbarTrack:"neutral",scrollbarThumb:"neutral",searchMatchText:"neutral",borderMuted:"neutral",accent:"violet",borderAccent:"violet",customMessageLabel:"violet",mdCode:"violet",mdListBullet:"violet",syntaxType:"violet",border:"blue",mdLink:"blue",syntaxKeyword:"blue",syntaxVariable:"calamine",success:"green",mdCodeBlock:"green",toolDiffAdded:"green",bashMode:"green",syntaxNumber:"green",error:"red",toolDiffRemoved:"red",warning:"yellow",mdHeading:"yellow",syntaxFunction:"yellow",syntaxString:"orange",thinkingOff:"neutral",thinkingMinimal:"thinkingSlate",thinkingLow:"thinkingBlue",thinkingMedium:"thinkingPeriwinkle",thinkingHigh:"thinkingViolet",thinkingXhigh:"thinkingMagenta",thinkingMax:"thinkingRed"},Eo={syntaxString:2,syntaxNumber:5,searchMatchBg:3},Lf={panel:{dark:{coefficients:[.29131,-.39746,2.33185,-.85524,-1.2076,.86276],reachable:[0,.979]},light:{coefficients:[-3.74073,27.94549,-78.44258,112.6798,-79.60015,22.11277],reachable:[.348,1]}},track:{dark:{coefficients:[.39028,-.23015,.83573,2.43829,-4.38292,2.01582],reachable:[0,.946]},light:{coefficients:[-5.24921,38.37322,-107.28833,152.10005,-106.17127,29.18061],reachable:[.368,1]}},thinking0:{dark:{coefficients:[.52988,-.05809,-.30924,4.63567,-6.52933,2.89108],reachable:[0,.873]},light:{coefficients:[-28.27749,182.85284,-469.62416,603.15916,-384.59976,97.35147],reachable:[.51,1]}},thinking1:{dark:{coefficients:[.55278,-.03667,-.45659,4.95347,-6.90265,3.0706],reachable:[0,.858]},light:{coefficients:[-37.10484,235.86282,-596.62344,754.3633,-474.00763,118.3551],reachable:[.535,1]}},thinking2:{dark:{coefficients:[.57486,-.01765,-.58987,5.25227,-7.27175,3.25532],reachable:[0,.842]},light:{coefficients:[-59.89653,377.05024,-945.07843,1182.03145,-734.96375,181.68658],reachable:[.556,1]}},thinking3:{dark:{coefficients:[.59621,-62e-5,-.71148,5.53588,-7.6392,3.44606],reachable:[0,.827]},light:{coefficients:[-72.07122,445.84082,-1099.57352,1353.88793,-829.53392,202.26164],reachable:[.58,1]}},thinking4:{dark:{coefficients:[.61691,.01462,-.82288,5.80651,-8.00641,3.64333],reachable:[0,.811]},light:{coefficients:[-110.14338,674.21488,-1645.75941,2004.32367,-1215.15899,293.3183],reachable:[.6,1]}},thinking5:{dark:{coefficients:[.63702,.02826,-.92498,6.06465,-8.37246,3.84651],reachable:[0,.795]},light:{coefficients:[-175.47701,1063.54495,-2570.70594,3098.80776,-1860.15527,444.76392],reachable:[.62,1]}},thinking6:{dark:{coefficients:[.65658,.04044,-1.01835,6.30989,-8.73529,4.05439],reachable:[0,.779]},light:{coefficients:[-183.81712,1094.70055,-2602.68539,3088.71276,-1826.91131,430.75931],reachable:[.643,1]}},subtle:{dark:{coefficients:[.56762,-.02475,-.5383,5.12628,-7.10931,3.17324],reachable:[0,.848]},light:{coefficients:[-232.85459,1376.54473,-3249.11801,3827.91186,-2248.29472,526.55751],reachable:[.657,1]}},thumb:{dark:{coefficients:[.60323,.00278,-.73328,5.57157,-7.68067,3.46933],reachable:[0,.823]},light:{coefficients:[-82.89897,511.01355,-1255.98095,1540.76821,-940.68087,228.58523],reachable:[.586,1]}},readable:{dark:{coefficients:[.66937,.04704,-1.06871,6.43941,-8.9332,4.17229],reachable:[0,.77]},light:{coefficients:[-1554.52576,8733.56817,-19604.93507,21977.72696,-12300.99599,2749.81288],reachable:[.751,1]}},emphasis:{dark:{coefficients:[.7303,.07695,-1.31626,7.1681,-10.14436,4.92846],reachable:[0,.712]},light:{coefficients:[-4948.31942,26870.91986,-58334.48399,63280.17197,-34298.01053,7430.30146],reachable:[.811,1]}},textOnPanel:{dark:{coefficients:[.86713,.05232,-.89428,4.79014,-5.5432,1.75023],reachable:[0,.542]},light:{coefficients:[-8570.89457,43954.60805,-90084.00702,92220.6791,-47152.15802,9632.27113],reachable:[.867,1]}},text:{dark:{coefficients:[.89242,.02311,-.44862,2.34417,-.06084,-2.63844],reachable:[0,.5]},light:{coefficients:[-2004.67048,6664.47299,-6060.70202,-1792.61209,5133.82359,-1939.85583],reachable:[.894,1]}}},ue=["toolPendingBg","toolSuccessBg","toolErrorBg"],Pi=["userMessageBg","customMessageBg"],ts=["userMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg","selectedBg","searchMatchBg","customMessageBg"],Ef=["thinkingOff","thinkingMinimal","thinkingLow","thinkingMedium","thinkingHigh","thinkingXhigh","thinkingMax"],Pf=["thinking0","thinking1","thinking2","thinking3","thinking4","thinking5","thinking6"],Ke=h((e,t,i)=>e.map(r=>({token:r,on:t,level:i})),"each"),$i=[...Ke(ts,["background"],"panel"),{token:"text",on:["background"],level:"text"},{token:"text",on:["selectedBg"],level:"textOnPanel"},{token:"userMessageText",on:["userMessageBg"],level:"textOnPanel"},{token:"toolTitle",on:ue,level:"textOnPanel"},...Ke(["accent","success","error","warning"],["background","selectedBg",...ue],"readable"),{token:"muted",on:["background","selectedBg","customMessageBg",...ue],level:"readable"},{token:"dim",on:["background","selectedBg","customMessageBg",...ue],level:"subtle"},{token:"thinkingText",on:["background"],level:"readable"},{token:"customMessageText",on:["customMessageBg",...ue],level:"readable"},{token:"customMessageLabel",on:["background","customMessageBg","selectedBg",...ue],level:"readable"},{token:"toolOutput",on:["background",...ue],level:"readable"},...Ke(["mdHeading","mdLink","mdLinkUrl","mdCode","mdQuote","mdCodeBlockBorder","mdListBullet"],["background",...Pi],"readable"),{token:"mdCodeBlock",on:["background",...Pi,...ue],level:"readable"},...Ke(["toolDiffAdded","toolDiffRemoved","toolDiffContext"],["background",...ue],"readable"),...Ke(["syntaxComment","syntaxKeyword","syntaxFunction","syntaxVariable","syntaxString","syntaxNumber","syntaxType","syntaxOperator","syntaxPunctuation"],["background",...Pi,...ue],"readable"),{token:"searchMatchText",on:["searchMatchBg"],level:"readable"},...Ke(["bashMode","border","borderAccent"],["background"],"readable"),{token:"borderMuted",on:["background"],level:"subtle"},...Ke(["mdQuoteBorder","mdHr"],["background",...Pi,...ue],"readable"),{token:"scrollbarTrack",on:["background"],level:"track"},{token:"scrollbarThumb",on:["scrollbarTrack"],level:"thumb"},...Ef.map((e,t)=>({token:e,on:["background"],level:Pf[t]}))],$f={dark:"readable",light:"subtle"},_f="emphasis",Po=["text","userMessageText","toolTitle"],is=4.5,Of=(()=>{let e=[],t=h(i=>{if(!e.includes(i)){for(let r of $i)if(r.token===i)for(let s of r.on)s!=="background"&&t(s);e.push(i)}},"visit");for(let i of $i)t(i.token);return e})();function pt(e){return Le(xe(e.r,e.g,e.b)).l}h(pt,"oklabLightness");function $o({r:e,g:t,b:i}){let r=h(s=>{let n=s/255;return n<=.04045?n/12.92:((n+.055)/1.055)**2.4},"linear");return .2126*r(e)+.7152*r(t)+.0722*r(i)}h($o,"relativeLuminance");function _i(e,t){let i=$o(e),r=$o(t);return(Math.max(i,r)+.05)/(Math.min(i,r)+.05)}h(_i,"wcagContrast");function _o(e,t){let i={r:255,g:255,b:255},r={r:0,g:0,b:0},s=_i(i,e),n=_i(r,e);if(t){let l=pt(t),o=pt(e);if(Math.abs(l-o)>.05){let a=l>o?"dark":"light";if((a==="dark"?s:n)>=is)return a}}return s>=n?"dark":"light"}h(_o,"terminalAppearance");var Df=h((e,t,i)=>Math.min(i,Math.max(t,e)),"clamp2");function Oo({r:e,g:t,b:i}){return`#${[e,t,i].map(r=>Math.round(r).toString(16).padStart(2,"0")).join("")}`}h(Oo,"hexOf");function Do(e){let t=h(i=>Math.exp(-((i-.5)**2)/.125),"gaussian");return(t(e)-t(0))/(1-t(0))}h(Do,"bellWeight");function Fo({saturation:{min:e,max:t}},i){let r=t>0?e/t:1;return r+(1-r)*Do(i)}h(Fo,"saturationCurve");function No(e,t,i){let r=Lf[e][t];if(!(i<r.reachable[0]||i>r.reachable[1]))return r.coefficients.reduce((s,n,l)=>s+n*i**l,0)}h(No,"levelTarget");function Ff(e){let t=Df(e.saturation??1,0,1),{background:i,foreground:r}=e;if(!i)return Wf(t,e.appearanceHint);let s=e.palette?.length===16?e.palette.map(Ho):void 0,n=_o(i,r),l=n==="dark",o=l?1:0,a=pt(i),u=h((y,w)=>{let S=ei(w),B=Jr[es[y]];if(!s){let{min:A,max:k}=B.saturation;return kt(B.hue,(A+(k-A)*Do(S))*t,S)}return Vo(s[Eo[y]??B.slot],B,S,t)},"paint"),d=h((y,w,S)=>{let B=No(y,n,w);if(B===void 0&&S===0)return;let A=(B??o)-w,k=(No($f[n],n,w)??o)-w,M=Math.abs(A)>Math.abs(k)?A-(A-k)*Math.min(S,1):A;return w+M*(1-Math.max(0,S-1))},"target"),c=l?{r:255,g:255,b:255}:{r:0,g:0,b:0},p=h(y=>_i(c,y)>=is,"readable"),f=h((y,w)=>{let S=u(y,w);if(p(S))return S;let[B,A]=[a,w];for(let k=0;k<20;k++){let M=(B+A)/2;p(u(y,M))?B=M:A=M}return u(y,B)},"limitPanel"),g=h(y=>{let w=new Map([["background",i]]);for(let S of Of){let B=[];for(let k of $i)if(k.token===S)for(let M of k.on){let P=d(k.level,pt(w.get(M)??i),y);if(P===void 0||P<0||P>1)return;B.push(P)}let A=l?Math.max(...B):Math.min(...B);w.set(S,ts.includes(S)?f(S,A):u(S,A))}return w},"solve"),m=0,x=g(0);if(!x){let[y,w]=[0,2];x=g(w);for(let S=0;S<20;S++){let B=(y+w)/2,A=g(B);A?[w,x]=[B,A]:y=B}m=w}let b=x??new Map,v=h(y=>$i.filter(w=>w.token===y).flatMap(w=>w.on.map(S=>b.get(S)??i)),"surfacesOf"),T={};for(let y of Object.keys(es)){let w=b.get(y);T[y]=w?Oo(w):""}for(let y of Po){let w=v(y),S=b.get(y);if(r){let B=w.map(A=>d(_f,pt(A),m));if(B.every(A=>A!==void 0&&A>=0&&A<=1)){let A=l?Math.max(...B):Math.min(...B),k=pt(r);if(l?k>=A:k<=A){T[y]="";continue}S=Vo(Ho(r),Jr.neutral,ei(A),t)}}S&&(T[y]=Oo(Nf(S,w,l)))}return{colors:T,dim:[],appearance:n}}h(Ff,"generateSystemThemeColors");function Wo({r:e,g:t,b:i}){return Ns(xe(e,t,i))}h(Wo,"okhslOf");function Ho(e){return{...Wo(e),chroma:Le(xe(e.r,e.g,e.b)).c}}h(Ho,"sourceOf");function Vo(e,t,i,r){let s=Fo(t,e.l),n=s>0?Math.min(1,Fo(t,i)/s):1,l=kt(e.h,e.s*n*r,i),o=e.chroma*n*r,{l:a,c:u}=Le(l);return u<=o?l:ye(ii(a,o,e.h))}h(Vo,"anchored");function Nf(e,t,i){let r=h(c=>t.every(p=>_i(c,p)>=is),"meets");if(r(e))return e;let{h:s,s:n,l}=Wo(e),o=h(c=>kt(s,n,c),"at2"),a=i?1:0;if(!r(o(a)))return o(a);let[u,d]=[l,a];for(let c=0;c<20;c++){let p=(u+d)/2;r(o(p))?d=p:u=p}return o(d)}h(Nf,"withTextContrast");function Wf(e,t){let i={},r=[];for(let[s,n]of Object.entries(es)){if(ts.includes(s)){i[s]="";continue}let l=n==="neutral";i[s]=!l&&e>0?Eo[s]??Jr[n].slot:"",l&&!Po.includes(s)&&r.push(s)}return{colors:i,dim:r,appearance:t}}h(Wf,"indexedColors");function Hf(e){for(let[t,i]of Object.entries(e)){if(i.fallback===void 0)continue;let r=e[i.fallback];if(r===void 0)throw new Error(`Theme token ${t} has unknown fallback ${i.fallback}`);if(r.slot!==i.slot)throw new Error(`Theme token ${t} has fallback ${i.fallback} in a different color slot`)}return e}h(Hf,"defineThemeTokens");var rs=Hf({accent:{slot:"foreground",description:"Primary accent color (logo, selected items, cursor)"},border:{slot:"foreground",description:"Normal borders"},borderAccent:{slot:"foreground",description:"Highlighted borders"},borderMuted:{slot:"foreground",description:"Subtle borders"},success:{slot:"foreground",description:"Success states"},error:{slot:"foreground",description:"Error states"},warning:{slot:"foreground",description:"Warning states"},muted:{slot:"foreground",description:"Secondary/dimmed text"},dim:{slot:"foreground",description:"Very dimmed text (more subtle than muted)"},text:{slot:"foreground",description:"Default text color (usually empty string)"},thinkingText:{slot:"foreground",description:"Thinking block text color"},scrollbarTrack:{slot:"foreground",description:"Fullscreen scrollbar track foreground (falls back to muted when omitted)",fallback:"muted"},scrollbarThumb:{slot:"foreground",description:"Fullscreen scrollbar thumb foreground (falls back to text when omitted)",fallback:"text"},selectedBg:{slot:"background",description:"Selected item background"},searchMatchBg:{slot:"background",description:"Transcript search match background and current-match text (falls back to selectedBg when omitted)",fallback:"selectedBg"},searchMatchText:{slot:"foreground",description:"Transcript search match text and current-match background (falls back to text when omitted)",fallback:"text"},userMessageBg:{slot:"background",description:"User message background"},userMessageText:{slot:"foreground",description:"User message text color"},customMessageBg:{slot:"background",description:"Custom message background (hook-injected messages)"},customMessageText:{slot:"foreground",description:"Custom message text color"},customMessageLabel:{slot:"foreground",description:"Custom message type label color"},toolPendingBg:{slot:"background",description:"Tool execution box (pending state)"},toolSuccessBg:{slot:"background",description:"Tool execution box (success state)"},toolErrorBg:{slot:"background",description:"Tool execution box (error state)"},toolTitle:{slot:"foreground",description:"Tool execution box title color"},toolOutput:{slot:"foreground",description:"Tool execution box output text color"},mdHeading:{slot:"foreground",description:"Markdown heading text"},mdLink:{slot:"foreground",description:"Markdown link text"},mdLinkUrl:{slot:"foreground",description:"Markdown link URL"},mdCode:{slot:"foreground",description:"Markdown inline code"},mdCodeBlock:{slot:"foreground",description:"Markdown code block content"},mdCodeBlockBorder:{slot:"foreground",description:"Markdown code block fences"},mdQuote:{slot:"foreground",description:"Markdown blockquote text"},mdQuoteBorder:{slot:"foreground",description:"Markdown blockquote border"},mdHr:{slot:"foreground",description:"Markdown horizontal rule"},mdListBullet:{slot:"foreground",description:"Markdown list bullets/numbers"},toolDiffAdded:{slot:"foreground",description:"Added lines in tool diffs"},toolDiffRemoved:{slot:"foreground",description:"Removed lines in tool diffs"},toolDiffContext:{slot:"foreground",description:"Context lines in tool diffs"},syntaxComment:{slot:"foreground",description:"Syntax highlighting: comments"},syntaxKeyword:{slot:"foreground",description:"Syntax highlighting: keywords"},syntaxFunction:{slot:"foreground",description:"Syntax highlighting: function names"},syntaxVariable:{slot:"foreground",description:"Syntax highlighting: variable names"},syntaxString:{slot:"foreground",description:"Syntax highlighting: string literals"},syntaxNumber:{slot:"foreground",description:"Syntax highlighting: number literals"},syntaxType:{slot:"foreground",description:"Syntax highlighting: type names"},syntaxOperator:{slot:"foreground",description:"Syntax highlighting: operators"},syntaxPunctuation:{slot:"foreground",description:"Syntax highlighting: punctuation"},thinkingOff:{slot:"foreground",description:"Thinking level border: off"},thinkingMinimal:{slot:"foreground",description:"Thinking level border: minimal"},thinkingLow:{slot:"foreground",description:"Thinking level border: low"},thinkingMedium:{slot:"foreground",description:"Thinking level border: medium"},thinkingHigh:{slot:"foreground",description:"Thinking level border: high"},thinkingXhigh:{slot:"foreground",description:"Thinking level border: xhigh"},thinkingMax:{slot:"foreground",description:"Thinking level border: max (falls back to thinkingXhigh when omitted)",fallback:"thinkingXhigh"},bashMode:{slot:"foreground",description:"Editor border color in bash mode"}}),ss;function Vf(e){ss=e}h(Vf,"setThemeJsonValidator");function ns(e,t,i=new Set){if(typeof e=="number"||e===""||e.startsWith("#")||/^ok(lch|hsl)\(/i.test(e))return e;if(i.has(e))throw new Error(`Circular variable reference detected: ${e}`);if(!(e in t))throw new Error(`Variable reference not found: ${e}`);return i.add(e),ns(t[e],t,i)}h(ns,"resolveVarRefs");function Kf(e,t={}){let i={};for(let[r,s]of Object.entries(e))i[r]=ns(s,t);return i}h(Kf,"resolveThemeColors");function ls(e){let t={...e};for(let[i,r]of Object.entries(rs)){if(!("fallback"in r))continue;let s=i;if(t[s]!==void 0)continue;let n=r.fallback,l=t[n];if(l===void 0)throw new Error(`Theme token ${i} has unresolved fallback ${r.fallback}`);t[s]=l}return t}h(ls,"withThemeTokenFallbacks");var Oi={},os=!1,Ko;function qf(e){Oi={...e},os=!1}h(qf,"setTerminalColors");function Uf(e){Ko=e}h(Uf,"setTerminalColorScheme");function zf(){os=!0}h(zf,"markTerminalColorsPending");var jf={dark:{foreground:ve("#e5e5e7"),background:ve("#000000")},light:{foreground:ve("#000000"),background:ve("#ffffff")}};function qo(e){let t=e.filter(i=>i.kind!=="indexed"||i.index>=16);if(t.length!==0)return t.reduce((i,r)=>i+Le(r).l,0)/t.length}h(qo,"averageLightness");function Gf(e,t){let i=qo(e),r=qo(t);if(i!==void 0&&r!==void 0)return r<i?"dark":"light";if(r!==void 0)return r<.5?"dark":"light";if(i!==void 0)return i>.5?"dark":"light"}h(Gf,"detectAppearance");var as=class{static{h(this,"Theme")}name;sourcePath;sourceInfo;mode;fgAnsi=new Map;bgAnsi=new Map;concreteColors={};defaultForegroundTokens=[];defaultBackgroundTokens=[];dimTokens;ownAppearance;resolvedColors;constructor(e,t,i,r={}){this.name=r.name,this.sourcePath=r.sourcePath,this.sourceInfo=r.sourceInfo,this.mode=i,this.dimTokens=new Set(r.dim);let{fgColors:s,bgColors:n}=cs(ls({...e,...t})),l=[],o=[],a=h((u,d,c)=>{if(d==="")return(c?this.defaultBackgroundTokens:this.defaultForegroundTokens).push(u),c?"\x1B[49m":"\x1B[39m";let p=ve(d);return this.concreteColors[u]=p,(c?o:l).push(p),c?St(p,i):wt(p,i)},"addToken");for(let[u,d]of Object.entries(s))this.fgAnsi.set(u,a(u,d,!1));for(let[u,d]of Object.entries(n))this.bgAnsi.set(u,a(u,d,!0));this.ownAppearance=r.appearance??Gf(l,o)}get appearance(){return this.ownAppearance??ps()}get colors(){let e=Oi;if(this.resolvedColors?.terminal!==e){let t=jf[this.appearance],i=h((l,o)=>l?xe(l.r,l.g,l.b):o,"toColor"),r=i(e.foreground,t.foreground),s=i(e.background,t.background),n={...this.concreteColors};for(let l of this.defaultForegroundTokens)n[l]=r;for(let l of this.defaultBackgroundTokens)n[l]=s;for(let l of this.dimTokens){let o=n[l];o&&(n[l]=Qi(o,s,.4))}this.resolvedColors={terminal:e,colors:Object.freeze(n)}}return this.resolvedColors.colors}style(e,t){let{fg:i,bg:r}=t;return typeof i=="string"&&this.dimTokens.has(i)&&(t={...t,dim:!0}),Zi(e,i===void 0?void 0:typeof i=="string"?this.tokenAnsi(this.fgAnsi,i):wt(i,this.mode),r===void 0?void 0:typeof r=="string"?this.tokenAnsi(this.bgAnsi,r):St(r,this.mode),t)}fg(e,t){let i=this.tokenAnsi(this.fgAnsi,e);return this.dimTokens.has(e)?`${i}\x1B[2m${t}\x1B[22;39m`:`${i}${t}\x1B[39m`}bg(e,t){return`${this.tokenAnsi(this.bgAnsi,e)}${t}\x1B[49m`}tokenAnsi(e,t){let i=e.get(t);if(i===void 0)throw new Error(`Unknown theme color: ${t}`);return i}bold(e){return xt.bold(e)}italic(e){return xt.italic(e)}underline(e){return xt.underline(e)}inverse(e){return xt.inverse(e)}strikethrough(e){return xt.strikethrough(e)}getFgAnsi(e){let t=this.tokenAnsi(this.fgAnsi,e);return this.dimTokens.has(e)?`${t}\x1B[2m`:t}getBgAnsi(e){return this.tokenAnsi(this.bgAnsi,e)}getColorMode(){return this.mode}getThinkingBorderColor(e){switch(e){case"off":return t=>this.fg("thinkingOff",t);case"minimal":return t=>this.fg("thinkingMinimal",t);case"low":return t=>this.fg("thinkingLow",t);case"medium":return t=>this.fg("thinkingMedium",t);case"high":return t=>this.fg("thinkingHigh",t);case"xhigh":return t=>this.fg("thinkingXhigh",t);case"max":return t=>this.fg("thinkingMax",t);default:return t=>this.fg("thinkingOff",t)}}getBashModeBorderColor(){return e=>this.fg("bashMode",e)}},hs;function Uo(){if(!hs){let e=ws(),t=dt.join(e,"dark.json"),i=dt.join(e,"light.json");hs={dark:JSON.parse(Ni(fe.readFileSync(t,"utf-8"))),light:JSON.parse(Ni(fe.readFileSync(i,"utf-8")))}}return hs}h(Uo,"getBuiltinThemes");function Yf(){return zo().map(({name:e})=>e)}h(Yf,"getAvailableThemes");function zo(){let e=ws(),t=[],i=new Set,r=h(s=>{i.has(s.name)||(i.add(s.name),t.push(s))},"addTheme");r({name:X,path:void 0});for(let s of Object.keys(Uo()))r({name:s,path:dt.join(e,`${s}.json`)});for(let s of Xf())r(s);for(let[s,n]of mt.entries())r({name:s,path:n.sourcePath});return t.sort((s,n)=>s.name===X?-1:n.name===X?1:s.name.localeCompare(n.name))}h(zo,"getAvailableThemesWithPaths");function Xf(){let e=Fi(),t=[];if(!fe.existsSync(e))return t;for(let i of fe.readdirSync(e)){if(!i.endsWith(".json"))continue;let r=dt.join(e,i);try{let s=ds(r);s.name&&t.push({name:s.name,path:r})}catch{}}return t}h(Xf,"getCustomThemeInfos");function Qf(e){if(e.includes("/"))throw new Error(`Invalid theme name "${e}": theme names cannot contain "/" because it is reserved for automatic light/dark theme settings.`)}h(Qf,"assertThemeNameIsValid");function Zf(e,t){if(ss)return ss(e,t);if(typeof t!="object"||t===null||!("colors"in t))throw new Error(`Invalid theme "${e}": expected an object with a "colors" map.`);return t}h(Zf,"parseThemeJson");function us(e,t){let i;try{i=JSON.parse(Ni(t))}catch(r){throw new Error(`Failed to parse theme ${e}: ${r}`)}return Zf(e,i)}h(us,"parseThemeJsonContent");function jo(e){let t=Uo();if(e in t)return t[e];let i=mt.get(e);if(i?.sourcePath){let l=fe.readFileSync(i.sourcePath,"utf-8");return us(i.sourcePath,l)}if(i)throw new Error(`Theme "${e}" does not have a source path for export`);let r=Fi(),s=dt.join(r,`${e}.json`);if(!fe.existsSync(s))throw new Error(`Theme not found: ${e}`);let n=fe.readFileSync(s,"utf-8");return us(e,n)}h(jo,"loadThemeJson");function cs(e){let t={},i={};for(let[r,s]of Object.entries(e))rs[r].slot==="background"?i[r]=s:t[r]=s;return{fgColors:t,bgColors:i}}h(cs,"splitThemeColors");function Go(e,t,i){let r=t??mi(),s=ls(Kf(e.colors,e.vars)),{fgColors:n,bgColors:l}=cs(s);return new as(n,l,r,{name:e.name,sourcePath:i,appearance:e.appearance})}h(Go,"createTheme");function Jf(e){let t=Ff({...Oi,saturation:os?0:1,appearanceHint:ps()}),{fgColors:i,bgColors:r}=cs(ls(t.colors));return new as(i,r,e??mi(),{name:X,appearance:t.appearance,dim:t.dim})}h(Jf,"createSystemTheme");function ds(e,t){let i=fe.readFileSync(e,"utf-8"),r=us(e,i);return Go(r,t,e)}h(ds,"loadThemeFromPath");function ft(e,t){if(e===X)return Jf(t);let i=mt.get(e);if(i)return i;let r=jo(e);return Go(r,t)}h(ft,"loadTheme");function eg(e){try{return ft(e)}catch{return}}h(eg,"getThemeByName");function Yo(e){if(!e)return;let t=e.indexOf("/");if(t===-1||e.indexOf("/",t+1)!==-1)return;let i=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!(!i||!r))return{lightTheme:i,darkTheme:r}}h(Yo,"parseAutoThemeSetting");function tg(e,t){let i=Yo(e);if(i)return t==="light"?i.lightTheme:i.darkTheme;if(!e?.includes("/")&&typeof e=="string")return e}h(tg,"resolveThemeSetting");function ig(e=process.env){let t=e.COLORFGBG?.split(";").at(-1)?.trim();if(!t||!/^\d{1,2}$/.test(t))return;let i=Number(t);if(!(i>15))return i<=6||i===8?"dark":"light"}h(ig,"detectColorFgBgTheme");function rg(e={},t,i=process.env){let{background:r,foreground:s}=e;return r?_o(r,s):t??ig(i)??"dark"}h(rg,"detectTerminalTheme");function ps(){return rg(Oi,Ko)}h(ps,"getTerminalTheme");var fs=Symbol.for("@earendil-works/pi-coding-agent:theme"),sg=Symbol.for("@mariozechner/pi-coding-agent:theme"),O=new Proxy({},{get(e,t){let i=globalThis[fs];if(!i)throw new Error("Theme not initialized. Call initTheme() first.");return i[t]}});function ng(){return globalThis[fs]}h(ng,"getGlobalTheme");function gt(e){globalThis[fs]=e,globalThis[sg]=e}h(gt,"setGlobalTheme");var Z,Vt,qe,Ue,mt=new Map;function lg(e){mt.clear();for(let t of e)t.name&&(Qf(t.name),mt.set(t.name,t))}h(lg,"setRegisteredThemes");function og(e,t=!1){let i=e??X;Z=i;try{gt(ft(i)),t&&Xo()}catch{Z=X,gt(ft(X))}}h(og,"initTheme");function ag(e,t=!1){Z=e;try{return gt(ft(e)),t&&Xo(),Ue&&Ue(),{success:!0}}catch(i){return Z=X,gt(ft(X)),{success:!1,error:i instanceof Error?i.message:String(i)}}}h(ag,"setTheme");function hg(e){gt(e),Z="<in-memory>",gs(),Ue&&Ue()}h(hg,"setThemeInstance");function ug(e){Ue=e}h(ug,"onThemeChange");function Xo(){if(gs(),!Z||Z==="dark"||Z==="light"||Z===X)return;let e=Fi(),t=Z,i=`${t}.json`,r=dt.join(e,i);if(!fe.existsSync(r))return;let s=h(()=>{qe&&clearTimeout(qe),qe=setTimeout(()=>{if(qe=void 0,Z===t&&fe.existsSync(r))try{let n=ds(r);mt.set(t,n),gt(n),Ue&&Ue()}catch{}},100)},"scheduleReload");Vt=Bo(e,(n,l)=>{if(Z===t){if(!l){s();return}l===i&&s()}},()=>{Qr(Vt),Vt=void 0})??void 0}h(Xo,"startThemeWatcher");function gs(){qe&&(clearTimeout(qe),qe=void 0),Qr(Vt),Vt=void 0}h(gs,"stopThemeWatcher");function cg(e){let t=ft(e??Z??X).colors;return Object.fromEntries(Object.entries(t).map(([i,r])=>[i,ri(r)]))}h(cg,"getResolvedThemeColors");function dg(e){let t=e??Z??X;if(t===X)return{};try{let i=jo(t),r=i.export;if(!r)return{};let s=i.vars??{},n=h(l=>{if(l===void 0)return;let o=ns(l,s);if(typeof o=="number")return ri(ti(o));if(o!=="")return/^okhsl\(/i.test(o)?ri(ve(o)):o},"resolve");return{pageBg:n(r.pageBg),cardBg:n(r.cardBg),infoBg:n(r.infoBg)}}catch{return{}}}h(dg,"getThemeExportColors");var Qo,ms;function pg(e){return{keyword:h(t=>e.fg("syntaxKeyword",t),"keyword"),built_in:h(t=>e.fg("syntaxType",t),"built_in"),literal:h(t=>e.fg("syntaxNumber",t),"literal"),number:h(t=>e.fg("syntaxNumber",t),"number"),regexp:h(t=>e.fg("syntaxString",t),"regexp"),string:h(t=>e.fg("syntaxString",t),"string"),subst:h(t=>e.fg("text",t),"subst"),comment:h(t=>e.fg("syntaxComment",t),"comment"),doctag:h(t=>e.fg("syntaxComment",t),"doctag"),meta:h(t=>e.fg("muted",t),"meta"),function:h(t=>e.fg("syntaxFunction",t),"function"),title:h(t=>e.fg("syntaxFunction",t),"title"),class:h(t=>e.fg("syntaxType",t),"class"),type:h(t=>e.fg("syntaxType",t),"type"),tag:h(t=>e.fg("syntaxPunctuation",t),"tag"),name:h(t=>e.fg("syntaxKeyword",t),"name"),attr:h(t=>e.fg("syntaxVariable",t),"attr"),variable:h(t=>e.fg("syntaxVariable",t),"variable"),params:h(t=>e.fg("syntaxVariable",t),"params"),operator:h(t=>e.fg("syntaxOperator",t),"operator"),punctuation:h(t=>e.fg("syntaxPunctuation",t),"punctuation"),emphasis:h(t=>e.italic(t),"emphasis"),strong:h(t=>e.bold(t),"strong"),link:h(t=>e.underline(t),"link"),addition:h(t=>e.fg("toolDiffAdded",t),"addition"),deletion:h(t=>e.fg("toolDiffRemoved",t),"deletion")}}h(pg,"buildCliHighlightTheme");function fg(e){return(Qo!==e||!ms)&&(Qo=e,ms=pg(e)),ms}h(fg,"getCliHighlightTheme");function xs(e,t){let i=t&&Bf(t)?t:void 0;if(!i)return e.split(`
126
+ `):r,r=""},"flushText"),l=0;for(;l<e.length;){if(Tf(e,l)){let o=e.indexOf(">",l+5);if(o!==-1){n();let a=e.slice(l,o+1),u=Sf(a);s.push(u),l=o+1;continue}}if(e.startsWith(Ro,l)){n(),s.length>0&&s.pop(),l+=Ro.length;continue}if(e[l]==="&"){let o=yf(e,l);if(o){r+=o.text,l+=o.length;continue}}r+=e[l],l++}return n(),i}h(Mf,"renderHighlightedHtml");function Af(e,t={}){let i=t.language?Ht.default.highlight(e,{language:t.language,ignoreIllegals:t.ignoreIllegals}).value:Ht.default.highlightAuto(e,t.languageSubset).value;return Mf(i,t.theme)}h(Af,"highlight");function Bf(e){return Ht.default.getLanguage(e)!==void 0}h(Bf,"supportsLanguage");function If(){return Ht.default.listLanguages().length}h(If,"getHighlightLanguageCount");var X="system",Rf="light/dark",Jr={neutral:{hue:231.49,saturation:{min:.02,max:.08},slot:8},blue:{hue:231.49,saturation:{min:.1,max:.68},slot:4},green:{hue:158.68,saturation:{min:.1,max:.76},slot:2},red:{hue:20,saturation:{min:.1,max:.92},slot:1},yellow:{hue:82.36,saturation:{min:.5,max:1},slot:3},orange:{hue:52,saturation:{min:.12,max:.85},slot:3},violet:{hue:295,saturation:{min:.2,max:.6},slot:5},calamine:{hue:202.43,saturation:{min:.1,max:.74},slot:6},thinkingSlate:{hue:231.49,saturation:{min:.08,max:.2},slot:4},thinkingBlue:{hue:231.49,saturation:{min:.2,max:.45},slot:4},thinkingPeriwinkle:{hue:263.25,saturation:{min:.3,max:.6},slot:6},thinkingViolet:{hue:295,saturation:{min:.4,max:.75},slot:5},thinkingMagenta:{hue:337.5,saturation:{min:.5,max:.85},slot:13},thinkingRed:{hue:20,saturation:{min:.95,max:1},slot:1}},es={selectedBg:"blue",searchMatchBg:"orange",userMessageBg:"blue",customMessageBg:"violet",toolPendingBg:"neutral",toolSuccessBg:"green",toolErrorBg:"red",toolDiffAddedBg:"green",toolDiffRemovedBg:"red",text:"neutral",userMessageText:"neutral",customMessageText:"neutral",toolTitle:"neutral",syntaxOperator:"neutral",syntaxPunctuation:"neutral",muted:"neutral",dim:"neutral",thinkingText:"neutral",toolOutput:"neutral",mdLinkUrl:"neutral",mdQuote:"neutral",mdQuoteBorder:"neutral",mdHr:"neutral",mdCodeBlockBorder:"neutral",toolDiffContext:"neutral",syntaxComment:"neutral",scrollbarTrack:"neutral",scrollbarThumb:"neutral",searchMatchText:"neutral",borderMuted:"neutral",accent:"violet",borderAccent:"violet",customMessageLabel:"violet",mdCode:"violet",mdListBullet:"violet",syntaxType:"violet",border:"blue",mdLink:"blue",syntaxKeyword:"blue",syntaxVariable:"calamine",success:"green",mdCodeBlock:"green",toolDiffAdded:"green",bashMode:"green",syntaxNumber:"green",error:"red",toolDiffRemoved:"red",warning:"yellow",mdHeading:"yellow",syntaxFunction:"yellow",syntaxString:"orange",thinkingOff:"neutral",thinkingMinimal:"thinkingSlate",thinkingLow:"thinkingBlue",thinkingMedium:"thinkingPeriwinkle",thinkingHigh:"thinkingViolet",thinkingXhigh:"thinkingMagenta",thinkingMax:"thinkingRed"},Eo={syntaxString:2,syntaxNumber:5,searchMatchBg:3},Lf={panel:{dark:{coefficients:[.29131,-.39746,2.33185,-.85524,-1.2076,.86276],reachable:[0,.979]},light:{coefficients:[-3.74073,27.94549,-78.44258,112.6798,-79.60015,22.11277],reachable:[.348,1]}},track:{dark:{coefficients:[.39028,-.23015,.83573,2.43829,-4.38292,2.01582],reachable:[0,.946]},light:{coefficients:[-5.24921,38.37322,-107.28833,152.10005,-106.17127,29.18061],reachable:[.368,1]}},thinking0:{dark:{coefficients:[.52988,-.05809,-.30924,4.63567,-6.52933,2.89108],reachable:[0,.873]},light:{coefficients:[-28.27749,182.85284,-469.62416,603.15916,-384.59976,97.35147],reachable:[.51,1]}},thinking1:{dark:{coefficients:[.55278,-.03667,-.45659,4.95347,-6.90265,3.0706],reachable:[0,.858]},light:{coefficients:[-37.10484,235.86282,-596.62344,754.3633,-474.00763,118.3551],reachable:[.535,1]}},thinking2:{dark:{coefficients:[.57486,-.01765,-.58987,5.25227,-7.27175,3.25532],reachable:[0,.842]},light:{coefficients:[-59.89653,377.05024,-945.07843,1182.03145,-734.96375,181.68658],reachable:[.556,1]}},thinking3:{dark:{coefficients:[.59621,-62e-5,-.71148,5.53588,-7.6392,3.44606],reachable:[0,.827]},light:{coefficients:[-72.07122,445.84082,-1099.57352,1353.88793,-829.53392,202.26164],reachable:[.58,1]}},thinking4:{dark:{coefficients:[.61691,.01462,-.82288,5.80651,-8.00641,3.64333],reachable:[0,.811]},light:{coefficients:[-110.14338,674.21488,-1645.75941,2004.32367,-1215.15899,293.3183],reachable:[.6,1]}},thinking5:{dark:{coefficients:[.63702,.02826,-.92498,6.06465,-8.37246,3.84651],reachable:[0,.795]},light:{coefficients:[-175.47701,1063.54495,-2570.70594,3098.80776,-1860.15527,444.76392],reachable:[.62,1]}},thinking6:{dark:{coefficients:[.65658,.04044,-1.01835,6.30989,-8.73529,4.05439],reachable:[0,.779]},light:{coefficients:[-183.81712,1094.70055,-2602.68539,3088.71276,-1826.91131,430.75931],reachable:[.643,1]}},subtle:{dark:{coefficients:[.56762,-.02475,-.5383,5.12628,-7.10931,3.17324],reachable:[0,.848]},light:{coefficients:[-232.85459,1376.54473,-3249.11801,3827.91186,-2248.29472,526.55751],reachable:[.657,1]}},thumb:{dark:{coefficients:[.60323,.00278,-.73328,5.57157,-7.68067,3.46933],reachable:[0,.823]},light:{coefficients:[-82.89897,511.01355,-1255.98095,1540.76821,-940.68087,228.58523],reachable:[.586,1]}},readable:{dark:{coefficients:[.66937,.04704,-1.06871,6.43941,-8.9332,4.17229],reachable:[0,.77]},light:{coefficients:[-1554.52576,8733.56817,-19604.93507,21977.72696,-12300.99599,2749.81288],reachable:[.751,1]}},emphasis:{dark:{coefficients:[.7303,.07695,-1.31626,7.1681,-10.14436,4.92846],reachable:[0,.712]},light:{coefficients:[-4948.31942,26870.91986,-58334.48399,63280.17197,-34298.01053,7430.30146],reachable:[.811,1]}},textOnPanel:{dark:{coefficients:[.86713,.05232,-.89428,4.79014,-5.5432,1.75023],reachable:[0,.542]},light:{coefficients:[-8570.89457,43954.60805,-90084.00702,92220.6791,-47152.15802,9632.27113],reachable:[.867,1]}},text:{dark:{coefficients:[.89242,.02311,-.44862,2.34417,-.06084,-2.63844],reachable:[0,.5]},light:{coefficients:[-2004.67048,6664.47299,-6060.70202,-1792.61209,5133.82359,-1939.85583],reachable:[.894,1]}}},ue=["toolPendingBg","toolSuccessBg","toolErrorBg"],Pi=["userMessageBg","customMessageBg"],ts=["userMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg","selectedBg","searchMatchBg","customMessageBg","toolDiffAddedBg","toolDiffRemovedBg"],Ef=["thinkingOff","thinkingMinimal","thinkingLow","thinkingMedium","thinkingHigh","thinkingXhigh","thinkingMax"],Pf=["thinking0","thinking1","thinking2","thinking3","thinking4","thinking5","thinking6"],Ke=h((e,t,i)=>e.map(r=>({token:r,on:t,level:i})),"each"),$i=[...Ke(ts,["background"],"panel"),{token:"text",on:["background"],level:"text"},{token:"text",on:["selectedBg"],level:"textOnPanel"},{token:"userMessageText",on:["userMessageBg"],level:"textOnPanel"},{token:"toolTitle",on:ue,level:"textOnPanel"},...Ke(["accent","success","error","warning"],["background","selectedBg",...ue],"readable"),{token:"muted",on:["background","selectedBg","customMessageBg",...ue],level:"readable"},{token:"dim",on:["background","selectedBg","customMessageBg",...ue],level:"subtle"},{token:"thinkingText",on:["background"],level:"readable"},{token:"customMessageText",on:["customMessageBg",...ue],level:"readable"},{token:"customMessageLabel",on:["background","customMessageBg","selectedBg",...ue],level:"readable"},{token:"toolOutput",on:["background",...ue],level:"readable"},...Ke(["mdHeading","mdLink","mdLinkUrl","mdCode","mdQuote","mdCodeBlockBorder","mdListBullet"],["background",...Pi],"readable"),{token:"mdCodeBlock",on:["background",...Pi,...ue],level:"readable"},...Ke(["toolDiffAdded","toolDiffRemoved","toolDiffContext"],["background",...ue],"readable"),{token:"toolDiffAdded",on:["toolDiffAddedBg"],level:"readable"},{token:"toolDiffRemoved",on:["toolDiffRemovedBg"],level:"readable"},...Ke(["syntaxComment","syntaxKeyword","syntaxFunction","syntaxVariable","syntaxString","syntaxNumber","syntaxType","syntaxOperator","syntaxPunctuation"],["background",...Pi,...ue],"readable"),{token:"searchMatchText",on:["searchMatchBg"],level:"readable"},...Ke(["bashMode","border","borderAccent"],["background"],"readable"),{token:"borderMuted",on:["background"],level:"subtle"},...Ke(["mdQuoteBorder","mdHr"],["background",...Pi,...ue],"readable"),{token:"scrollbarTrack",on:["background"],level:"track"},{token:"scrollbarThumb",on:["scrollbarTrack"],level:"thumb"},...Ef.map((e,t)=>({token:e,on:["background"],level:Pf[t]}))],$f={dark:"readable",light:"subtle"},_f="emphasis",Po=["text","userMessageText","toolTitle"],is=4.5,Of=(()=>{let e=[],t=h(i=>{if(!e.includes(i)){for(let r of $i)if(r.token===i)for(let s of r.on)s!=="background"&&t(s);e.push(i)}},"visit");for(let i of $i)t(i.token);return e})();function pt(e){return Le(xe(e.r,e.g,e.b)).l}h(pt,"oklabLightness");function $o({r:e,g:t,b:i}){let r=h(s=>{let n=s/255;return n<=.04045?n/12.92:((n+.055)/1.055)**2.4},"linear");return .2126*r(e)+.7152*r(t)+.0722*r(i)}h($o,"relativeLuminance");function _i(e,t){let i=$o(e),r=$o(t);return(Math.max(i,r)+.05)/(Math.min(i,r)+.05)}h(_i,"wcagContrast");function _o(e,t){let i={r:255,g:255,b:255},r={r:0,g:0,b:0},s=_i(i,e),n=_i(r,e);if(t){let l=pt(t),o=pt(e);if(Math.abs(l-o)>.05){let a=l>o?"dark":"light";if((a==="dark"?s:n)>=is)return a}}return s>=n?"dark":"light"}h(_o,"terminalAppearance");var Df=h((e,t,i)=>Math.min(i,Math.max(t,e)),"clamp2");function Oo({r:e,g:t,b:i}){return`#${[e,t,i].map(r=>Math.round(r).toString(16).padStart(2,"0")).join("")}`}h(Oo,"hexOf");function Do(e){let t=h(i=>Math.exp(-((i-.5)**2)/.125),"gaussian");return(t(e)-t(0))/(1-t(0))}h(Do,"bellWeight");function Fo({saturation:{min:e,max:t}},i){let r=t>0?e/t:1;return r+(1-r)*Do(i)}h(Fo,"saturationCurve");function No(e,t,i){let r=Lf[e][t];if(!(i<r.reachable[0]||i>r.reachable[1]))return r.coefficients.reduce((s,n,l)=>s+n*i**l,0)}h(No,"levelTarget");function Ff(e){let t=Df(e.saturation??1,0,1),{background:i,foreground:r}=e;if(!i)return Wf(t,e.appearanceHint);let s=e.palette?.length===16?e.palette.map(Ho):void 0,n=_o(i,r),l=n==="dark",o=l?1:0,a=pt(i),u=h((y,w)=>{let S=ei(w),B=Jr[es[y]];if(!s){let{min:A,max:k}=B.saturation;return kt(B.hue,(A+(k-A)*Do(S))*t,S)}return Vo(s[Eo[y]??B.slot],B,S,t)},"paint"),d=h((y,w,S)=>{let B=No(y,n,w);if(B===void 0&&S===0)return;let A=(B??o)-w,k=(No($f[n],n,w)??o)-w,M=Math.abs(A)>Math.abs(k)?A-(A-k)*Math.min(S,1):A;return w+M*(1-Math.max(0,S-1))},"target"),c=l?{r:255,g:255,b:255}:{r:0,g:0,b:0},p=h(y=>_i(c,y)>=is,"readable"),f=h((y,w)=>{let S=u(y,w);if(p(S))return S;let[B,A]=[a,w];for(let k=0;k<20;k++){let M=(B+A)/2;p(u(y,M))?B=M:A=M}return u(y,B)},"limitPanel"),g=h(y=>{let w=new Map([["background",i]]);for(let S of Of){let B=[];for(let k of $i)if(k.token===S)for(let M of k.on){let P=d(k.level,pt(w.get(M)??i),y);if(P===void 0||P<0||P>1)return;B.push(P)}let A=l?Math.max(...B):Math.min(...B);w.set(S,ts.includes(S)?f(S,A):u(S,A))}return w},"solve"),m=0,x=g(0);if(!x){let[y,w]=[0,2];x=g(w);for(let S=0;S<20;S++){let B=(y+w)/2,A=g(B);A?[w,x]=[B,A]:y=B}m=w}let b=x??new Map,v=h(y=>$i.filter(w=>w.token===y).flatMap(w=>w.on.map(S=>b.get(S)??i)),"surfacesOf"),T={};for(let y of Object.keys(es)){let w=b.get(y);T[y]=w?Oo(w):""}for(let y of Po){let w=v(y),S=b.get(y);if(r){let B=w.map(A=>d(_f,pt(A),m));if(B.every(A=>A!==void 0&&A>=0&&A<=1)){let A=l?Math.max(...B):Math.min(...B),k=pt(r);if(l?k>=A:k<=A){T[y]="";continue}S=Vo(Ho(r),Jr.neutral,ei(A),t)}}S&&(T[y]=Oo(Nf(S,w,l)))}return{colors:T,dim:[],appearance:n}}h(Ff,"generateSystemThemeColors");function Wo({r:e,g:t,b:i}){return Ns(xe(e,t,i))}h(Wo,"okhslOf");function Ho(e){return{...Wo(e),chroma:Le(xe(e.r,e.g,e.b)).c}}h(Ho,"sourceOf");function Vo(e,t,i,r){let s=Fo(t,e.l),n=s>0?Math.min(1,Fo(t,i)/s):1,l=kt(e.h,e.s*n*r,i),o=e.chroma*n*r,{l:a,c:u}=Le(l);return u<=o?l:ye(ii(a,o,e.h))}h(Vo,"anchored");function Nf(e,t,i){let r=h(c=>t.every(p=>_i(c,p)>=is),"meets");if(r(e))return e;let{h:s,s:n,l}=Wo(e),o=h(c=>kt(s,n,c),"at2"),a=i?1:0;if(!r(o(a)))return o(a);let[u,d]=[l,a];for(let c=0;c<20;c++){let p=(u+d)/2;r(o(p))?d=p:u=p}return o(d)}h(Nf,"withTextContrast");function Wf(e,t){let i={},r=[];for(let[s,n]of Object.entries(es)){if(ts.includes(s)){i[s]="";continue}let l=n==="neutral";i[s]=!l&&e>0?Eo[s]??Jr[n].slot:"",l&&!Po.includes(s)&&r.push(s)}return{colors:i,dim:r,appearance:t}}h(Wf,"indexedColors");function Hf(e){for(let[t,i]of Object.entries(e)){if(i.fallback===void 0)continue;let r=e[i.fallback];if(r===void 0)throw new Error(`Theme token ${t} has unknown fallback ${i.fallback}`);if(r.slot!==i.slot)throw new Error(`Theme token ${t} has fallback ${i.fallback} in a different color slot`)}return e}h(Hf,"defineThemeTokens");var rs=Hf({accent:{slot:"foreground",description:"Primary accent color (logo, selected items, cursor)"},border:{slot:"foreground",description:"Normal borders"},borderAccent:{slot:"foreground",description:"Highlighted borders"},borderMuted:{slot:"foreground",description:"Subtle borders"},success:{slot:"foreground",description:"Success states"},error:{slot:"foreground",description:"Error states"},warning:{slot:"foreground",description:"Warning states"},muted:{slot:"foreground",description:"Secondary/dimmed text"},dim:{slot:"foreground",description:"Very dimmed text (more subtle than muted)"},text:{slot:"foreground",description:"Default text color (usually empty string)"},thinkingText:{slot:"foreground",description:"Thinking block text color"},scrollbarTrack:{slot:"foreground",description:"Fullscreen scrollbar track foreground (falls back to muted when omitted)",fallback:"muted"},scrollbarThumb:{slot:"foreground",description:"Fullscreen scrollbar thumb foreground (falls back to text when omitted)",fallback:"text"},selectedBg:{slot:"background",description:"Selected item background"},searchMatchBg:{slot:"background",description:"Transcript search match background and current-match text (falls back to selectedBg when omitted)",fallback:"selectedBg"},searchMatchText:{slot:"foreground",description:"Transcript search match text and current-match background (falls back to text when omitted)",fallback:"text"},userMessageBg:{slot:"background",description:"User message background"},userMessageText:{slot:"foreground",description:"User message text color"},customMessageBg:{slot:"background",description:"Custom message background (hook-injected messages)"},customMessageText:{slot:"foreground",description:"Custom message text color"},customMessageLabel:{slot:"foreground",description:"Custom message type label color"},toolPendingBg:{slot:"background",description:"Tool execution box (pending state)"},toolSuccessBg:{slot:"background",description:"Tool execution box (success state)"},toolErrorBg:{slot:"background",description:"Tool execution box (error state)"},toolTitle:{slot:"foreground",description:"Tool execution box title color"},toolOutput:{slot:"foreground",description:"Tool execution box output text color"},mdHeading:{slot:"foreground",description:"Markdown heading text"},mdLink:{slot:"foreground",description:"Markdown link text"},mdLinkUrl:{slot:"foreground",description:"Markdown link URL"},mdCode:{slot:"foreground",description:"Markdown inline code"},mdCodeBlock:{slot:"foreground",description:"Markdown code block content"},mdCodeBlockBorder:{slot:"foreground",description:"Markdown code block fences"},mdQuote:{slot:"foreground",description:"Markdown blockquote text"},mdQuoteBorder:{slot:"foreground",description:"Markdown blockquote border"},mdHr:{slot:"foreground",description:"Markdown horizontal rule"},mdListBullet:{slot:"foreground",description:"Markdown list bullets/numbers"},toolDiffAdded:{slot:"foreground",description:"Added lines in tool diffs"},toolDiffRemoved:{slot:"foreground",description:"Removed lines in tool diffs"},toolDiffContext:{slot:"foreground",description:"Context lines in tool diffs"},toolDiffAddedBg:{slot:"background",description:"Whole-line background of added lines in tool diffs (falls back to toolSuccessBg when omitted)",fallback:"toolSuccessBg"},toolDiffRemovedBg:{slot:"background",description:"Whole-line background of removed lines in tool diffs (falls back to toolErrorBg when omitted)",fallback:"toolErrorBg"},syntaxComment:{slot:"foreground",description:"Syntax highlighting: comments"},syntaxKeyword:{slot:"foreground",description:"Syntax highlighting: keywords"},syntaxFunction:{slot:"foreground",description:"Syntax highlighting: function names"},syntaxVariable:{slot:"foreground",description:"Syntax highlighting: variable names"},syntaxString:{slot:"foreground",description:"Syntax highlighting: string literals"},syntaxNumber:{slot:"foreground",description:"Syntax highlighting: number literals"},syntaxType:{slot:"foreground",description:"Syntax highlighting: type names"},syntaxOperator:{slot:"foreground",description:"Syntax highlighting: operators"},syntaxPunctuation:{slot:"foreground",description:"Syntax highlighting: punctuation"},thinkingOff:{slot:"foreground",description:"Thinking level border: off"},thinkingMinimal:{slot:"foreground",description:"Thinking level border: minimal"},thinkingLow:{slot:"foreground",description:"Thinking level border: low"},thinkingMedium:{slot:"foreground",description:"Thinking level border: medium"},thinkingHigh:{slot:"foreground",description:"Thinking level border: high"},thinkingXhigh:{slot:"foreground",description:"Thinking level border: xhigh"},thinkingMax:{slot:"foreground",description:"Thinking level border: max (falls back to thinkingXhigh when omitted)",fallback:"thinkingXhigh"},bashMode:{slot:"foreground",description:"Editor border color in bash mode"}}),ss;function Vf(e){ss=e}h(Vf,"setThemeJsonValidator");function ns(e,t,i=new Set){if(typeof e=="number"||e===""||e.startsWith("#")||/^ok(lch|hsl)\(/i.test(e))return e;if(i.has(e))throw new Error(`Circular variable reference detected: ${e}`);if(!(e in t))throw new Error(`Variable reference not found: ${e}`);return i.add(e),ns(t[e],t,i)}h(ns,"resolveVarRefs");function Kf(e,t={}){let i={};for(let[r,s]of Object.entries(e))i[r]=ns(s,t);return i}h(Kf,"resolveThemeColors");function ls(e){let t={...e};for(let[i,r]of Object.entries(rs)){if(!("fallback"in r))continue;let s=i;if(t[s]!==void 0)continue;let n=r.fallback,l=t[n];if(l===void 0)throw new Error(`Theme token ${i} has unresolved fallback ${r.fallback}`);t[s]=l}return t}h(ls,"withThemeTokenFallbacks");var Oi={},os=!1,Ko;function qf(e){Oi={...e},os=!1}h(qf,"setTerminalColors");function Uf(e){Ko=e}h(Uf,"setTerminalColorScheme");function zf(){os=!0}h(zf,"markTerminalColorsPending");var jf={dark:{foreground:ve("#e5e5e7"),background:ve("#000000")},light:{foreground:ve("#000000"),background:ve("#ffffff")}};function qo(e){let t=e.filter(i=>i.kind!=="indexed"||i.index>=16);if(t.length!==0)return t.reduce((i,r)=>i+Le(r).l,0)/t.length}h(qo,"averageLightness");function Gf(e,t){let i=qo(e),r=qo(t);if(i!==void 0&&r!==void 0)return r<i?"dark":"light";if(r!==void 0)return r<.5?"dark":"light";if(i!==void 0)return i>.5?"dark":"light"}h(Gf,"detectAppearance");var as=class{static{h(this,"Theme")}name;sourcePath;sourceInfo;mode;fgAnsi=new Map;bgAnsi=new Map;concreteColors={};defaultForegroundTokens=[];defaultBackgroundTokens=[];dimTokens;ownAppearance;resolvedColors;constructor(e,t,i,r={}){this.name=r.name,this.sourcePath=r.sourcePath,this.sourceInfo=r.sourceInfo,this.mode=i,this.dimTokens=new Set(r.dim);let{fgColors:s,bgColors:n}=cs(ls({...e,...t})),l=[],o=[],a=h((u,d,c)=>{if(d==="")return(c?this.defaultBackgroundTokens:this.defaultForegroundTokens).push(u),c?"\x1B[49m":"\x1B[39m";let p=ve(d);return this.concreteColors[u]=p,(c?o:l).push(p),c?St(p,i):wt(p,i)},"addToken");for(let[u,d]of Object.entries(s))this.fgAnsi.set(u,a(u,d,!1));for(let[u,d]of Object.entries(n))this.bgAnsi.set(u,a(u,d,!0));this.ownAppearance=r.appearance??Gf(l,o)}get appearance(){return this.ownAppearance??ps()}get colors(){let e=Oi;if(this.resolvedColors?.terminal!==e){let t=jf[this.appearance],i=h((l,o)=>l?xe(l.r,l.g,l.b):o,"toColor"),r=i(e.foreground,t.foreground),s=i(e.background,t.background),n={...this.concreteColors};for(let l of this.defaultForegroundTokens)n[l]=r;for(let l of this.defaultBackgroundTokens)n[l]=s;for(let l of this.dimTokens){let o=n[l];o&&(n[l]=Qi(o,s,.4))}this.resolvedColors={terminal:e,colors:Object.freeze(n)}}return this.resolvedColors.colors}style(e,t){let{fg:i,bg:r}=t;return typeof i=="string"&&this.dimTokens.has(i)&&(t={...t,dim:!0}),Zi(e,i===void 0?void 0:typeof i=="string"?this.tokenAnsi(this.fgAnsi,i):wt(i,this.mode),r===void 0?void 0:typeof r=="string"?this.tokenAnsi(this.bgAnsi,r):St(r,this.mode),t)}fg(e,t){let i=this.tokenAnsi(this.fgAnsi,e);return this.dimTokens.has(e)?`${i}\x1B[2m${t}\x1B[22;39m`:`${i}${t}\x1B[39m`}bg(e,t){return`${this.tokenAnsi(this.bgAnsi,e)}${t}\x1B[49m`}tokenAnsi(e,t){let i=e.get(t);if(i===void 0)throw new Error(`Unknown theme color: ${t}`);return i}bold(e){return xt.bold(e)}italic(e){return xt.italic(e)}underline(e){return xt.underline(e)}inverse(e){return xt.inverse(e)}strikethrough(e){return xt.strikethrough(e)}getFgAnsi(e){let t=this.tokenAnsi(this.fgAnsi,e);return this.dimTokens.has(e)?`${t}\x1B[2m`:t}getBgAnsi(e){return this.tokenAnsi(this.bgAnsi,e)}getColorMode(){return this.mode}getThinkingBorderColor(e){switch(e){case"off":return t=>this.fg("thinkingOff",t);case"minimal":return t=>this.fg("thinkingMinimal",t);case"low":return t=>this.fg("thinkingLow",t);case"medium":return t=>this.fg("thinkingMedium",t);case"high":return t=>this.fg("thinkingHigh",t);case"xhigh":return t=>this.fg("thinkingXhigh",t);case"max":return t=>this.fg("thinkingMax",t);default:return t=>this.fg("thinkingOff",t)}}getBashModeBorderColor(){return e=>this.fg("bashMode",e)}},hs;function Uo(){if(!hs){let e=ws(),t=dt.join(e,"dark.json"),i=dt.join(e,"light.json");hs={dark:JSON.parse(Ni(fe.readFileSync(t,"utf-8"))),light:JSON.parse(Ni(fe.readFileSync(i,"utf-8")))}}return hs}h(Uo,"getBuiltinThemes");function Yf(){return zo().map(({name:e})=>e)}h(Yf,"getAvailableThemes");function zo(){let e=ws(),t=[],i=new Set,r=h(s=>{i.has(s.name)||(i.add(s.name),t.push(s))},"addTheme");r({name:X,path:void 0});for(let s of Object.keys(Uo()))r({name:s,path:dt.join(e,`${s}.json`)});for(let s of Xf())r(s);for(let[s,n]of mt.entries())r({name:s,path:n.sourcePath});return t.sort((s,n)=>s.name===X?-1:n.name===X?1:s.name.localeCompare(n.name))}h(zo,"getAvailableThemesWithPaths");function Xf(){let e=Fi(),t=[];if(!fe.existsSync(e))return t;for(let i of fe.readdirSync(e)){if(!i.endsWith(".json"))continue;let r=dt.join(e,i);try{let s=ds(r);s.name&&t.push({name:s.name,path:r})}catch{}}return t}h(Xf,"getCustomThemeInfos");function Qf(e){if(e.includes("/"))throw new Error(`Invalid theme name "${e}": theme names cannot contain "/" because it is reserved for automatic light/dark theme settings.`)}h(Qf,"assertThemeNameIsValid");function Zf(e,t){if(ss)return ss(e,t);if(typeof t!="object"||t===null||!("colors"in t))throw new Error(`Invalid theme "${e}": expected an object with a "colors" map.`);return t}h(Zf,"parseThemeJson");function us(e,t){let i;try{i=JSON.parse(Ni(t))}catch(r){throw new Error(`Failed to parse theme ${e}: ${r}`)}return Zf(e,i)}h(us,"parseThemeJsonContent");function jo(e){let t=Uo();if(e in t)return t[e];let i=mt.get(e);if(i?.sourcePath){let l=fe.readFileSync(i.sourcePath,"utf-8");return us(i.sourcePath,l)}if(i)throw new Error(`Theme "${e}" does not have a source path for export`);let r=Fi(),s=dt.join(r,`${e}.json`);if(!fe.existsSync(s))throw new Error(`Theme not found: ${e}`);let n=fe.readFileSync(s,"utf-8");return us(e,n)}h(jo,"loadThemeJson");function cs(e){let t={},i={};for(let[r,s]of Object.entries(e))rs[r].slot==="background"?i[r]=s:t[r]=s;return{fgColors:t,bgColors:i}}h(cs,"splitThemeColors");function Go(e,t,i){let r=t??mi(),s=ls(Kf(e.colors,e.vars)),{fgColors:n,bgColors:l}=cs(s);return new as(n,l,r,{name:e.name,sourcePath:i,appearance:e.appearance})}h(Go,"createTheme");function Jf(e){let t=Ff({...Oi,saturation:os?0:1,appearanceHint:ps()}),{fgColors:i,bgColors:r}=cs(ls(t.colors));return new as(i,r,e??mi(),{name:X,appearance:t.appearance,dim:t.dim})}h(Jf,"createSystemTheme");function ds(e,t){let i=fe.readFileSync(e,"utf-8"),r=us(e,i);return Go(r,t,e)}h(ds,"loadThemeFromPath");function ft(e,t){if(e===X)return Jf(t);let i=mt.get(e);if(i)return i;let r=jo(e);return Go(r,t)}h(ft,"loadTheme");function eg(e){try{return ft(e)}catch{return}}h(eg,"getThemeByName");function Yo(e){if(!e)return;let t=e.indexOf("/");if(t===-1||e.indexOf("/",t+1)!==-1)return;let i=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!(!i||!r))return{lightTheme:i,darkTheme:r}}h(Yo,"parseAutoThemeSetting");function tg(e,t){let i=Yo(e);if(i)return t==="light"?i.lightTheme:i.darkTheme;if(!e?.includes("/")&&typeof e=="string")return e}h(tg,"resolveThemeSetting");function ig(e=process.env){let t=e.COLORFGBG?.split(";").at(-1)?.trim();if(!t||!/^\d{1,2}$/.test(t))return;let i=Number(t);if(!(i>15))return i<=6||i===8?"dark":"light"}h(ig,"detectColorFgBgTheme");function rg(e={},t,i=process.env){let{background:r,foreground:s}=e;return r?_o(r,s):t??ig(i)??"dark"}h(rg,"detectTerminalTheme");function ps(){return rg(Oi,Ko)}h(ps,"getTerminalTheme");var fs=Symbol.for("@earendil-works/pi-coding-agent:theme"),sg=Symbol.for("@mariozechner/pi-coding-agent:theme"),O=new Proxy({},{get(e,t){let i=globalThis[fs];if(!i)throw new Error("Theme not initialized. Call initTheme() first.");return i[t]}});function ng(){return globalThis[fs]}h(ng,"getGlobalTheme");function gt(e){globalThis[fs]=e,globalThis[sg]=e}h(gt,"setGlobalTheme");var Z,Vt,qe,Ue,mt=new Map;function lg(e){mt.clear();for(let t of e)t.name&&(Qf(t.name),mt.set(t.name,t))}h(lg,"setRegisteredThemes");function og(e,t=!1){let i=e??X;Z=i;try{gt(ft(i)),t&&Xo()}catch{Z=X,gt(ft(X))}}h(og,"initTheme");function ag(e,t=!1){Z=e;try{return gt(ft(e)),t&&Xo(),Ue&&Ue(),{success:!0}}catch(i){return Z=X,gt(ft(X)),{success:!1,error:i instanceof Error?i.message:String(i)}}}h(ag,"setTheme");function hg(e){gt(e),Z="<in-memory>",gs(),Ue&&Ue()}h(hg,"setThemeInstance");function ug(e){Ue=e}h(ug,"onThemeChange");function Xo(){if(gs(),!Z||Z==="dark"||Z==="light"||Z===X)return;let e=Fi(),t=Z,i=`${t}.json`,r=dt.join(e,i);if(!fe.existsSync(r))return;let s=h(()=>{qe&&clearTimeout(qe),qe=setTimeout(()=>{if(qe=void 0,Z===t&&fe.existsSync(r))try{let n=ds(r);mt.set(t,n),gt(n),Ue&&Ue()}catch{}},100)},"scheduleReload");Vt=Bo(e,(n,l)=>{if(Z===t){if(!l){s();return}l===i&&s()}},()=>{Qr(Vt),Vt=void 0})??void 0}h(Xo,"startThemeWatcher");function gs(){qe&&(clearTimeout(qe),qe=void 0),Qr(Vt),Vt=void 0}h(gs,"stopThemeWatcher");function cg(e){let t=ft(e??Z??X).colors;return Object.fromEntries(Object.entries(t).map(([i,r])=>[i,ri(r)]))}h(cg,"getResolvedThemeColors");function dg(e){let t=e??Z??X;if(t===X)return{};try{let i=jo(t),r=i.export;if(!r)return{};let s=i.vars??{},n=h(l=>{if(l===void 0)return;let o=ns(l,s);if(typeof o=="number")return ri(ti(o));if(o!=="")return/^okhsl\(/i.test(o)?ri(ve(o)):o},"resolve");return{pageBg:n(r.pageBg),cardBg:n(r.cardBg),infoBg:n(r.infoBg)}}catch{return{}}}h(dg,"getThemeExportColors");var Qo,ms;function pg(e){return{keyword:h(t=>e.fg("syntaxKeyword",t),"keyword"),built_in:h(t=>e.fg("syntaxType",t),"built_in"),literal:h(t=>e.fg("syntaxNumber",t),"literal"),number:h(t=>e.fg("syntaxNumber",t),"number"),regexp:h(t=>e.fg("syntaxString",t),"regexp"),string:h(t=>e.fg("syntaxString",t),"string"),subst:h(t=>e.fg("text",t),"subst"),comment:h(t=>e.fg("syntaxComment",t),"comment"),doctag:h(t=>e.fg("syntaxComment",t),"doctag"),meta:h(t=>e.fg("muted",t),"meta"),function:h(t=>e.fg("syntaxFunction",t),"function"),title:h(t=>e.fg("syntaxFunction",t),"title"),class:h(t=>e.fg("syntaxType",t),"class"),type:h(t=>e.fg("syntaxType",t),"type"),tag:h(t=>e.fg("syntaxPunctuation",t),"tag"),name:h(t=>e.fg("syntaxKeyword",t),"name"),attr:h(t=>e.fg("syntaxVariable",t),"attr"),variable:h(t=>e.fg("syntaxVariable",t),"variable"),params:h(t=>e.fg("syntaxVariable",t),"params"),operator:h(t=>e.fg("syntaxOperator",t),"operator"),punctuation:h(t=>e.fg("syntaxPunctuation",t),"punctuation"),emphasis:h(t=>e.italic(t),"emphasis"),strong:h(t=>e.bold(t),"strong"),link:h(t=>e.underline(t),"link"),addition:h(t=>e.fg("toolDiffAdded",t),"addition"),deletion:h(t=>e.fg("toolDiffRemoved",t),"deletion")}}h(pg,"buildCliHighlightTheme");function fg(e){return(Qo!==e||!ms)&&(Qo=e,ms=pg(e)),ms}h(fg,"getCliHighlightTheme");function xs(e,t){let i=t&&Bf(t)?t:void 0;if(!i)return e.split(`
127
127
  `).map(s=>O.fg("mdCodeBlock",s));let r={language:i,ignoreIllegals:!0,theme:fg(O)};try{return Af(e,r).split(`
128
128
  `)}catch{return e.split(`
129
- `).map(s=>O.fg("mdCodeBlock",s))}}h(xs,"highlightCode");var gg=class{static{h(this,"CodeHighlighter")}last;highlight(e,t){let i=ng(),r=If(),s=this.last;if(s?.code===e&&s.lang===t&&s.theme===i&&s.languageCount===r)return s.lines;let n=xs(e,t);return this.last={code:e,lang:t,theme:i,languageCount:r,lines:n},n}};function mg(e){let t=e.split(".").pop()?.toLowerCase();return t?{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",kt:"kotlin",swift:"swift",dart:"dart",groovy:"groovy",gradle:"groovy",nix:"nix",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",markdown:"markdown",dockerfile:"dockerfile",makefile:"makefile",cmake:"cmake",lua:"lua",perl:"perl",r:"r",scala:"scala",clj:"clojure",ex:"elixir",exs:"elixir",erl:"erlang",hs:"haskell",ml:"ocaml",vim:"vim",graphql:"graphql",proto:"protobuf",tf:"hcl",hcl:"hcl"}[t]:void 0}h(mg,"getLanguageFromPath");function xg(){return{heading:h(e=>O.fg("mdHeading",e),"heading"),link:h(e=>O.fg("mdLink",e),"link"),linkUrl:h(e=>O.fg("mdLinkUrl",e),"linkUrl"),code:h(e=>O.fg("mdCode",e),"code"),codeBlock:h(e=>O.fg("mdCodeBlock",e),"codeBlock"),codeBlockBorder:h(e=>O.fg("mdCodeBlockBorder",e),"codeBlockBorder"),quote:h(e=>O.fg("mdQuote",e),"quote"),quoteBorder:h(e=>O.fg("mdQuoteBorder",e),"quoteBorder"),hr:h(e=>O.fg("mdHr",e),"hr"),listBullet:h(e=>O.fg("mdListBullet",e),"listBullet"),bold:h(e=>O.bold(e),"bold"),italic:h(e=>O.italic(e),"italic"),underline:h(e=>O.underline(e),"underline"),strikethrough:h(e=>O.strikethrough(e),"strikethrough"),highlightCode:xs}}h(xg,"getMarkdownTheme");function Zo(){return{selectedPrefix:h(e=>O.fg("accent",e),"selectedPrefix"),selectedText:h(e=>O.fg("accent",e),"selectedText"),description:h(e=>O.fg("muted",e),"description"),scrollInfo:h(e=>O.fg("muted",e),"scrollInfo"),noMatch:h(e=>O.fg("muted",e),"noMatch")}}h(Zo,"getSelectListTheme");function bg(){return{borderColor:h(e=>O.fg("border",e),"borderColor"),selectList:Zo(),placeholder:h(e=>O.fg("dim",e),"placeholder")}}h(bg,"getEditorTheme");function yg(){return{label:h((e,t)=>t?O.fg("accent",e):e,"label"),value:h((e,t)=>t?O.fg("accent",e):O.fg("muted",e),"value"),description:h(e=>O.fg("dim",e),"description"),cursor:O.fg("accent","\u2192 "),hint:h(e=>O.fg("dim",e),"hint")}}h(yg,"getSettingsListTheme");function kg(e,t){let i=process.platform==="darwin"&&e.toLowerCase()==="alt"?"option":e;return t.capitalize?i.charAt(0).toUpperCase()+i.slice(1):i}h(kg,"formatKeyPart");function bs(e,t={}){return e.split("/").map(i=>i.split("+").map(r=>kg(r,t)).join("+")).join("/")}h(bs,"formatKeyText");function Jo(e,t={}){return e.length===0?"":bs(e.join("/"),t)}h(Jo,"formatKeys");function ea(e){return Jo(se().getKeys(e))}h(ea,"keyText");function wg(e){return Jo(se().getKeys(e),{capitalize:!0})}h(wg,"keyDisplayText");function Sg(e,t){return O.fg("dim",ea(e))+O.fg("muted",` ${t}`)}h(Sg,"keyHint");function Cg(e,t){return O.fg("dim",bs(e))+O.fg("muted",` ${t}`)}h(Cg,"rawKeyHint");export{ll as Box,pe as CURSOR_MARKER,hl as CancellableLoader,gg as CodeHighlighter,$n as CombinedAutocompleteProvider,Ie as Container,Rf as DEFAULT_THEME_SETTING,Tl as Editor,Yp as FS_WATCH_RETRY_DELAY_MS,Il as Image,Ci as Input,qs as Key,ir as KeybindingsManager,Ar as Loader,Vl as Markdown,Kl as MouseRegion,lo as ProcessTerminal,X as SYSTEM_THEME_NAME,Nr as ScrollView,Br as SelectList,ql as SettingsList,Ul as Spacer,rs as THEME_TOKENS,tr as TUI_KEYBINDINGS,Mr as Text,as as Theme,zl as TruncatedText,So as TuiAltScreen,Ao as TuiMainScreen,jl as VStack,fi as Z,St as backgroundAnsi,Qr as closeWatcher,ye as colorToRgb,gr as detectCapabilities,en as dist_exports,wt as foregroundAnsi,bs as formatKeyText,Et as fuzzyFilter,pr as fuzzyMatch,Yf as getAvailableThemes,zo as getAvailableThemesWithPaths,oe as getCapabilities,bg as getEditorTheme,Sr as getImageDimensions,se as getKeybindings,mg as getLanguageFromPath,xg as getMarkdownTheme,Yl as getNativeClipboard,cg as getResolvedThemeColors,Zo as getSelectListTheme,hi as getSelectPageIndex,yg as getSettingsListTheme,mi as getTerminalColorMode,ps as getTerminalTheme,eg as getThemeByName,dg as getThemeExportColors,xs as highlightCode,xi as hyperlink,bi as imageFallback,ti as indexedColor,og as initTheme,sl as isViewportTUI,wg as keyDisplayText,Sg as keyHint,ea as keyText,wf as loadAllHighlightLanguages,ds as loadThemeFromPath,zf as markTerminalColorsPending,Me as matchesKey,Qi as mixColors,ug as onThemeChange,Yo as parseAutoThemeSetting,ve as parseColor,Cg as rawKeyHint,Ut as replaceControlCharacters,tg as resolveThemeSetting,xe as rgbColor,Nn as setCapabilityOverrides,Bl as setImageTranscoder,Js as setKeybindings,lg as setRegisteredThemes,Uf as setTerminalColorScheme,qf as setTerminalColors,ag as setTheme,hg as setThemeInstance,Vf as setThemeJsonValidator,z as sliceByColumn,gs as stopThemeWatcher,O as theme,H as truncateToWidth,C as visibleWidth,Bo as watchWithErrorHandler,me as wrapTextWithAnsi};
129
+ `).map(s=>O.fg("mdCodeBlock",s))}}h(xs,"highlightCode");var gg=class{static{h(this,"CodeHighlighter")}last;highlight(e,t){let i=ng(),r=If(),s=this.last;if(s?.code===e&&s.lang===t&&s.theme===i&&s.languageCount===r)return s.lines;let n=xs(e,t);return this.last={code:e,lang:t,theme:i,languageCount:r,lines:n},n}};function mg(e){let t=e.split(".").pop()?.toLowerCase();return t?{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",kt:"kotlin",swift:"swift",dart:"dart",groovy:"groovy",gradle:"groovy",nix:"nix",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",markdown:"markdown",dockerfile:"dockerfile",makefile:"makefile",cmake:"cmake",lua:"lua",perl:"perl",r:"r",scala:"scala",clj:"clojure",ex:"elixir",exs:"elixir",erl:"erlang",hs:"haskell",ml:"ocaml",vim:"vim",graphql:"graphql",proto:"protobuf",tf:"hcl",hcl:"hcl"}[t]:void 0}h(mg,"getLanguageFromPath");function xg(){return{heading:h(e=>O.fg("mdHeading",e),"heading"),link:h(e=>O.fg("mdLink",e),"link"),linkUrl:h(e=>O.fg("mdLinkUrl",e),"linkUrl"),code:h(e=>O.fg("mdCode",e),"code"),codeBlock:h(e=>O.fg("mdCodeBlock",e),"codeBlock"),codeBlockBorder:h(e=>O.fg("mdCodeBlockBorder",e),"codeBlockBorder"),quote:h(e=>O.fg("mdQuote",e),"quote"),quoteBorder:h(e=>O.fg("mdQuoteBorder",e),"quoteBorder"),hr:h(e=>O.fg("mdHr",e),"hr"),listBullet:h(e=>O.fg("mdListBullet",e),"listBullet"),bold:h(e=>O.bold(e),"bold"),italic:h(e=>O.italic(e),"italic"),underline:h(e=>O.underline(e),"underline"),strikethrough:h(e=>O.strikethrough(e),"strikethrough"),highlightCode:xs}}h(xg,"getMarkdownTheme");function Zo(){return{selectedPrefix:h(e=>O.fg("accent",e),"selectedPrefix"),selectedText:h(e=>O.fg("accent",e),"selectedText"),description:h(e=>O.fg("muted",e),"description"),scrollInfo:h(e=>O.fg("muted",e),"scrollInfo"),noMatch:h(e=>O.fg("muted",e),"noMatch")}}h(Zo,"getSelectListTheme");function bg(){return{borderColor:h(e=>O.fg("border",e),"borderColor"),selectList:Zo(),placeholder:h(e=>O.fg("dim",e),"placeholder")}}h(bg,"getEditorTheme");function yg(){return{label:h((e,t)=>t?O.fg("accent",e):e,"label"),value:h((e,t)=>t?O.fg("accent",e):O.fg("muted",e),"value"),description:h(e=>O.fg("dim",e),"description"),cursor:O.fg("accent","\u2192 "),hint:h(e=>O.fg("dim",e),"hint")}}h(yg,"getSettingsListTheme");function kg(e,t){let i=process.platform==="darwin"&&e.toLowerCase()==="alt"?"option":e;return t.capitalize?i.toLowerCase()==="escape"?"Esc":i.charAt(0).toUpperCase()+i.slice(1):i}h(kg,"formatKeyPart");function bs(e,t={}){return e.split("/").map(i=>i.split("+").map(r=>kg(r,t)).join("+")).join("/")}h(bs,"formatKeyText");function Jo(e,t={}){return e.length===0?"":bs(e.join("/"),t)}h(Jo,"formatKeys");function ea(e){return Jo(se().getKeys(e))}h(ea,"keyText");function wg(e){return Jo(se().getKeys(e),{capitalize:!0})}h(wg,"keyDisplayText");function Sg(e,t){return O.fg("dim",ea(e))+O.fg("muted",` ${t}`)}h(Sg,"keyHint");function Cg(e,t){return O.fg("dim",bs(e))+O.fg("muted",` ${t}`)}h(Cg,"rawKeyHint");export{ll as Box,pe as CURSOR_MARKER,hl as CancellableLoader,gg as CodeHighlighter,$n as CombinedAutocompleteProvider,Ie as Container,Rf as DEFAULT_THEME_SETTING,Tl as Editor,Yp as FS_WATCH_RETRY_DELAY_MS,Il as Image,Ci as Input,qs as Key,ir as KeybindingsManager,Ar as Loader,Vl as Markdown,Kl as MouseRegion,lo as ProcessTerminal,X as SYSTEM_THEME_NAME,Nr as ScrollView,Br as SelectList,ql as SettingsList,Ul as Spacer,rs as THEME_TOKENS,tr as TUI_KEYBINDINGS,Mr as Text,as as Theme,zl as TruncatedText,So as TuiAltScreen,Ao as TuiMainScreen,jl as VStack,fi as Z,St as backgroundAnsi,Qr as closeWatcher,ye as colorToRgb,gr as detectCapabilities,en as dist_exports,wt as foregroundAnsi,bs as formatKeyText,Et as fuzzyFilter,pr as fuzzyMatch,Yf as getAvailableThemes,zo as getAvailableThemesWithPaths,oe as getCapabilities,bg as getEditorTheme,Sr as getImageDimensions,se as getKeybindings,mg as getLanguageFromPath,xg as getMarkdownTheme,Yl as getNativeClipboard,cg as getResolvedThemeColors,Zo as getSelectListTheme,hi as getSelectPageIndex,yg as getSettingsListTheme,mi as getTerminalColorMode,ps as getTerminalTheme,eg as getThemeByName,dg as getThemeExportColors,xs as highlightCode,xi as hyperlink,bi as imageFallback,ti as indexedColor,og as initTheme,sl as isViewportTUI,wg as keyDisplayText,Sg as keyHint,ea as keyText,wf as loadAllHighlightLanguages,ds as loadThemeFromPath,zf as markTerminalColorsPending,Me as matchesKey,Qi as mixColors,ug as onThemeChange,Yo as parseAutoThemeSetting,ve as parseColor,Cg as rawKeyHint,Ut as replaceControlCharacters,tg as resolveThemeSetting,xe as rgbColor,Nn as setCapabilityOverrides,Bl as setImageTranscoder,Js as setKeybindings,lg as setRegisteredThemes,Uf as setTerminalColorScheme,qf as setTerminalColors,ag as setTheme,hg as setThemeInstance,Vf as setThemeJsonValidator,z as sliceByColumn,gs as stopThemeWatcher,O as theme,H as truncateToWidth,C as visibleWidth,Bo as watchWithErrorHandler,me as wrapTextWithAnsi};
@@ -1,4 +1,4 @@
1
- var it=Object.defineProperty;var o=(e,t)=>it(e,"name",{value:t,configurable:!0});import{createRequire as st}from"node:module";const Vr=st(import.meta.url);import{fill as nt,getShellConfig as ot}from"./chunk-SE42OS3U.js";import{APP_TITLE as at,getAgentDir as U,getFileRevision as N,normalizePath as V,require_cross_spawn as lt,stripBom as te}from"./chunk-R47JBGS3.js";import{require_graceful_fs as fe}from"./chunk-XJFQKN3N.js";import{drainNewerDataFormatFiles as ut,t as ct,writeFileAtomicSync as pe}from"./chunk-XRF4A4KI.js";import{__commonJS as P,__require as re,__toESM as me}from"./chunk-JXWJOIH4.js";var dt=P({"node_modules/proper-lockfile/node_modules/retry/lib/retry_operation.js"(e,t){function r(i,s){typeof s=="boolean"&&(s={forever:s}),this._originalTimeouts=JSON.parse(JSON.stringify(i)),this._timeouts=i,this._options=s||{},this._maxRetryTime=s&&s.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}o(r,"RetryOperation"),t.exports=r,r.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},r.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},r.prototype.retry=function(i){if(this._timeout&&clearTimeout(this._timeout),!i)return!1;var s=new Date().getTime();if(i&&s-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(i);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1;var a=this,l=setTimeout(function(){a._attempts++,a._operationTimeoutCb&&(a._timeout=setTimeout(function(){a._operationTimeoutCb(a._attempts)},a._operationTimeout),a._options.unref&&a._timeout.unref()),a._fn(a._attempts)},n);return this._options.unref&&l.unref(),!0},r.prototype.attempt=function(i,s){this._fn=i,s&&(s.timeout&&(this._operationTimeout=s.timeout),s.cb&&(this._operationTimeoutCb=s.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},r.prototype.try=function(i){console.log("Using RetryOperation.try() is deprecated"),this.attempt(i)},r.prototype.start=function(i){console.log("Using RetryOperation.start() is deprecated"),this.attempt(i)},r.prototype.start=r.prototype.try,r.prototype.errors=function(){return this._errors},r.prototype.attempts=function(){return this._attempts},r.prototype.mainError=function(){if(this._errors.length===0)return null;for(var i={},s=null,n=0,a=0;a<this._errors.length;a++){var l=this._errors[a],u=l.message,h=(i[u]||0)+1;i[u]=h,h>=n&&(s=l,n=h)}return s}}}),ht=P({"node_modules/proper-lockfile/node_modules/retry/lib/retry.js"(e){var t=dt();e.operation=function(r){var i=e.timeouts(r);return new t(i,{forever:r&&r.forever,unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(r){if(r instanceof Array)return[].concat(r);var i={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var s in r)i[s]=r[s];if(i.minTimeout>i.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],a=0;a<i.retries;a++)n.push(this.createTimeout(a,i));return r&&r.forever&&!n.length&&n.push(this.createTimeout(a,i)),n.sort(function(l,u){return l-u}),n},e.createTimeout=function(r,i){var s=i.randomize?Math.random()+1:1,n=Math.round(s*i.minTimeout*Math.pow(i.factor,r));return n=Math.min(n,i.maxTimeout),n},e.wrap=function(r,i,s){if(i instanceof Array&&(s=i,i=null),!s){s=[];for(var n in r)typeof r[n]=="function"&&s.push(n)}for(var a=0;a<s.length;a++){var l=s[a],u=r[l];r[l]=function(h){var f=e.operation(i),g=Array.prototype.slice.call(arguments,1),m=g.pop();g.push(function(w){f.retry(w)||(w&&(arguments[0]=f.mainError()),m.apply(this,arguments))}),f.attempt(function(){h.apply(r,g)})}.bind(r,u),r[l].options=i}}}}),ft=P({"node_modules/proper-lockfile/node_modules/retry/index.js"(e,t){t.exports=ht()}}),pt=P({"node_modules/signal-exit/signals.js"(e,t){t.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&t.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&t.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}}),mt=P({"node_modules/signal-exit/index.js"(e,t){var r=global.process,i=o(function(y){return y&&typeof y=="object"&&typeof y.removeListener=="function"&&typeof y.emit=="function"&&typeof y.reallyExit=="function"&&typeof y.listeners=="function"&&typeof y.kill=="function"&&typeof y.pid=="number"&&typeof y.on=="function"},"processOk");i(r)?(s=re("assert"),n=pt(),a=/^win/i.test(r.platform),l=re("events"),typeof l!="function"&&(l=l.EventEmitter),r.__signal_exit_emitter__?u=r.__signal_exit_emitter__:(u=r.__signal_exit_emitter__=new l,u.count=0,u.emitted={}),u.infinite||(u.setMaxListeners(1/0),u.infinite=!0),t.exports=function(y,p){if(!i(global.process))return function(){};s.equal(typeof y,"function","a callback must be provided for exit handler"),m===!1&&w();var c="exit";p&&p.alwaysLast&&(c="afterexit");var d=o(function(){u.removeListener(c,y),u.listeners("exit").length===0&&u.listeners("afterexit").length===0&&h()},"remove");return u.on(c,y),d},h=o(function(){!m||!i(global.process)||(m=!1,n.forEach(function(y){try{r.removeListener(y,g[y])}catch{}}),r.emit=b,r.reallyExit=v,u.count-=1)},"unload"),t.exports.unload=h,f=o(function(y,p,c){u.emitted[y]||(u.emitted[y]=!0,u.emit(y,p,c))},"emit"),g={},n.forEach(function(y){g[y]=function(){if(i(global.process)){var p=r.listeners(y);p.length===u.count&&(h(),f("exit",null,y),f("afterexit",null,y),a&&y==="SIGHUP"&&(y="SIGINT"),r.kill(r.pid,y))}}}),t.exports.signals=function(){return n},m=!1,w=o(function(){m||!i(global.process)||(m=!0,u.count+=1,n=n.filter(function(y){try{return r.on(y,g[y]),!0}catch{return!1}}),r.emit=S,r.reallyExit=x)},"load"),t.exports.load=w,v=r.reallyExit,x=o(function(y){i(global.process)&&(r.exitCode=y||0,f("exit",r.exitCode,null),f("afterexit",r.exitCode,null),v.call(r,r.exitCode))},"processReallyExit"),b=r.emit,S=o(function(y,p){if(y==="exit"&&i(global.process)){p!==void 0&&(r.exitCode=p);var c=b.apply(this,arguments);return f("exit",r.exitCode,null),f("afterexit",r.exitCode,null),c}else return b.apply(this,arguments)},"processEmit")):t.exports=function(){return function(){}};var s,n,a,l,u,h,f,g,m,w,v,x,b,S}}),yt=P({"node_modules/proper-lockfile/lib/mtime-precision.js"(e,t){"use strict";var r=Symbol();function i(n,a,l){let u=a[r];if(u)return a.stat(n,(f,g)=>{if(f)return l(f);l(null,g.mtime,u)});let h=new Date(Math.ceil(Date.now()/1e3)*1e3+5);a.utimes(n,h,h,f=>{if(f)return l(f);a.stat(n,(g,m)=>{if(g)return l(g);let w=m.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(a,r,{value:w}),l(null,m.mtime,w)})})}o(i,"probe");function s(n){let a=Date.now();return n==="s"&&(a=Math.ceil(a/1e3)*1e3),new Date(a)}o(s,"getMtime"),t.exports.probe=i,t.exports.getMtime=s}}),gt=P({"node_modules/proper-lockfile/lib/lockfile.js"(e,t){"use strict";var r=re("path"),i=fe(),s=ft(),n=mt(),a=yt(),l={};function u(p,c){return c.lockfilePath||`${p}.lock`}o(u,"getLockFile");function h(p,c,d){if(!c.realpath)return d(null,r.resolve(p));c.fs.realpath(p,d)}o(h,"resolveCanonicalPath");function f(p,c,d){let E=u(p,c);c.fs.mkdir(E,C=>{if(!C)return a.probe(E,c.fs,(_,R,M)=>{if(_)return c.fs.rmdir(E,()=>{}),d(_);d(null,R,M)});if(C.code!=="EEXIST")return d(C);if(c.stale<=0)return d(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:p}));c.fs.stat(E,(_,R)=>{if(_)return _.code==="ENOENT"?f(p,{...c,stale:0},d):d(_);if(!g(R,c))return d(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:p}));m(p,c,M=>{if(M)return d(M);f(p,{...c,stale:0},d)})})})}o(f,"acquireLock");function g(p,c){return p.mtime.getTime()<Date.now()-c.stale}o(g,"isLockStale");function m(p,c,d){c.fs.rmdir(u(p,c),E=>{if(E&&E.code!=="ENOENT")return d(E);d()})}o(m,"removeLock");function w(p,c){let d=l[p];d.updateTimeout||(d.updateDelay=d.updateDelay||c.update,d.updateTimeout=setTimeout(()=>{d.updateTimeout=null,c.fs.stat(d.lockfilePath,(E,C)=>{let _=d.lastUpdate+c.stale<Date.now();if(E)return E.code==="ENOENT"||_?v(p,d,Object.assign(E,{code:"ECOMPROMISED"})):(d.updateDelay=1e3,w(p,c));if(d.mtime.getTime()!==C.mtime.getTime())return v(p,d,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let R=a.getMtime(d.mtimePrecision);c.fs.utimes(d.lockfilePath,R,R,M=>{let Q=d.lastUpdate+c.stale<Date.now();if(!d.released){if(M)return M.code==="ENOENT"||Q?v(p,d,Object.assign(M,{code:"ECOMPROMISED"})):(d.updateDelay=1e3,w(p,c));d.mtime=R,d.lastUpdate=Date.now(),d.updateDelay=null,w(p,c)}})})},d.updateDelay),d.updateTimeout.unref&&d.updateTimeout.unref())}o(w,"updateLock");function v(p,c,d){c.released=!0,c.updateTimeout&&clearTimeout(c.updateTimeout),l[p]===c&&delete l[p],c.options.onCompromised(d)}o(v,"setLockAsCompromised");function x(p,c,d){c={stale:1e4,update:null,realpath:!0,retries:0,fs:i,onCompromised:o(E=>{throw E},"onCompromised"),...c},c.retries=c.retries||0,c.retries=typeof c.retries=="number"?{retries:c.retries}:c.retries,c.stale=Math.max(c.stale||0,2e3),c.update=c.update==null?c.stale/2:c.update||0,c.update=Math.max(Math.min(c.update,c.stale/2),1e3),h(p,c,(E,C)=>{if(E)return d(E);let _=s.operation(c.retries);_.attempt(()=>{f(C,c,(R,M,Q)=>{if(_.retry(R))return;if(R)return d(_.mainError());let rt=l[C]={lockfilePath:u(C,c),mtime:M,mtimePrecision:Q,options:c,lastUpdate:Date.now()};w(C,c),d(null,ee=>{if(rt.released)return ee&&ee(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));b(C,{...c,realpath:!1},ee)})})})})}o(x,"lock");function b(p,c,d){c={fs:i,realpath:!0,...c},h(p,c,(E,C)=>{if(E)return d(E);let _=l[C];if(!_)return d(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));_.updateTimeout&&clearTimeout(_.updateTimeout),_.released=!0,delete l[C],m(C,c,d)})}o(b,"unlock");function S(p,c,d){c={stale:1e4,realpath:!0,fs:i,...c},c.stale=Math.max(c.stale||0,2e3),h(p,c,(E,C)=>{if(E)return d(E);c.fs.stat(u(C,c),(_,R)=>_?_.code==="ENOENT"?d(null,!1):d(_):d(null,!g(R,c)))})}o(S,"check");function y(){return l}o(y,"getLocks"),n(()=>{for(let p in l){let c=l[p].options;try{c.fs.rmdirSync(u(p,c))}catch{}}}),t.exports.lock=x,t.exports.unlock=b,t.exports.check=S,t.exports.getLocks=y}}),vt=P({"node_modules/proper-lockfile/lib/adapter.js"(e,t){"use strict";var r=fe();function i(l){let u=["mkdir","realpath","stat","rmdir","utimes"],h={...l};return u.forEach(f=>{h[f]=(...g)=>{let m=g.pop(),w;try{w=l[`${f}Sync`](...g)}catch(v){return m(v)}m(null,w)}}),h}o(i,"createSyncFs");function s(l){return(...u)=>new Promise((h,f)=>{u.push((g,m)=>{g?f(g):h(m)}),l(...u)})}o(s,"toPromise");function n(l){return(...u)=>{let h,f;if(u.push((g,m)=>{h=g,f=m}),l(...u),h)throw h;return f}}o(n,"toSync");function a(l){if(l={...l},l.fs=i(l.fs||r),typeof l.retries=="number"&&l.retries>0||l.retries&&typeof l.retries.retries=="number"&&l.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return l}o(a,"toSyncOptions"),t.exports={toPromise:s,toSync:n,toSyncOptions:a}}}),ye=P({"node_modules/proper-lockfile/index.js"(e,t){"use strict";var r=gt(),{toPromise:i,toSync:s,toSyncOptions:n}=vt();async function a(m,w){let v=await i(r.lock)(m,w);return i(v)}o(a,"lock");function l(m,w){let v=s(r.lock)(m,n(w));return s(v)}o(l,"lockSync");function u(m,w){return i(r.unlock)(m,w)}o(u,"unlock");function h(m,w){return s(r.unlock)(m,n(w))}o(h,"unlockSync");function f(m,w){return i(r.check)(m,w)}o(f,"check");function g(m,w){return s(r.check)(m,n(w))}o(g,"checkSync"),t.exports=a,t.exports.lock=a,t.exports.unlock=u,t.exports.lockSync=l,t.exports.unlockSync=h,t.exports.check=f,t.exports.checkSync=g}}),L={parseError:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internalError:-32603},A=class extends Error{static{o(this,"McpError")}code;data;constructor(e,t,r){super(t),this.name="McpError",this.code=e,this.data=r}},I=class extends Error{static{o(this,"McpConnectionClosedError")}constructor(e="MCP connection closed"){super(e),this.name="McpConnectionClosedError"}},wt=class extends Error{static{o(this,"McpTimeoutError")}timeoutMs;constructor(e){super(`MCP request timed out after ${e}ms`),this.name="McpTimeoutError",this.timeoutMs=e}},ie=class extends Error{static{o(this,"McpAbortError")}constructor(e="MCP request aborted"){super(e),this.name="AbortError"}};function T(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(T,"isObject");function F(e){return e instanceof Error?e:new Error(String(e))}o(F,"toError");function B(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}o(B,"isJsonRpcId");function se(e){return T(e)&&e.jsonrpc==="2.0"&&B(e.id)&&typeof e.method=="string"}o(se,"isJsonRpcRequest");function ge(e){return T(e)&&e.jsonrpc==="2.0"&&!("id"in e)&&typeof e.method=="string"}o(ge,"isJsonRpcNotification");function ne(e){return!T(e)||e.jsonrpc!=="2.0"||!B(e.id)?!1:"result"in e?!("error"in e):!("error"in e)||!T(e.error)?!1:typeof e.error.code=="number"&&typeof e.error.message=="string"}o(ne,"isJsonRpcResponse");function G(e){if(se(e)||ge(e)||ne(e))return e;throw new A(L.invalidRequest,"Invalid JSON-RPC message")}o(G,"parseJsonRpcMessage");var oe="2025-11-25",Et=[oe,"2025-06-18","2025-03-26","2024-11-05"],St=3e4,ve=1e3;function _t(e){if(!T(e)||typeof e.protocolVersion!="string"||!T(e.capabilities)||!T(e.serverInfo)||typeof e.serverInfo.name!="string"||typeof e.serverInfo.version!="string"||e.instructions!==void 0&&typeof e.instructions!="string")throw new A(L.invalidRequest,"Invalid MCP initialize result");return e}o(_t,"validateInitializeResult");function j(e){return new A(L.invalidRequest,e)}o(j,"invalid");function xt(e,t,r,i){let s=T(r)?r[t]:void 0;if(!T(r)||!Array.isArray(s))throw j(`Invalid MCP ${e} result`);for(let a of s)if(!T(a)||!i(a))throw j(`Invalid entry in MCP ${e} result`);let n=r.nextCursor===null||r.nextCursor===""?void 0:r.nextCursor;if(n!==void 0&&typeof n!="string")throw j(`Invalid MCP ${e} cursor`);return{items:s,...n===void 0?{}:{nextCursor:n}}}o(xt,"validateListPage");var bt=o(e=>typeof e.name=="string"&&T(e.inputSchema),"isTool"),we=o(e=>typeof e.uri=="string"&&(e.name===void 0||typeof e.name=="string"),"isResource"),Ee=o(e=>typeof e.uriTemplate=="string"&&(e.name===void 0||typeof e.name=="string"),"isResourceTemplate");function Se(e){return{...e,name:e.name??e.uri}}o(Se,"toResource");function _e(e){return{...e,name:e.name??e.uriTemplate}}o(_e,"toResourceTemplate");function xe(e){return e.nextCursor===void 0?{}:{nextCursor:e.nextCursor}}o(xe,"pageCursor");function Tt(e){if(!T(e)||!Array.isArray(e.contents))throw j("Invalid MCP resources/read result");for(let t of e.contents)if(!T(t)||typeof t.uri!="string"||typeof t.text!="string"&&typeof t.blob!="string")throw j("Invalid contents in MCP resources/read result");return e}o(Tt,"validateReadResourceResult");function Ct(e){if(!T(e)||e.content!==void 0&&!Array.isArray(e.content))throw new A(L.invalidRequest,"Invalid MCP tools/call result");return e.content===void 0?{...e,content:[]}:e}o(Ct,"validateCallToolResult");var Rt=class{static{o(this,"McpClient")}options;state="idle";transport;nextRequestId=1;serverInfoValue;serverCapabilitiesValue;instructionsValue;protocolVersionValue;pending=new Map;progressRequests=new Map;incoming=new Map;requestHandlers=new Map;notificationListeners=new Map;errorListeners=new Set;closeListeners=new Set;disposers=[];constructor(e){this.options=Object.freeze({...e}),this.requestHandlers.set("ping",()=>({}));let t=e.roots;t&&this.requestHandlers.set("roots/list",async()=>({roots:[...typeof t=="function"?await t():t]}))}get connectionState(){return this.state}get serverInfo(){return this.serverInfoValue}get serverCapabilities(){return this.serverCapabilitiesValue}get instructions(){return this.instructionsValue}get protocolVersion(){return this.protocolVersionValue}async connect(e){if(this.state!=="idle")throw new Error(`Cannot connect MCP client in ${this.state} state`);this.state="connecting",this.transport=e,this.disposers=[e.onMessage(t=>this.handleMessage(t)),e.onError(t=>this.emitError(t)),e.onClose(()=>this.handleTransportClose())];try{await e.start();let t={...this.options.capabilities};this.options.roots&&t.roots===void 0&&(t.roots={});let r=_t(await this.requestInternal("initialize",{protocolVersion:this.options.protocolVersion??oe,capabilities:t,clientInfo:{name:this.options.name,version:this.options.version,...this.options.title===void 0?{}:{title:this.options.title}}},{},!0));if(!Et.includes(r.protocolVersion))throw new Error(`MCP server selected unsupported protocol version ${r.protocolVersion}`);return this.protocolVersionValue=r.protocolVersion,this.serverInfoValue=r.serverInfo,this.serverCapabilitiesValue=r.capabilities,this.instructionsValue=r.instructions,e.setProtocolVersion?.(r.protocolVersion),await this.notifyInternal("notifications/initialized",void 0,!0),this.state="connected",r}catch(t){throw await this.close().catch(()=>{}),t}}request(e,t,r={}){return this.requestInternal(e,t,r,!1)}notify(e,t){return this.notifyInternal(e,t,!1)}setRequestHandler(e,t){return this.requestHandlers.set(e,t),()=>{this.requestHandlers.get(e)===t&&this.requestHandlers.delete(e)}}onNotification(e,t){let r=this.notificationListeners.get(e)??new Set;return this.notificationListeners.set(e,r),r.add(t),()=>{r.delete(t),r.size===0&&this.notificationListeners.delete(e)}}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onClose(e){return this.closeListeners.add(e),()=>this.closeListeners.delete(e)}async ping(e={}){await this.request("ping",void 0,e)}async listTools(e={}){return await this.listAll("tools/list","tools",bt,e)}async listResources(e={}){return(await this.listAll("resources/list","resources",we,e)).map(Se)}async listResourcesPage(e,t={}){let r=await this.listPage("resources/list","resources",we,e,t);return{resources:r.items.map(Se),...xe(r)}}async listResourceTemplates(e={}){return(await this.listAll("resources/templates/list","resourceTemplates",Ee,e)).map(_e)}async listResourceTemplatesPage(e,t={}){let r=await this.listPage("resources/templates/list","resourceTemplates",Ee,e,t);return{resourceTemplates:r.items.map(_e),...xe(r)}}async readResource(e,t={}){return Tt(await this.request("resources/read",{uri:e},t))}async listPage(e,t,r,i,s){return xt(e,t,await this.request(e,i===void 0?void 0:{cursor:i},s),r)}async listAll(e,t,r,i){let s=[],n=new Set,a;for(let l=0;l<ve;l++){let u=await this.listPage(e,t,r,a,i);if(s.push(...u.items),u.nextCursor===void 0)return s;if(n.has(u.nextCursor))throw new Error(`MCP ${e} returned duplicate cursor: ${u.nextCursor}`);n.add(u.nextCursor),a=u.nextCursor}throw new Error(`MCP ${e} exceeded ${ve} pages`)}async callTool(e,t,r={}){return Ct(await this.request("tools/call",{name:e,...t===void 0?{}:{arguments:t}},r))}async close(){let e=this.transport;this.transport=void 0,this.disposeTransportListeners(),this.markClosed(new I),await e?.close()}async requestInternal(e,t,r,i){let s=this.requireTransport(i);if(r.signal?.aborted)throw new ie;let n=this.nextRequestId++,a=r.onProgress?n:void 0,l=a===void 0?t:{...t,_meta:{...T(t?._meta)?t._meta:{},progressToken:a}},u={jsonrpc:"2.0",id:n,method:e,...l===void 0?{}:{params:l}};return new Promise((h,f)=>{let g={resolve:h,reject:f,timeoutMs:r.timeoutMs??this.options.requestTimeoutMs??St,timer:void 0,signal:r.signal,onAbort:o(()=>this.cancelPending(n,new ie,e!=="initialize",String(r.signal?.reason??"Aborted")),"onAbort"),sendController:new AbortController,cancellable:e!=="initialize",onProgress:r.onProgress,progressToken:a};this.pending.set(n,g),a!==void 0&&this.progressRequests.set(a,n),r.signal?.addEventListener("abort",g.onAbort,{once:!0}),this.armTimeout(n,g),s.send(u,{signal:g.sendController.signal}).catch(m=>this.cancelPending(n,m,!1))})}async notifyInternal(e,t,r){await this.requireTransport(r).send({jsonrpc:"2.0",method:e,...t===void 0?{}:{params:t}})}requireTransport(e){if(this.transport&&(this.state==="connected"||e&&this.state==="connecting"))return this.transport;throw new I(`MCP client is ${this.state}`)}handleMessage(e){if(ne(e)){this.handleResponse(e);return}if(se(e)){this.handleRequest(e);return}if(ge(e)){this.handleNotification(e.method,e.params);return}this.emitError(new A(L.invalidRequest,"Received invalid JSON-RPC message"))}handleResponse(e){let t=this.pending.get(e.id);if(!t){this.emitError(new Error(`Received response for unknown MCP request ${String(e.id)}`));return}this.removePending(e.id,t),"error"in e?t.reject(new A(e.error.code,e.error.message,e.error.data)):t.resolve(e.result)}async handleRequest(e){let t=this.transport;if(!t)return;let r=this.requestHandlers.get(e.method);if(!r){await t.send({jsonrpc:"2.0",id:e.id,error:{code:L.methodNotFound,message:`Method not found: ${e.method}`}}).catch(s=>this.emitError(s));return}let i=new AbortController;this.incoming.set(e.id,i);try{let s=await r(e.params,{signal:i.signal});await t.send({jsonrpc:"2.0",id:e.id,result:s??{}})}catch(s){let n=s instanceof A?{code:s.code,message:s.message,data:s.data}:{code:L.internalError,message:F(s).message};await t.send({jsonrpc:"2.0",id:e.id,error:n}).catch(a=>this.emitError(a))}finally{this.incoming.delete(e.id)}}handleNotification(e,t){e==="notifications/progress"?this.handleProgress(t):e==="notifications/cancelled"&&this.handleCancelled(t);for(let r of this.notificationListeners.get(e)??[])try{r(t)}catch(i){this.emitError(i)}}handleProgress(e){if(!T(e)||!B(e.progressToken)||typeof e.progress!="number")return;let t=this.progressRequests.get(e.progressToken),r=t===void 0?void 0:this.pending.get(t);if(!(t===void 0||!r)){this.armTimeout(t,r);try{r.onProgress?.(e)}catch(i){this.emitError(i)}}}handleCancelled(e){T(e)&&B(e.requestId)&&this.incoming.get(e.requestId)?.abort(e.reason)}armTimeout(e,t){t.timer&&clearTimeout(t.timer),!(!Number.isFinite(t.timeoutMs)||t.timeoutMs<=0)&&(t.timer=setTimeout(()=>{this.cancelPending(e,new wt(t.timeoutMs),t.cancellable,"Request timed out")},t.timeoutMs))}cancelPending(e,t,r,i){let s=this.pending.get(e);s&&(this.removePending(e,s),s.reject(t),r&&this.transport&&this.transport.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:e,...i?{reason:i}:{}}}).catch(n=>this.emitError(n)))}removePending(e,t){this.pending.delete(e),t.timer&&clearTimeout(t.timer),t.progressToken!==void 0&&this.progressRequests.delete(t.progressToken),t.signal?.removeEventListener("abort",t.onAbort),t.sendController.abort()}rejectPending(e){for(let[t,r]of this.pending)this.removePending(t,r),r.reject(e)}handleTransportClose(){this.markClosed(new I)}markClosed(e){let t=this.state==="closed";this.state="closed",this.rejectPending(e);for(let r of this.incoming.values())r.abort(e);if(this.incoming.clear(),!t)for(let r of[...this.closeListeners])try{r()}catch(i){this.emitError(i)}}emitError(e){let t=F(e);for(let r of this.errorListeners)r(t)}disposeTransportListeners(){for(let e of this.disposers.splice(0))e()}},Mt=me(lt(),1);import{spawn as Pt}from"node:child_process";import O from"node:process";var H=16*1024*1024,be=class{static{o(this,"TransportEvents")}messageListeners=new Set;errorListeners=new Set;closeListeners=new Set;closeEmitted=!1;onMessage(e){return this.messageListeners.add(e),()=>this.messageListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onClose(e){return this.closeListeners.add(e),()=>this.closeListeners.delete(e)}emitMessage(e){for(let t of this.messageListeners)t(e)}emitError(e){let t=F(e);for(let r of this.errorListeners)r(t)}emitClose(){if(!this.closeEmitted){this.closeEmitted=!0;for(let e of this.closeListeners)e()}}},Lt=64*1024,At=class{static{o(this,"JsonRpcLineReader")}options;stdoutChunks=[];stdoutPendingBytes=0;stderrBuffer=Buffer.alloc(0);constructor(e){this.options=e}get stderr(){return this.stderrBuffer.toString("utf8")}readStdout(e){let t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=this.options.maxMessageBytes??H,i=0;for(;;){let s=t.indexOf(10,i);if(s<0){i<t.length&&(this.stdoutChunks.push(Buffer.from(t.subarray(i))),this.stdoutPendingBytes+=t.length-i),this.stdoutPendingBytes>r&&(this.stdoutChunks=[],this.stdoutPendingBytes=0,this.options.onError(new Error(`MCP stdio message exceeds ${r} bytes`)));return}let n=t.subarray(i,s);if(this.stdoutChunks.length>0&&(this.stdoutChunks.push(n),n=Buffer.concat(this.stdoutChunks,this.stdoutPendingBytes+n.length),this.stdoutChunks=[],this.stdoutPendingBytes=0),i=s+1,n.length>r){this.options.onError(new Error(`MCP stdio message exceeds ${r} bytes`));continue}let a=n.toString("utf8").replace(/\r$/,"");if(a.trim())try{this.options.onMessage(G(JSON.parse(a)))}catch(l){this.options.onError(l)}}}readStderr(e){let t=this.options.maxStderrBytes??Lt;this.stderrBuffer=Buffer.concat([this.stderrBuffer,e]),this.stderrBuffer.length>t&&(this.stderrBuffer=this.stderrBuffer.subarray(-t)),this.options.onStderr?.(Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"))}end(){Buffer.concat(this.stdoutChunks).toString("utf8").trim()&&this.options.onError(new Error("MCP stdio server closed with an incomplete JSON-RPC message")),this.stdoutChunks=[],this.stdoutPendingBytes=0}},It=2e3,kt=500,z=O.platform!=="win32",ae=new Set,Te=!1;function le(e,t){let r=e.pid;if(O.platform==="win32"&&r!==void 0){if(e.exitCode!==null)return;Pt("taskkill",["/pid",String(r),"/T","/F"],{stdio:"ignore",windowsHide:!0}).on("error",()=>{});return}if(z&&r!==void 0)try{O.kill(-r,t);return}catch{}try{e.kill(t)}catch{}}o(le,"killProcessTree");function Ot(){Te||(Te=!0,O.once("exit",()=>{for(let e of ae)try{O.kill(-e,"SIGTERM")}catch{}}))}o(Ot,"installExitHook");var $t=class extends be{static{o(this,"StdioTransport")}options;child;lines;started=!1;closed=!1;constructor(e){super(),this.options=Object.freeze({...e,args:e.args?[...e.args]:void 0}),this.lines=new At({maxMessageBytes:this.options.maxMessageBytes,maxStderrBytes:this.options.maxStderrBytes,onStderr:this.options.onStderr,onMessage:o(t=>this.emitMessage(t),"onMessage"),onError:o(t=>this.emitError(t),"onError")})}get pid(){return this.child?.pid}get stderr(){return this.lines.stderr}async start(){if(this.started)throw new Error("MCP stdio transport already started");if(this.closed)throw new I;this.started=!0;let e=this.options.inheritEnv===!1?{...this.options.env}:{...O.env,...this.options.env},t=(0,Mt.default)(this.options.command,this.options.args??[],{cwd:this.options.cwd,env:e,stdio:["pipe","pipe",this.options.stderr==="inherit"?"inherit":"pipe"],windowsHide:!0,detached:z});this.child=t;let r=t.pid;z&&r!==void 0&&(Ot(),ae.add(r),t.once("close",()=>ae.delete(r))),t.stdout?.on("data",i=>this.lines.readStdout(i)),t.stdout?.on("error",i=>this.emitError(i)),t.stdin?.on("error",i=>{this.closed||this.emitError(i)}),t.stderr?.on("data",i=>this.lines.readStderr(i)),t.stderr?.on("error",i=>this.emitError(i)),t.on("close",()=>{this.child=void 0,this.lines.end(),this.emitClose()}),await new Promise((i,s)=>{let n=o(()=>{t.off("error",a),i()},"onSpawn"),a=o(l=>{t.off("spawn",n),s(l)},"onError");t.once("spawn",n),t.once("error",a)}),t.on("error",i=>{this.closed||this.emitError(i)})}async send(e){let t=this.child?.stdin;if(!this.started||this.closed||!t?.writable)throw new I;let r=`${JSON.stringify(e)}
1
+ var it=Object.defineProperty;var o=(e,t)=>it(e,"name",{value:t,configurable:!0});import{createRequire as st}from"node:module";const Vr=st(import.meta.url);import{fill as nt,getShellConfig as ot}from"./chunk-SE42OS3U.js";import{APP_TITLE as at,getAgentDir as U,getFileRevision as N,normalizePath as V,require_cross_spawn as lt,stripBom as te}from"./chunk-R47JBGS3.js";import{require_graceful_fs as fe}from"./chunk-XJFQKN3N.js";import{drainNewerDataFormatFiles as ut,t as ct,writeFileAtomicSync as pe}from"./chunk-SNBVCTMQ.js";import{__commonJS as P,__require as re,__toESM as me}from"./chunk-JXWJOIH4.js";var dt=P({"node_modules/proper-lockfile/node_modules/retry/lib/retry_operation.js"(e,t){function r(i,s){typeof s=="boolean"&&(s={forever:s}),this._originalTimeouts=JSON.parse(JSON.stringify(i)),this._timeouts=i,this._options=s||{},this._maxRetryTime=s&&s.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}o(r,"RetryOperation"),t.exports=r,r.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},r.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},r.prototype.retry=function(i){if(this._timeout&&clearTimeout(this._timeout),!i)return!1;var s=new Date().getTime();if(i&&s-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(i);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1;var a=this,l=setTimeout(function(){a._attempts++,a._operationTimeoutCb&&(a._timeout=setTimeout(function(){a._operationTimeoutCb(a._attempts)},a._operationTimeout),a._options.unref&&a._timeout.unref()),a._fn(a._attempts)},n);return this._options.unref&&l.unref(),!0},r.prototype.attempt=function(i,s){this._fn=i,s&&(s.timeout&&(this._operationTimeout=s.timeout),s.cb&&(this._operationTimeoutCb=s.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},r.prototype.try=function(i){console.log("Using RetryOperation.try() is deprecated"),this.attempt(i)},r.prototype.start=function(i){console.log("Using RetryOperation.start() is deprecated"),this.attempt(i)},r.prototype.start=r.prototype.try,r.prototype.errors=function(){return this._errors},r.prototype.attempts=function(){return this._attempts},r.prototype.mainError=function(){if(this._errors.length===0)return null;for(var i={},s=null,n=0,a=0;a<this._errors.length;a++){var l=this._errors[a],u=l.message,h=(i[u]||0)+1;i[u]=h,h>=n&&(s=l,n=h)}return s}}}),ht=P({"node_modules/proper-lockfile/node_modules/retry/lib/retry.js"(e){var t=dt();e.operation=function(r){var i=e.timeouts(r);return new t(i,{forever:r&&r.forever,unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(r){if(r instanceof Array)return[].concat(r);var i={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var s in r)i[s]=r[s];if(i.minTimeout>i.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],a=0;a<i.retries;a++)n.push(this.createTimeout(a,i));return r&&r.forever&&!n.length&&n.push(this.createTimeout(a,i)),n.sort(function(l,u){return l-u}),n},e.createTimeout=function(r,i){var s=i.randomize?Math.random()+1:1,n=Math.round(s*i.minTimeout*Math.pow(i.factor,r));return n=Math.min(n,i.maxTimeout),n},e.wrap=function(r,i,s){if(i instanceof Array&&(s=i,i=null),!s){s=[];for(var n in r)typeof r[n]=="function"&&s.push(n)}for(var a=0;a<s.length;a++){var l=s[a],u=r[l];r[l]=function(h){var f=e.operation(i),g=Array.prototype.slice.call(arguments,1),m=g.pop();g.push(function(w){f.retry(w)||(w&&(arguments[0]=f.mainError()),m.apply(this,arguments))}),f.attempt(function(){h.apply(r,g)})}.bind(r,u),r[l].options=i}}}}),ft=P({"node_modules/proper-lockfile/node_modules/retry/index.js"(e,t){t.exports=ht()}}),pt=P({"node_modules/signal-exit/signals.js"(e,t){t.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&t.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&t.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}}),mt=P({"node_modules/signal-exit/index.js"(e,t){var r=global.process,i=o(function(y){return y&&typeof y=="object"&&typeof y.removeListener=="function"&&typeof y.emit=="function"&&typeof y.reallyExit=="function"&&typeof y.listeners=="function"&&typeof y.kill=="function"&&typeof y.pid=="number"&&typeof y.on=="function"},"processOk");i(r)?(s=re("assert"),n=pt(),a=/^win/i.test(r.platform),l=re("events"),typeof l!="function"&&(l=l.EventEmitter),r.__signal_exit_emitter__?u=r.__signal_exit_emitter__:(u=r.__signal_exit_emitter__=new l,u.count=0,u.emitted={}),u.infinite||(u.setMaxListeners(1/0),u.infinite=!0),t.exports=function(y,p){if(!i(global.process))return function(){};s.equal(typeof y,"function","a callback must be provided for exit handler"),m===!1&&w();var c="exit";p&&p.alwaysLast&&(c="afterexit");var d=o(function(){u.removeListener(c,y),u.listeners("exit").length===0&&u.listeners("afterexit").length===0&&h()},"remove");return u.on(c,y),d},h=o(function(){!m||!i(global.process)||(m=!1,n.forEach(function(y){try{r.removeListener(y,g[y])}catch{}}),r.emit=b,r.reallyExit=v,u.count-=1)},"unload"),t.exports.unload=h,f=o(function(y,p,c){u.emitted[y]||(u.emitted[y]=!0,u.emit(y,p,c))},"emit"),g={},n.forEach(function(y){g[y]=function(){if(i(global.process)){var p=r.listeners(y);p.length===u.count&&(h(),f("exit",null,y),f("afterexit",null,y),a&&y==="SIGHUP"&&(y="SIGINT"),r.kill(r.pid,y))}}}),t.exports.signals=function(){return n},m=!1,w=o(function(){m||!i(global.process)||(m=!0,u.count+=1,n=n.filter(function(y){try{return r.on(y,g[y]),!0}catch{return!1}}),r.emit=S,r.reallyExit=x)},"load"),t.exports.load=w,v=r.reallyExit,x=o(function(y){i(global.process)&&(r.exitCode=y||0,f("exit",r.exitCode,null),f("afterexit",r.exitCode,null),v.call(r,r.exitCode))},"processReallyExit"),b=r.emit,S=o(function(y,p){if(y==="exit"&&i(global.process)){p!==void 0&&(r.exitCode=p);var c=b.apply(this,arguments);return f("exit",r.exitCode,null),f("afterexit",r.exitCode,null),c}else return b.apply(this,arguments)},"processEmit")):t.exports=function(){return function(){}};var s,n,a,l,u,h,f,g,m,w,v,x,b,S}}),yt=P({"node_modules/proper-lockfile/lib/mtime-precision.js"(e,t){"use strict";var r=Symbol();function i(n,a,l){let u=a[r];if(u)return a.stat(n,(f,g)=>{if(f)return l(f);l(null,g.mtime,u)});let h=new Date(Math.ceil(Date.now()/1e3)*1e3+5);a.utimes(n,h,h,f=>{if(f)return l(f);a.stat(n,(g,m)=>{if(g)return l(g);let w=m.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(a,r,{value:w}),l(null,m.mtime,w)})})}o(i,"probe");function s(n){let a=Date.now();return n==="s"&&(a=Math.ceil(a/1e3)*1e3),new Date(a)}o(s,"getMtime"),t.exports.probe=i,t.exports.getMtime=s}}),gt=P({"node_modules/proper-lockfile/lib/lockfile.js"(e,t){"use strict";var r=re("path"),i=fe(),s=ft(),n=mt(),a=yt(),l={};function u(p,c){return c.lockfilePath||`${p}.lock`}o(u,"getLockFile");function h(p,c,d){if(!c.realpath)return d(null,r.resolve(p));c.fs.realpath(p,d)}o(h,"resolveCanonicalPath");function f(p,c,d){let E=u(p,c);c.fs.mkdir(E,C=>{if(!C)return a.probe(E,c.fs,(_,R,M)=>{if(_)return c.fs.rmdir(E,()=>{}),d(_);d(null,R,M)});if(C.code!=="EEXIST")return d(C);if(c.stale<=0)return d(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:p}));c.fs.stat(E,(_,R)=>{if(_)return _.code==="ENOENT"?f(p,{...c,stale:0},d):d(_);if(!g(R,c))return d(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:p}));m(p,c,M=>{if(M)return d(M);f(p,{...c,stale:0},d)})})})}o(f,"acquireLock");function g(p,c){return p.mtime.getTime()<Date.now()-c.stale}o(g,"isLockStale");function m(p,c,d){c.fs.rmdir(u(p,c),E=>{if(E&&E.code!=="ENOENT")return d(E);d()})}o(m,"removeLock");function w(p,c){let d=l[p];d.updateTimeout||(d.updateDelay=d.updateDelay||c.update,d.updateTimeout=setTimeout(()=>{d.updateTimeout=null,c.fs.stat(d.lockfilePath,(E,C)=>{let _=d.lastUpdate+c.stale<Date.now();if(E)return E.code==="ENOENT"||_?v(p,d,Object.assign(E,{code:"ECOMPROMISED"})):(d.updateDelay=1e3,w(p,c));if(d.mtime.getTime()!==C.mtime.getTime())return v(p,d,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let R=a.getMtime(d.mtimePrecision);c.fs.utimes(d.lockfilePath,R,R,M=>{let Q=d.lastUpdate+c.stale<Date.now();if(!d.released){if(M)return M.code==="ENOENT"||Q?v(p,d,Object.assign(M,{code:"ECOMPROMISED"})):(d.updateDelay=1e3,w(p,c));d.mtime=R,d.lastUpdate=Date.now(),d.updateDelay=null,w(p,c)}})})},d.updateDelay),d.updateTimeout.unref&&d.updateTimeout.unref())}o(w,"updateLock");function v(p,c,d){c.released=!0,c.updateTimeout&&clearTimeout(c.updateTimeout),l[p]===c&&delete l[p],c.options.onCompromised(d)}o(v,"setLockAsCompromised");function x(p,c,d){c={stale:1e4,update:null,realpath:!0,retries:0,fs:i,onCompromised:o(E=>{throw E},"onCompromised"),...c},c.retries=c.retries||0,c.retries=typeof c.retries=="number"?{retries:c.retries}:c.retries,c.stale=Math.max(c.stale||0,2e3),c.update=c.update==null?c.stale/2:c.update||0,c.update=Math.max(Math.min(c.update,c.stale/2),1e3),h(p,c,(E,C)=>{if(E)return d(E);let _=s.operation(c.retries);_.attempt(()=>{f(C,c,(R,M,Q)=>{if(_.retry(R))return;if(R)return d(_.mainError());let rt=l[C]={lockfilePath:u(C,c),mtime:M,mtimePrecision:Q,options:c,lastUpdate:Date.now()};w(C,c),d(null,ee=>{if(rt.released)return ee&&ee(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));b(C,{...c,realpath:!1},ee)})})})})}o(x,"lock");function b(p,c,d){c={fs:i,realpath:!0,...c},h(p,c,(E,C)=>{if(E)return d(E);let _=l[C];if(!_)return d(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));_.updateTimeout&&clearTimeout(_.updateTimeout),_.released=!0,delete l[C],m(C,c,d)})}o(b,"unlock");function S(p,c,d){c={stale:1e4,realpath:!0,fs:i,...c},c.stale=Math.max(c.stale||0,2e3),h(p,c,(E,C)=>{if(E)return d(E);c.fs.stat(u(C,c),(_,R)=>_?_.code==="ENOENT"?d(null,!1):d(_):d(null,!g(R,c)))})}o(S,"check");function y(){return l}o(y,"getLocks"),n(()=>{for(let p in l){let c=l[p].options;try{c.fs.rmdirSync(u(p,c))}catch{}}}),t.exports.lock=x,t.exports.unlock=b,t.exports.check=S,t.exports.getLocks=y}}),vt=P({"node_modules/proper-lockfile/lib/adapter.js"(e,t){"use strict";var r=fe();function i(l){let u=["mkdir","realpath","stat","rmdir","utimes"],h={...l};return u.forEach(f=>{h[f]=(...g)=>{let m=g.pop(),w;try{w=l[`${f}Sync`](...g)}catch(v){return m(v)}m(null,w)}}),h}o(i,"createSyncFs");function s(l){return(...u)=>new Promise((h,f)=>{u.push((g,m)=>{g?f(g):h(m)}),l(...u)})}o(s,"toPromise");function n(l){return(...u)=>{let h,f;if(u.push((g,m)=>{h=g,f=m}),l(...u),h)throw h;return f}}o(n,"toSync");function a(l){if(l={...l},l.fs=i(l.fs||r),typeof l.retries=="number"&&l.retries>0||l.retries&&typeof l.retries.retries=="number"&&l.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return l}o(a,"toSyncOptions"),t.exports={toPromise:s,toSync:n,toSyncOptions:a}}}),ye=P({"node_modules/proper-lockfile/index.js"(e,t){"use strict";var r=gt(),{toPromise:i,toSync:s,toSyncOptions:n}=vt();async function a(m,w){let v=await i(r.lock)(m,w);return i(v)}o(a,"lock");function l(m,w){let v=s(r.lock)(m,n(w));return s(v)}o(l,"lockSync");function u(m,w){return i(r.unlock)(m,w)}o(u,"unlock");function h(m,w){return s(r.unlock)(m,n(w))}o(h,"unlockSync");function f(m,w){return i(r.check)(m,w)}o(f,"check");function g(m,w){return s(r.check)(m,n(w))}o(g,"checkSync"),t.exports=a,t.exports.lock=a,t.exports.unlock=u,t.exports.lockSync=l,t.exports.unlockSync=h,t.exports.check=f,t.exports.checkSync=g}}),L={parseError:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internalError:-32603},A=class extends Error{static{o(this,"McpError")}code;data;constructor(e,t,r){super(t),this.name="McpError",this.code=e,this.data=r}},I=class extends Error{static{o(this,"McpConnectionClosedError")}constructor(e="MCP connection closed"){super(e),this.name="McpConnectionClosedError"}},wt=class extends Error{static{o(this,"McpTimeoutError")}timeoutMs;constructor(e){super(`MCP request timed out after ${e}ms`),this.name="McpTimeoutError",this.timeoutMs=e}},ie=class extends Error{static{o(this,"McpAbortError")}constructor(e="MCP request aborted"){super(e),this.name="AbortError"}};function T(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(T,"isObject");function F(e){return e instanceof Error?e:new Error(String(e))}o(F,"toError");function B(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}o(B,"isJsonRpcId");function se(e){return T(e)&&e.jsonrpc==="2.0"&&B(e.id)&&typeof e.method=="string"}o(se,"isJsonRpcRequest");function ge(e){return T(e)&&e.jsonrpc==="2.0"&&!("id"in e)&&typeof e.method=="string"}o(ge,"isJsonRpcNotification");function ne(e){return!T(e)||e.jsonrpc!=="2.0"||!B(e.id)?!1:"result"in e?!("error"in e):!("error"in e)||!T(e.error)?!1:typeof e.error.code=="number"&&typeof e.error.message=="string"}o(ne,"isJsonRpcResponse");function G(e){if(se(e)||ge(e)||ne(e))return e;throw new A(L.invalidRequest,"Invalid JSON-RPC message")}o(G,"parseJsonRpcMessage");var oe="2025-11-25",Et=[oe,"2025-06-18","2025-03-26","2024-11-05"],St=3e4,ve=1e3;function _t(e){if(!T(e)||typeof e.protocolVersion!="string"||!T(e.capabilities)||!T(e.serverInfo)||typeof e.serverInfo.name!="string"||typeof e.serverInfo.version!="string"||e.instructions!==void 0&&typeof e.instructions!="string")throw new A(L.invalidRequest,"Invalid MCP initialize result");return e}o(_t,"validateInitializeResult");function j(e){return new A(L.invalidRequest,e)}o(j,"invalid");function xt(e,t,r,i){let s=T(r)?r[t]:void 0;if(!T(r)||!Array.isArray(s))throw j(`Invalid MCP ${e} result`);for(let a of s)if(!T(a)||!i(a))throw j(`Invalid entry in MCP ${e} result`);let n=r.nextCursor===null||r.nextCursor===""?void 0:r.nextCursor;if(n!==void 0&&typeof n!="string")throw j(`Invalid MCP ${e} cursor`);return{items:s,...n===void 0?{}:{nextCursor:n}}}o(xt,"validateListPage");var bt=o(e=>typeof e.name=="string"&&T(e.inputSchema),"isTool"),we=o(e=>typeof e.uri=="string"&&(e.name===void 0||typeof e.name=="string"),"isResource"),Ee=o(e=>typeof e.uriTemplate=="string"&&(e.name===void 0||typeof e.name=="string"),"isResourceTemplate");function Se(e){return{...e,name:e.name??e.uri}}o(Se,"toResource");function _e(e){return{...e,name:e.name??e.uriTemplate}}o(_e,"toResourceTemplate");function xe(e){return e.nextCursor===void 0?{}:{nextCursor:e.nextCursor}}o(xe,"pageCursor");function Tt(e){if(!T(e)||!Array.isArray(e.contents))throw j("Invalid MCP resources/read result");for(let t of e.contents)if(!T(t)||typeof t.uri!="string"||typeof t.text!="string"&&typeof t.blob!="string")throw j("Invalid contents in MCP resources/read result");return e}o(Tt,"validateReadResourceResult");function Ct(e){if(!T(e)||e.content!==void 0&&!Array.isArray(e.content))throw new A(L.invalidRequest,"Invalid MCP tools/call result");return e.content===void 0?{...e,content:[]}:e}o(Ct,"validateCallToolResult");var Rt=class{static{o(this,"McpClient")}options;state="idle";transport;nextRequestId=1;serverInfoValue;serverCapabilitiesValue;instructionsValue;protocolVersionValue;pending=new Map;progressRequests=new Map;incoming=new Map;requestHandlers=new Map;notificationListeners=new Map;errorListeners=new Set;closeListeners=new Set;disposers=[];constructor(e){this.options=Object.freeze({...e}),this.requestHandlers.set("ping",()=>({}));let t=e.roots;t&&this.requestHandlers.set("roots/list",async()=>({roots:[...typeof t=="function"?await t():t]}))}get connectionState(){return this.state}get serverInfo(){return this.serverInfoValue}get serverCapabilities(){return this.serverCapabilitiesValue}get instructions(){return this.instructionsValue}get protocolVersion(){return this.protocolVersionValue}async connect(e){if(this.state!=="idle")throw new Error(`Cannot connect MCP client in ${this.state} state`);this.state="connecting",this.transport=e,this.disposers=[e.onMessage(t=>this.handleMessage(t)),e.onError(t=>this.emitError(t)),e.onClose(()=>this.handleTransportClose())];try{await e.start();let t={...this.options.capabilities};this.options.roots&&t.roots===void 0&&(t.roots={});let r=_t(await this.requestInternal("initialize",{protocolVersion:this.options.protocolVersion??oe,capabilities:t,clientInfo:{name:this.options.name,version:this.options.version,...this.options.title===void 0?{}:{title:this.options.title}}},{},!0));if(!Et.includes(r.protocolVersion))throw new Error(`MCP server selected unsupported protocol version ${r.protocolVersion}`);return this.protocolVersionValue=r.protocolVersion,this.serverInfoValue=r.serverInfo,this.serverCapabilitiesValue=r.capabilities,this.instructionsValue=r.instructions,e.setProtocolVersion?.(r.protocolVersion),await this.notifyInternal("notifications/initialized",void 0,!0),this.state="connected",r}catch(t){throw await this.close().catch(()=>{}),t}}request(e,t,r={}){return this.requestInternal(e,t,r,!1)}notify(e,t){return this.notifyInternal(e,t,!1)}setRequestHandler(e,t){return this.requestHandlers.set(e,t),()=>{this.requestHandlers.get(e)===t&&this.requestHandlers.delete(e)}}onNotification(e,t){let r=this.notificationListeners.get(e)??new Set;return this.notificationListeners.set(e,r),r.add(t),()=>{r.delete(t),r.size===0&&this.notificationListeners.delete(e)}}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onClose(e){return this.closeListeners.add(e),()=>this.closeListeners.delete(e)}async ping(e={}){await this.request("ping",void 0,e)}async listTools(e={}){return await this.listAll("tools/list","tools",bt,e)}async listResources(e={}){return(await this.listAll("resources/list","resources",we,e)).map(Se)}async listResourcesPage(e,t={}){let r=await this.listPage("resources/list","resources",we,e,t);return{resources:r.items.map(Se),...xe(r)}}async listResourceTemplates(e={}){return(await this.listAll("resources/templates/list","resourceTemplates",Ee,e)).map(_e)}async listResourceTemplatesPage(e,t={}){let r=await this.listPage("resources/templates/list","resourceTemplates",Ee,e,t);return{resourceTemplates:r.items.map(_e),...xe(r)}}async readResource(e,t={}){return Tt(await this.request("resources/read",{uri:e},t))}async listPage(e,t,r,i,s){return xt(e,t,await this.request(e,i===void 0?void 0:{cursor:i},s),r)}async listAll(e,t,r,i){let s=[],n=new Set,a;for(let l=0;l<ve;l++){let u=await this.listPage(e,t,r,a,i);if(s.push(...u.items),u.nextCursor===void 0)return s;if(n.has(u.nextCursor))throw new Error(`MCP ${e} returned duplicate cursor: ${u.nextCursor}`);n.add(u.nextCursor),a=u.nextCursor}throw new Error(`MCP ${e} exceeded ${ve} pages`)}async callTool(e,t,r={}){return Ct(await this.request("tools/call",{name:e,...t===void 0?{}:{arguments:t}},r))}async close(){let e=this.transport;this.transport=void 0,this.disposeTransportListeners(),this.markClosed(new I),await e?.close()}async requestInternal(e,t,r,i){let s=this.requireTransport(i);if(r.signal?.aborted)throw new ie;let n=this.nextRequestId++,a=r.onProgress?n:void 0,l=a===void 0?t:{...t,_meta:{...T(t?._meta)?t._meta:{},progressToken:a}},u={jsonrpc:"2.0",id:n,method:e,...l===void 0?{}:{params:l}};return new Promise((h,f)=>{let g={resolve:h,reject:f,timeoutMs:r.timeoutMs??this.options.requestTimeoutMs??St,timer:void 0,signal:r.signal,onAbort:o(()=>this.cancelPending(n,new ie,e!=="initialize",String(r.signal?.reason??"Aborted")),"onAbort"),sendController:new AbortController,cancellable:e!=="initialize",onProgress:r.onProgress,progressToken:a};this.pending.set(n,g),a!==void 0&&this.progressRequests.set(a,n),r.signal?.addEventListener("abort",g.onAbort,{once:!0}),this.armTimeout(n,g),s.send(u,{signal:g.sendController.signal}).catch(m=>this.cancelPending(n,m,!1))})}async notifyInternal(e,t,r){await this.requireTransport(r).send({jsonrpc:"2.0",method:e,...t===void 0?{}:{params:t}})}requireTransport(e){if(this.transport&&(this.state==="connected"||e&&this.state==="connecting"))return this.transport;throw new I(`MCP client is ${this.state}`)}handleMessage(e){if(ne(e)){this.handleResponse(e);return}if(se(e)){this.handleRequest(e);return}if(ge(e)){this.handleNotification(e.method,e.params);return}this.emitError(new A(L.invalidRequest,"Received invalid JSON-RPC message"))}handleResponse(e){let t=this.pending.get(e.id);if(!t){this.emitError(new Error(`Received response for unknown MCP request ${String(e.id)}`));return}this.removePending(e.id,t),"error"in e?t.reject(new A(e.error.code,e.error.message,e.error.data)):t.resolve(e.result)}async handleRequest(e){let t=this.transport;if(!t)return;let r=this.requestHandlers.get(e.method);if(!r){await t.send({jsonrpc:"2.0",id:e.id,error:{code:L.methodNotFound,message:`Method not found: ${e.method}`}}).catch(s=>this.emitError(s));return}let i=new AbortController;this.incoming.set(e.id,i);try{let s=await r(e.params,{signal:i.signal});await t.send({jsonrpc:"2.0",id:e.id,result:s??{}})}catch(s){let n=s instanceof A?{code:s.code,message:s.message,data:s.data}:{code:L.internalError,message:F(s).message};await t.send({jsonrpc:"2.0",id:e.id,error:n}).catch(a=>this.emitError(a))}finally{this.incoming.delete(e.id)}}handleNotification(e,t){e==="notifications/progress"?this.handleProgress(t):e==="notifications/cancelled"&&this.handleCancelled(t);for(let r of this.notificationListeners.get(e)??[])try{r(t)}catch(i){this.emitError(i)}}handleProgress(e){if(!T(e)||!B(e.progressToken)||typeof e.progress!="number")return;let t=this.progressRequests.get(e.progressToken),r=t===void 0?void 0:this.pending.get(t);if(!(t===void 0||!r)){this.armTimeout(t,r);try{r.onProgress?.(e)}catch(i){this.emitError(i)}}}handleCancelled(e){T(e)&&B(e.requestId)&&this.incoming.get(e.requestId)?.abort(e.reason)}armTimeout(e,t){t.timer&&clearTimeout(t.timer),!(!Number.isFinite(t.timeoutMs)||t.timeoutMs<=0)&&(t.timer=setTimeout(()=>{this.cancelPending(e,new wt(t.timeoutMs),t.cancellable,"Request timed out")},t.timeoutMs))}cancelPending(e,t,r,i){let s=this.pending.get(e);s&&(this.removePending(e,s),s.reject(t),r&&this.transport&&this.transport.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:e,...i?{reason:i}:{}}}).catch(n=>this.emitError(n)))}removePending(e,t){this.pending.delete(e),t.timer&&clearTimeout(t.timer),t.progressToken!==void 0&&this.progressRequests.delete(t.progressToken),t.signal?.removeEventListener("abort",t.onAbort),t.sendController.abort()}rejectPending(e){for(let[t,r]of this.pending)this.removePending(t,r),r.reject(e)}handleTransportClose(){this.markClosed(new I)}markClosed(e){let t=this.state==="closed";this.state="closed",this.rejectPending(e);for(let r of this.incoming.values())r.abort(e);if(this.incoming.clear(),!t)for(let r of[...this.closeListeners])try{r()}catch(i){this.emitError(i)}}emitError(e){let t=F(e);for(let r of this.errorListeners)r(t)}disposeTransportListeners(){for(let e of this.disposers.splice(0))e()}},Mt=me(lt(),1);import{spawn as Pt}from"node:child_process";import O from"node:process";var H=16*1024*1024,be=class{static{o(this,"TransportEvents")}messageListeners=new Set;errorListeners=new Set;closeListeners=new Set;closeEmitted=!1;onMessage(e){return this.messageListeners.add(e),()=>this.messageListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onClose(e){return this.closeListeners.add(e),()=>this.closeListeners.delete(e)}emitMessage(e){for(let t of this.messageListeners)t(e)}emitError(e){let t=F(e);for(let r of this.errorListeners)r(t)}emitClose(){if(!this.closeEmitted){this.closeEmitted=!0;for(let e of this.closeListeners)e()}}},Lt=64*1024,At=class{static{o(this,"JsonRpcLineReader")}options;stdoutChunks=[];stdoutPendingBytes=0;stderrBuffer=Buffer.alloc(0);constructor(e){this.options=e}get stderr(){return this.stderrBuffer.toString("utf8")}readStdout(e){let t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=this.options.maxMessageBytes??H,i=0;for(;;){let s=t.indexOf(10,i);if(s<0){i<t.length&&(this.stdoutChunks.push(Buffer.from(t.subarray(i))),this.stdoutPendingBytes+=t.length-i),this.stdoutPendingBytes>r&&(this.stdoutChunks=[],this.stdoutPendingBytes=0,this.options.onError(new Error(`MCP stdio message exceeds ${r} bytes`)));return}let n=t.subarray(i,s);if(this.stdoutChunks.length>0&&(this.stdoutChunks.push(n),n=Buffer.concat(this.stdoutChunks,this.stdoutPendingBytes+n.length),this.stdoutChunks=[],this.stdoutPendingBytes=0),i=s+1,n.length>r){this.options.onError(new Error(`MCP stdio message exceeds ${r} bytes`));continue}let a=n.toString("utf8").replace(/\r$/,"");if(a.trim())try{this.options.onMessage(G(JSON.parse(a)))}catch(l){this.options.onError(l)}}}readStderr(e){let t=this.options.maxStderrBytes??Lt;this.stderrBuffer=Buffer.concat([this.stderrBuffer,e]),this.stderrBuffer.length>t&&(this.stderrBuffer=this.stderrBuffer.subarray(-t)),this.options.onStderr?.(Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"))}end(){Buffer.concat(this.stdoutChunks).toString("utf8").trim()&&this.options.onError(new Error("MCP stdio server closed with an incomplete JSON-RPC message")),this.stdoutChunks=[],this.stdoutPendingBytes=0}},It=2e3,kt=500,z=O.platform!=="win32",ae=new Set,Te=!1;function le(e,t){let r=e.pid;if(O.platform==="win32"&&r!==void 0){if(e.exitCode!==null)return;Pt("taskkill",["/pid",String(r),"/T","/F"],{stdio:"ignore",windowsHide:!0}).on("error",()=>{});return}if(z&&r!==void 0)try{O.kill(-r,t);return}catch{}try{e.kill(t)}catch{}}o(le,"killProcessTree");function Ot(){Te||(Te=!0,O.once("exit",()=>{for(let e of ae)try{O.kill(-e,"SIGTERM")}catch{}}))}o(Ot,"installExitHook");var $t=class extends be{static{o(this,"StdioTransport")}options;child;lines;started=!1;closed=!1;constructor(e){super(),this.options=Object.freeze({...e,args:e.args?[...e.args]:void 0}),this.lines=new At({maxMessageBytes:this.options.maxMessageBytes,maxStderrBytes:this.options.maxStderrBytes,onStderr:this.options.onStderr,onMessage:o(t=>this.emitMessage(t),"onMessage"),onError:o(t=>this.emitError(t),"onError")})}get pid(){return this.child?.pid}get stderr(){return this.lines.stderr}async start(){if(this.started)throw new Error("MCP stdio transport already started");if(this.closed)throw new I;this.started=!0;let e=this.options.inheritEnv===!1?{...this.options.env}:{...O.env,...this.options.env},t=(0,Mt.default)(this.options.command,this.options.args??[],{cwd:this.options.cwd,env:e,stdio:["pipe","pipe",this.options.stderr==="inherit"?"inherit":"pipe"],windowsHide:!0,detached:z});this.child=t;let r=t.pid;z&&r!==void 0&&(Ot(),ae.add(r),t.once("close",()=>ae.delete(r))),t.stdout?.on("data",i=>this.lines.readStdout(i)),t.stdout?.on("error",i=>this.emitError(i)),t.stdin?.on("error",i=>{this.closed||this.emitError(i)}),t.stderr?.on("data",i=>this.lines.readStderr(i)),t.stderr?.on("error",i=>this.emitError(i)),t.on("close",()=>{this.child=void 0,this.lines.end(),this.emitClose()}),await new Promise((i,s)=>{let n=o(()=>{t.off("error",a),i()},"onSpawn"),a=o(l=>{t.off("spawn",n),s(l)},"onError");t.once("spawn",n),t.once("error",a)}),t.on("error",i=>{this.closed||this.emitError(i)})}async send(e){let t=this.child?.stdin;if(!this.started||this.closed||!t?.writable)throw new I;let r=`${JSON.stringify(e)}
2
2
  `;await new Promise((i,s)=>{t.write(r,n=>n?s(n):i())})}async close(){if(this.closed)return;this.closed=!0;let e=this.child;if(!e){this.emitClose();return}if(!z&&(e.exitCode!==null||e.signalCode!==null)){e.stdin?.end();return}let t=this.options.closeTimeoutMs??It;await new Promise(r=>{let i=[];e.once("close",()=>{for(let n of i)clearTimeout(n);le(e,"SIGTERM"),r()});let s=Math.min(kt,t);i.push(setTimeout(()=>le(e,"SIGTERM"),s)),i.push(setTimeout(()=>le(e,"SIGKILL"),s+t)),e.stdin?.end()})}},Dt=8*1024,Ce=500,Nt=1e3,jt=3e4,qt=5;async function Ut(e,t){let r=e.getReader(),i=new TextDecoder,s="",n,a,l=[],u=0,h=t.maxEventBytes??H,f=o(()=>{if(l.length===0){n=void 0,a=void 0;return}let v=l.join(`
3
3
  `);t.onEvent({...n?{event:n}:{},data:v,...a?{id:a}:{}}),n=void 0,a=void 0,l=[],u=0},"dispatch"),g=o(v=>{if(v===""){f();return}if(v.startsWith(":"))return;let x=v.indexOf(":"),b=x<0?v:v.slice(0,x),S=x<0?"":v.slice(x+1);if(S.startsWith(" ")&&(S=S.slice(1)),b==="data"){if(u+=Buffer.byteLength(S)+(l.length>0?1:0),u>h)throw new Error(`MCP SSE event exceeds ${h} bytes`);l.push(S)}else b==="event"?n=S:b==="id"&&!S.includes("\0")?(a=S,t.onId?.(S)):b==="retry"&&/^\d+$/.test(S)&&t.onRetry?.(Number(S))},"processLine"),m=!1,w=o(()=>{let v=0;for(let x=0;x<s.length;x++){let b=s[x];b!=="\r"&&b!==`
4
4
  `||(g(s.slice(v,x)),b==="\r"&&(x+1<s.length?s[x+1]===`
@@ -1 +1 @@
1
- var R=Object.defineProperty;var o=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createRequire as b}from"node:module";const S=b(import.meta.url);import{retryProviderRequest as w}from"./chunk-ML5DIOWR.js";import{headersToRecord as q,providerHeadersToRecord as k}from"./chunk-UTB4DTYQ.js";import{calculateCost as x}from"./chunk-K4B5ABCQ.js";import{getIdentityHeaders as E}from"./chunk-SCYK4XNE.js";function $(e,r,a){let i=new Error(`${e} returned ${r.status}`);return i.status=r.status,i.headers=r.headers,i.body=a,i}o($,"httpError");function T(e){let r=new Error(`Request timed out after ${e}ms`);return r.name="TimeoutError",r.status=void 0,r.headers=void 0,r.body="",r}o(T,"timeoutError");function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(m,"isRecord");function _(e,r,a){if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${e} returned an invalid ${a}`);return r}o(_,"requiredNumber");function j(e,r,a,i){return k(E(e,i),{authorization:`Bearer ${r}`,"content-type":"application/json"},e.headers,a)??{}}o(j,"requestHeaders");async function A(e,r,a,i,t,y){if(!t?.apiKey)throw new Error(`No API key for provider: ${a.provider}`);let h=t.apiKey,u=i,d=await t.onPayload?.(u,a);d!==void 0&&(u=d);let l=t.fetch??globalThis.fetch,{response:c,json:p}=await w(async()=>{let s=t.timeoutMs!==void 0?AbortSignal.timeout(t.timeoutMs):void 0,g=t.signal&&s?AbortSignal.any([t.signal,s]):t.signal??s;try{let n=await l(r,{method:"POST",headers:j(a,h,t.headers,t.identity),body:JSON.stringify(u),signal:g});if(!n.ok)throw $(e,n,await n.text());return{response:n,json:await n.json()}}catch(n){throw s?.aborted&&!t.signal?.aborted?T(t.timeoutMs):n}},{maxRetries:t.maxRetries??2,maxRetryDelayMs:t.maxRetryDelayMs,signal:t.signal,noRetryStatuses:y});return await t.onResponse?.({status:c.status,headers:q(c.headers)},a),p}o(A,"postClassifierRequest");function f(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}o(f,"tokenCount");function C(e,r){if(!m(e)||e.input_tokens===void 0&&e.output_tokens===void 0)return;let a=f(e.input_tokens),i=f(e.output_tokens),t={input:a,output:i,cacheRead:0,cacheWrite:0,totalTokens:a+i,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return x(r,t),t}o(C,"parseClassifierUsage");export{m as isRecord,C as parseClassifierUsage,A as postClassifierRequest,_ as requiredNumber};
1
+ var R=Object.defineProperty;var o=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createRequire as b}from"node:module";const S=b(import.meta.url);import{retryProviderRequest as w}from"./chunk-ML5DIOWR.js";import{headersToRecord as q,providerHeadersToRecord as k}from"./chunk-UTB4DTYQ.js";import{calculateCost as x}from"./chunk-2XX4WZT6.js";import{getIdentityHeaders as E}from"./chunk-44EXLOHK.js";function $(e,r,a){let i=new Error(`${e} returned ${r.status}`);return i.status=r.status,i.headers=r.headers,i.body=a,i}o($,"httpError");function T(e){let r=new Error(`Request timed out after ${e}ms`);return r.name="TimeoutError",r.status=void 0,r.headers=void 0,r.body="",r}o(T,"timeoutError");function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(m,"isRecord");function _(e,r,a){if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${e} returned an invalid ${a}`);return r}o(_,"requiredNumber");function j(e,r,a,i){return k(E(e,i),{authorization:`Bearer ${r}`,"content-type":"application/json"},e.headers,a)??{}}o(j,"requestHeaders");async function A(e,r,a,i,t,y){if(!t?.apiKey)throw new Error(`No API key for provider: ${a.provider}`);let h=t.apiKey,u=i,d=await t.onPayload?.(u,a);d!==void 0&&(u=d);let l=t.fetch??globalThis.fetch,{response:c,json:p}=await w(async()=>{let s=t.timeoutMs!==void 0?AbortSignal.timeout(t.timeoutMs):void 0,g=t.signal&&s?AbortSignal.any([t.signal,s]):t.signal??s;try{let n=await l(r,{method:"POST",headers:j(a,h,t.headers,t.identity),body:JSON.stringify(u),signal:g});if(!n.ok)throw $(e,n,await n.text());return{response:n,json:await n.json()}}catch(n){throw s?.aborted&&!t.signal?.aborted?T(t.timeoutMs):n}},{maxRetries:t.maxRetries??2,maxRetryDelayMs:t.maxRetryDelayMs,signal:t.signal,noRetryStatuses:y});return await t.onResponse?.({status:c.status,headers:q(c.headers)},a),p}o(A,"postClassifierRequest");function f(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}o(f,"tokenCount");function C(e,r){if(!m(e)||e.input_tokens===void 0&&e.output_tokens===void 0)return;let a=f(e.input_tokens),i=f(e.output_tokens),t={input:a,output:i,cacheRead:0,cacheWrite:0,totalTokens:a+i,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return x(r,t),t}o(C,"parseClassifierUsage");export{m as isRecord,C as parseClassifierUsage,A as postClassifierRequest,_ as requiredNumber};
@@ -1 +1 @@
1
- var O=Object.defineProperty;var n=(t,e)=>O(t,"name",{value:e,configurable:!0});import{createRequire as S}from"node:module";const G=S(import.meta.url);import{getAgentDir as L}from"./chunk-R47JBGS3.js";import{t as k}from"./chunk-XRF4A4KI.js";var h=["planner","executor","reviewer","escalate"],v={planner:"claude-opus-5-5",executor:"deepseek-flash",reviewer:"gpt-6.1-sol",escalate:"claude-opus-5-5"};function E(t){let e=t.toLowerCase();return/claude/.test(e)?"anthropic":/^gpt|^o\d|codex/.test(e)?"openai":/gemini/.test(e)?"google":/grok/.test(e)?"xai":/deepseek/.test(e)?"deepseek":/glm/.test(e)?"zhipu":/kimi/.test(e)?"moonshot":/qwen/.test(e)?"alibaba":/minimax/.test(e)?"minimax":e.split(/[-_/.]/)[0]??e}n(E,"vendorOf");var I=["deepseek","zhipu","moonshot","alibaba","minimax"];function F(t){return I.includes(E(t))}n(F,"isDomesticModel");function A(t){return t.cost.input>0&&t.cost.output>0}n(A,"isPriced");function s(t){return(t.cost.input+t.cost.output)/2}n(s,"blendedPrice");var P=/(?:^|[-_/.:])(?:flash|mini|lite|nano|haiku|small|air|tiny|instant)(?:$|[-_/.:\d])/i;function w(t,e){let o=e.trim();if(!o)return;let r=o.indexOf("/");if(r>0){let l=o.slice(0,r),i=o.slice(r+1);return t.find(a=>a.provider===l&&a.id===i)}return t.find(l=>l.id===o)}n(w,"findSpec");function C(t,e,o=Number.POSITIVE_INFINITY){let r=t.filter(i=>A(i)&&!e.has(i.id)&&s(i)<=o),l=r.filter(i=>!P.test(i.id));return[...l.length>0?l:r].sort((i,a)=>Number(a.reasoning)-Number(i.reasoning)||s(a)-s(i)||i.id.localeCompare(a.id))[0]}n(C,"strongest");function T(t){return[...t.filter(A)].sort((e,o)=>s(e)-s(o)||Number(F(o.id))-Number(F(e.id))||e.id.localeCompare(o.id))[0]}n(T,"cheapest");var _=15;function $(t,e,o={}){let r=[],l=o.maxFallbackPrice??_,i=o.preferDomestic?t.filter(m=>F(m.id)):[...t],a=n((m,x)=>{let b=e[m],f=w(i,b);if(f&&A(f))return f;let R=x();if(R){let N=f?"unpriced":w(t,b)?"not-domestic":"missing";r.push({role:m,spec:b,why:N,replacement:R.id})}return R},"pick"),u=a("executor",()=>T(i));if(!u)return{ok:!1,reason:"no priced model in the catalogue"};let y=new Set([u.id]),c=a("planner",()=>C(i,y,l));if(!c||c.id===u.id||s(c)<=s(u))return{ok:!1,reason:`no priced model stronger than the executor ${u.id}`};let D=a("reviewer",()=>{let m=i.filter(x=>E(x.id)!==E(u.id));return C(m,y,l)??c}),M=a("escalate",()=>c);return!D||!M?{ok:!1,reason:"no reviewer or escalation model"}:{ok:!0,roles:{planner:c,executor:u,reviewer:D,escalate:M,notes:r}}}n($,"resolveRoles");import{existsSync as j,readFileSync as q}from"node:fs";import{join as B}from"node:path";var d={enabled:!0,mainAutoRoute:!0,auxRoute:{subagent:!0,compaction:!0},subagentModel:"route",suggestAuto:!0,roles:{enabled:!0,review:!0,plannerReads:4,planWaitMs:12e4,maxEscalations:1,preferDomestic:!1,maxFallbackPrice:_,models:v}};function W(){return B(L(),"factory.json")}n(W,"factoryConfigPath");function p(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}n(p,"isRecord");function g(t,e,o){return typeof t=="number"&&Number.isFinite(t)&&t>=e&&t<=o?t:void 0}n(g,"numberInRange");function J(t,e){let o={...t};if(typeof e.enabled=="boolean"&&(o.enabled=e.enabled),typeof e.mainAutoRoute=="boolean"&&(o.mainAutoRoute=e.mainAutoRoute),p(e.auxRoute)&&(o.auxRoute={subagent:typeof e.auxRoute.subagent=="boolean"?e.auxRoute.subagent:t.auxRoute.subagent,compaction:typeof e.auxRoute.compaction=="boolean"?e.auxRoute.compaction:t.auxRoute.compaction}),typeof e.subagentModel=="string"&&e.subagentModel.trim()&&(o.subagentModel=e.subagentModel.trim()),typeof e.suggestAuto=="boolean"&&(o.suggestAuto=e.suggestAuto),p(e.roles)){let r=e.roles,l=p(r.models)?r.models:{},i=n(u=>typeof l[u]=="string"&&l[u].trim()?l[u].trim():t.roles.models[u],"spec"),a=g(r.maxEscalations,0,3);o.roles={enabled:typeof r.enabled=="boolean"?r.enabled:t.roles.enabled,review:typeof r.review=="boolean"?r.review:t.roles.review,plannerReads:Math.floor(g(r.plannerReads,0,8)??t.roles.plannerReads),planWaitMs:Math.floor(g(r.planWaitMs,0,3e5)??t.roles.planWaitMs),maxEscalations:a===void 0?t.roles.maxEscalations:Math.floor(a),preferDomestic:typeof r.preferDomestic=="boolean"?r.preferDomestic:t.roles.preferDomestic,maxFallbackPrice:g(r.maxFallbackPrice,0,1e3)??t.roles.maxFallbackPrice,models:Object.fromEntries(h.map(u=>[u,i(u)]))}}return o}n(J,"mergeConfig");function U(){let t=W();if(!j(t))return{config:d,mainAutoRouteExplicit:!1};try{let e=JSON.parse(q(t,"utf8"));return p(e)?{config:J(d,e),mainAutoRouteExplicit:typeof e.mainAutoRoute=="boolean"}:{config:d,mainAutoRouteExplicit:!1,warning:k(`${t}: \u9876\u5C42\u4E0D\u662F JSON \u5BF9\u8C61\uFF0C\u5DF2\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E\u3002`)}}catch(e){let o=e instanceof Error?e.message:String(e);return{config:d,mainAutoRouteExplicit:!1,warning:`${t}: ${k("JSON \u89E3\u6790\u5931\u8D25\uFF0C\u5DF2\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E\u3002")}${o}`}}}n(U,"loadFactoryConfig");export{d as DEFAULT_CONFIG,v as DEFAULT_ROLE_MODELS,U as loadFactoryConfig,$ as resolveRoles};
1
+ var O=Object.defineProperty;var n=(t,e)=>O(t,"name",{value:e,configurable:!0});import{createRequire as S}from"node:module";const G=S(import.meta.url);import{getAgentDir as L}from"./chunk-R47JBGS3.js";import{t as k}from"./chunk-SNBVCTMQ.js";var h=["planner","executor","reviewer","escalate"],v={planner:"claude-opus-5-5",executor:"deepseek-flash",reviewer:"gpt-6.1-sol",escalate:"claude-opus-5-5"};function E(t){let e=t.toLowerCase();return/claude/.test(e)?"anthropic":/^gpt|^o\d|codex/.test(e)?"openai":/gemini/.test(e)?"google":/grok/.test(e)?"xai":/deepseek/.test(e)?"deepseek":/glm/.test(e)?"zhipu":/kimi/.test(e)?"moonshot":/qwen/.test(e)?"alibaba":/minimax/.test(e)?"minimax":e.split(/[-_/.]/)[0]??e}n(E,"vendorOf");var I=["deepseek","zhipu","moonshot","alibaba","minimax"];function F(t){return I.includes(E(t))}n(F,"isDomesticModel");function A(t){return t.cost.input>0&&t.cost.output>0}n(A,"isPriced");function s(t){return(t.cost.input+t.cost.output)/2}n(s,"blendedPrice");var P=/(?:^|[-_/.:])(?:flash|mini|lite|nano|haiku|small|air|tiny|instant)(?:$|[-_/.:\d])/i;function w(t,e){let o=e.trim();if(!o)return;let r=o.indexOf("/");if(r>0){let l=o.slice(0,r),i=o.slice(r+1);return t.find(a=>a.provider===l&&a.id===i)}return t.find(l=>l.id===o)}n(w,"findSpec");function C(t,e,o=Number.POSITIVE_INFINITY){let r=t.filter(i=>A(i)&&!e.has(i.id)&&s(i)<=o),l=r.filter(i=>!P.test(i.id));return[...l.length>0?l:r].sort((i,a)=>Number(a.reasoning)-Number(i.reasoning)||s(a)-s(i)||i.id.localeCompare(a.id))[0]}n(C,"strongest");function T(t){return[...t.filter(A)].sort((e,o)=>s(e)-s(o)||Number(F(o.id))-Number(F(e.id))||e.id.localeCompare(o.id))[0]}n(T,"cheapest");var _=15;function $(t,e,o={}){let r=[],l=o.maxFallbackPrice??_,i=o.preferDomestic?t.filter(m=>F(m.id)):[...t],a=n((m,x)=>{let b=e[m],f=w(i,b);if(f&&A(f))return f;let R=x();if(R){let N=f?"unpriced":w(t,b)?"not-domestic":"missing";r.push({role:m,spec:b,why:N,replacement:R.id})}return R},"pick"),u=a("executor",()=>T(i));if(!u)return{ok:!1,reason:"no priced model in the catalogue"};let y=new Set([u.id]),c=a("planner",()=>C(i,y,l));if(!c||c.id===u.id||s(c)<=s(u))return{ok:!1,reason:`no priced model stronger than the executor ${u.id}`};let D=a("reviewer",()=>{let m=i.filter(x=>E(x.id)!==E(u.id));return C(m,y,l)??c}),M=a("escalate",()=>c);return!D||!M?{ok:!1,reason:"no reviewer or escalation model"}:{ok:!0,roles:{planner:c,executor:u,reviewer:D,escalate:M,notes:r}}}n($,"resolveRoles");import{existsSync as j,readFileSync as q}from"node:fs";import{join as B}from"node:path";var d={enabled:!0,mainAutoRoute:!0,auxRoute:{subagent:!0,compaction:!0},subagentModel:"route",suggestAuto:!0,roles:{enabled:!0,review:!0,plannerReads:4,planWaitMs:12e4,maxEscalations:1,preferDomestic:!1,maxFallbackPrice:_,models:v}};function W(){return B(L(),"factory.json")}n(W,"factoryConfigPath");function p(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}n(p,"isRecord");function g(t,e,o){return typeof t=="number"&&Number.isFinite(t)&&t>=e&&t<=o?t:void 0}n(g,"numberInRange");function J(t,e){let o={...t};if(typeof e.enabled=="boolean"&&(o.enabled=e.enabled),typeof e.mainAutoRoute=="boolean"&&(o.mainAutoRoute=e.mainAutoRoute),p(e.auxRoute)&&(o.auxRoute={subagent:typeof e.auxRoute.subagent=="boolean"?e.auxRoute.subagent:t.auxRoute.subagent,compaction:typeof e.auxRoute.compaction=="boolean"?e.auxRoute.compaction:t.auxRoute.compaction}),typeof e.subagentModel=="string"&&e.subagentModel.trim()&&(o.subagentModel=e.subagentModel.trim()),typeof e.suggestAuto=="boolean"&&(o.suggestAuto=e.suggestAuto),p(e.roles)){let r=e.roles,l=p(r.models)?r.models:{},i=n(u=>typeof l[u]=="string"&&l[u].trim()?l[u].trim():t.roles.models[u],"spec"),a=g(r.maxEscalations,0,3);o.roles={enabled:typeof r.enabled=="boolean"?r.enabled:t.roles.enabled,review:typeof r.review=="boolean"?r.review:t.roles.review,plannerReads:Math.floor(g(r.plannerReads,0,8)??t.roles.plannerReads),planWaitMs:Math.floor(g(r.planWaitMs,0,3e5)??t.roles.planWaitMs),maxEscalations:a===void 0?t.roles.maxEscalations:Math.floor(a),preferDomestic:typeof r.preferDomestic=="boolean"?r.preferDomestic:t.roles.preferDomestic,maxFallbackPrice:g(r.maxFallbackPrice,0,1e3)??t.roles.maxFallbackPrice,models:Object.fromEntries(h.map(u=>[u,i(u)]))}}return o}n(J,"mergeConfig");function U(){let t=W();if(!j(t))return{config:d,mainAutoRouteExplicit:!1};try{let e=JSON.parse(q(t,"utf8"));return p(e)?{config:J(d,e),mainAutoRouteExplicit:typeof e.mainAutoRoute=="boolean"}:{config:d,mainAutoRouteExplicit:!1,warning:k(`${t}: \u9876\u5C42\u4E0D\u662F JSON \u5BF9\u8C61\uFF0C\u5DF2\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E\u3002`)}}catch(e){let o=e instanceof Error?e.message:String(e);return{config:d,mainAutoRouteExplicit:!1,warning:`${t}: ${k("JSON \u89E3\u6790\u5931\u8D25\uFF0C\u5DF2\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E\u3002")}${o}`}}}n(U,"loadFactoryConfig");export{d as DEFAULT_CONFIG,v as DEFAULT_ROLE_MODELS,U as loadFactoryConfig,$ as resolveRoles};
@@ -1 +1 @@
1
- var g=Object.defineProperty;var l=(t,e)=>g(t,"name",{value:e,configurable:!0});import{createRequire as x}from"node:module";const R=x(import.meta.url);import{theme as f}from"./chunk-EH7SFF47.js";var d=31,u=36,h=d,p=u,M=[255,255,255,127,255,240,255,127,255,237,255,127,255,219,255,127,255,183,255,127,255,119,254,127,63,248,254,127,223,255,254,127,223,63,252,127,159,195,251,127,111,252,244,127,247,15,247,127,247,255,247,127,247,255,227,127,247,7,232,127,239,248,103,112,15,255,187,111,241,0,208,91,253,63,236,83,193,255,239,87,159,253,238,95,159,252,174,95,31,120,172,95,63,0,80,108,127,0,220,119,255,192,63,120,255,1,248,127,255,3,156,120,255,7,140,124,255,15,206,120,255,255,207,127,255,255,207,120,255,255,223,120,255,255,223,125,255,255,63,126,255,255,255,127],k=Math.ceil(h/8),a=Math.ceil(p/2),m=["typewriter","scanline","rain","fade","crt","glitch","dissolve"];function o(t,e){if(e>=p)return!1;let i=e*k+Math.floor(t/8),r=t%8;return(M[i]>>r&1)===0}l(o,"isArminPixel");function S(t,e){let i=o(t,e*2),r=o(t,e*2+1);return i&&r?"\u2588":i?"\u2580":r?"\u2584":" "}l(S,"getChar");function y(){let t=[];for(let e=0;e<a;e++){let i=[];for(let r=0;r<h;r++)i.push(S(r,e));t.push(i)}return t}l(y,"buildFinalGrid");var w=class{static{l(this,"ArminComponent")}ui;interval=null;effect;finalGrid;currentGrid;effectState={};cachedLines=[];cachedWidth=0;gridVersion=0;cachedVersion=-1;constructor(t){this.ui=t,this.effect=m[Math.floor(Math.random()*m.length)],this.finalGrid=y(),this.currentGrid=this.createEmptyGrid(),this.initEffect(),this.startAnimation()}invalidate(){this.cachedWidth=0}render(t){if(t===this.cachedWidth&&this.cachedVersion===this.gridVersion)return this.cachedLines;let e=1,i=t-e;this.cachedLines=this.currentGrid.map(n=>{let c=n.slice(0,i).join(""),G=Math.max(0,t-e-c.length);return` ${f.fg("accent",c)}${" ".repeat(G)}`});let r="ARMIN SAYS HI",s=Math.max(0,t-e-r.length);return this.cachedLines.push(` ${f.fg("accent",r)}${" ".repeat(s)}`),this.cachedWidth=t,this.cachedVersion=this.gridVersion,this.cachedLines}createEmptyGrid(){return Array.from({length:a},()=>Array(h).fill(" "))}initEffect(){switch(this.effect){case"typewriter":this.effectState={pos:0};break;case"scanline":this.effectState={row:0};break;case"rain":this.effectState={drops:Array.from({length:h},()=>({y:-Math.floor(Math.random()*a*2),settled:0}))};break;case"fade":{let t=[];for(let e=0;e<a;e++)for(let i=0;i<h;i++)t.push([e,i]);for(let e=t.length-1;e>0;e--){let i=Math.floor(Math.random()*(e+1));[t[e],t[i]]=[t[i],t[e]]}this.effectState={positions:t,idx:0};break}case"crt":this.effectState={expansion:0};break;case"glitch":this.effectState={phase:0,glitchFrames:8};break;case"dissolve":{this.currentGrid=Array.from({length:a},()=>Array.from({length:h},()=>{let e=[" ","\u2591","\u2592","\u2593","\u2588","\u2580","\u2584"];return e[Math.floor(Math.random()*e.length)]}));let t=[];for(let e=0;e<a;e++)for(let i=0;i<h;i++)t.push([e,i]);for(let e=t.length-1;e>0;e--){let i=Math.floor(Math.random()*(e+1));[t[e],t[i]]=[t[i],t[e]]}this.effectState={positions:t,idx:0};break}}}startAnimation(){let t=this.effect==="glitch"?60:30;this.interval=setInterval(()=>{let e=this.tickEffect();this.updateDisplay(),this.ui.requestRender(),e&&this.stopAnimation()},1e3/t)}stopAnimation(){this.interval&&(clearInterval(this.interval),this.interval=null)}tickEffect(){switch(this.effect){case"typewriter":return this.tickTypewriter();case"scanline":return this.tickScanline();case"rain":return this.tickRain();case"fade":return this.tickFade();case"crt":return this.tickCrt();case"glitch":return this.tickGlitch();case"dissolve":return this.tickDissolve();default:return!0}}tickTypewriter(){let t=this.effectState,e=3;for(let i=0;i<e;i++){let r=Math.floor(t.pos/h),s=t.pos%h;if(r>=a)return!0;this.currentGrid[r][s]=this.finalGrid[r][s],t.pos++}return!1}tickScanline(){let t=this.effectState;if(t.row>=a)return!0;for(let e=0;e<h;e++)this.currentGrid[t.row][e]=this.finalGrid[t.row][e];return t.row++,!1}tickRain(){let t=this.effectState,e=!0;this.currentGrid=this.createEmptyGrid();for(let i=0;i<h;i++){let r=t.drops[i];for(let n=a-1;n>=a-r.settled;n--)n>=0&&(this.currentGrid[n][i]=this.finalGrid[n][i]);if(r.settled>=a)continue;e=!1;let s=-1;for(let n=a-1-r.settled;n>=0;n--)if(this.finalGrid[n][i]!==" "){s=n;break}r.y++,r.y>=0&&r.y<a&&(s>=0&&r.y>=s?(r.settled=a-s,r.y=-Math.floor(Math.random()*5)-1):this.currentGrid[r.y][i]="\u2593")}return e}tickFade(){let t=this.effectState,e=15;for(let i=0;i<e;i++){if(t.idx>=t.positions.length)return!0;let[r,s]=t.positions[t.idx];this.currentGrid[r][s]=this.finalGrid[r][s],t.idx++}return!1}tickCrt(){let t=this.effectState,e=Math.floor(a/2);this.currentGrid=this.createEmptyGrid();let i=e-t.expansion,r=e+t.expansion;for(let s=Math.max(0,i);s<=Math.min(a-1,r);s++)for(let n=0;n<h;n++)this.currentGrid[s][n]=this.finalGrid[s][n];return t.expansion++,t.expansion>a}tickGlitch(){let t=this.effectState;return t.phase<t.glitchFrames?(this.currentGrid=this.finalGrid.map(e=>{let i=Math.floor(Math.random()*7)-3,r=[...e];if(Math.random()<.3)return r.slice(i).concat(r.slice(0,i)).slice(0,h);if(Math.random()<.2){let s=Math.floor(Math.random()*a);return[...this.finalGrid[s]]}return r}),t.phase++,!1):(this.currentGrid=this.finalGrid.map(e=>[...e]),!0)}tickDissolve(){let t=this.effectState,e=20;for(let i=0;i<e;i++){if(t.idx>=t.positions.length)return!0;let[r,s]=t.positions[t.idx];this.currentGrid[r][s]=this.finalGrid[r][s],t.idx++}return!1}updateDisplay(){this.gridVersion++}dispose(){this.stopAnimation()}};export{u as ARMIN_HEIGHT,d as ARMIN_WIDTH,w as ArminComponent,o as isArminPixel};
1
+ var g=Object.defineProperty;var l=(t,e)=>g(t,"name",{value:e,configurable:!0});import{createRequire as x}from"node:module";const R=x(import.meta.url);import{theme as f}from"./chunk-AL3DFAIM.js";var d=31,u=36,h=d,p=u,M=[255,255,255,127,255,240,255,127,255,237,255,127,255,219,255,127,255,183,255,127,255,119,254,127,63,248,254,127,223,255,254,127,223,63,252,127,159,195,251,127,111,252,244,127,247,15,247,127,247,255,247,127,247,255,227,127,247,7,232,127,239,248,103,112,15,255,187,111,241,0,208,91,253,63,236,83,193,255,239,87,159,253,238,95,159,252,174,95,31,120,172,95,63,0,80,108,127,0,220,119,255,192,63,120,255,1,248,127,255,3,156,120,255,7,140,124,255,15,206,120,255,255,207,127,255,255,207,120,255,255,223,120,255,255,223,125,255,255,63,126,255,255,255,127],k=Math.ceil(h/8),a=Math.ceil(p/2),m=["typewriter","scanline","rain","fade","crt","glitch","dissolve"];function o(t,e){if(e>=p)return!1;let i=e*k+Math.floor(t/8),r=t%8;return(M[i]>>r&1)===0}l(o,"isArminPixel");function S(t,e){let i=o(t,e*2),r=o(t,e*2+1);return i&&r?"\u2588":i?"\u2580":r?"\u2584":" "}l(S,"getChar");function y(){let t=[];for(let e=0;e<a;e++){let i=[];for(let r=0;r<h;r++)i.push(S(r,e));t.push(i)}return t}l(y,"buildFinalGrid");var w=class{static{l(this,"ArminComponent")}ui;interval=null;effect;finalGrid;currentGrid;effectState={};cachedLines=[];cachedWidth=0;gridVersion=0;cachedVersion=-1;constructor(t){this.ui=t,this.effect=m[Math.floor(Math.random()*m.length)],this.finalGrid=y(),this.currentGrid=this.createEmptyGrid(),this.initEffect(),this.startAnimation()}invalidate(){this.cachedWidth=0}render(t){if(t===this.cachedWidth&&this.cachedVersion===this.gridVersion)return this.cachedLines;let e=1,i=t-e;this.cachedLines=this.currentGrid.map(n=>{let c=n.slice(0,i).join(""),G=Math.max(0,t-e-c.length);return` ${f.fg("accent",c)}${" ".repeat(G)}`});let r="ARMIN SAYS HI",s=Math.max(0,t-e-r.length);return this.cachedLines.push(` ${f.fg("accent",r)}${" ".repeat(s)}`),this.cachedWidth=t,this.cachedVersion=this.gridVersion,this.cachedLines}createEmptyGrid(){return Array.from({length:a},()=>Array(h).fill(" "))}initEffect(){switch(this.effect){case"typewriter":this.effectState={pos:0};break;case"scanline":this.effectState={row:0};break;case"rain":this.effectState={drops:Array.from({length:h},()=>({y:-Math.floor(Math.random()*a*2),settled:0}))};break;case"fade":{let t=[];for(let e=0;e<a;e++)for(let i=0;i<h;i++)t.push([e,i]);for(let e=t.length-1;e>0;e--){let i=Math.floor(Math.random()*(e+1));[t[e],t[i]]=[t[i],t[e]]}this.effectState={positions:t,idx:0};break}case"crt":this.effectState={expansion:0};break;case"glitch":this.effectState={phase:0,glitchFrames:8};break;case"dissolve":{this.currentGrid=Array.from({length:a},()=>Array.from({length:h},()=>{let e=[" ","\u2591","\u2592","\u2593","\u2588","\u2580","\u2584"];return e[Math.floor(Math.random()*e.length)]}));let t=[];for(let e=0;e<a;e++)for(let i=0;i<h;i++)t.push([e,i]);for(let e=t.length-1;e>0;e--){let i=Math.floor(Math.random()*(e+1));[t[e],t[i]]=[t[i],t[e]]}this.effectState={positions:t,idx:0};break}}}startAnimation(){let t=this.effect==="glitch"?60:30;this.interval=setInterval(()=>{let e=this.tickEffect();this.updateDisplay(),this.ui.requestRender(),e&&this.stopAnimation()},1e3/t)}stopAnimation(){this.interval&&(clearInterval(this.interval),this.interval=null)}tickEffect(){switch(this.effect){case"typewriter":return this.tickTypewriter();case"scanline":return this.tickScanline();case"rain":return this.tickRain();case"fade":return this.tickFade();case"crt":return this.tickCrt();case"glitch":return this.tickGlitch();case"dissolve":return this.tickDissolve();default:return!0}}tickTypewriter(){let t=this.effectState,e=3;for(let i=0;i<e;i++){let r=Math.floor(t.pos/h),s=t.pos%h;if(r>=a)return!0;this.currentGrid[r][s]=this.finalGrid[r][s],t.pos++}return!1}tickScanline(){let t=this.effectState;if(t.row>=a)return!0;for(let e=0;e<h;e++)this.currentGrid[t.row][e]=this.finalGrid[t.row][e];return t.row++,!1}tickRain(){let t=this.effectState,e=!0;this.currentGrid=this.createEmptyGrid();for(let i=0;i<h;i++){let r=t.drops[i];for(let n=a-1;n>=a-r.settled;n--)n>=0&&(this.currentGrid[n][i]=this.finalGrid[n][i]);if(r.settled>=a)continue;e=!1;let s=-1;for(let n=a-1-r.settled;n>=0;n--)if(this.finalGrid[n][i]!==" "){s=n;break}r.y++,r.y>=0&&r.y<a&&(s>=0&&r.y>=s?(r.settled=a-s,r.y=-Math.floor(Math.random()*5)-1):this.currentGrid[r.y][i]="\u2593")}return e}tickFade(){let t=this.effectState,e=15;for(let i=0;i<e;i++){if(t.idx>=t.positions.length)return!0;let[r,s]=t.positions[t.idx];this.currentGrid[r][s]=this.finalGrid[r][s],t.idx++}return!1}tickCrt(){let t=this.effectState,e=Math.floor(a/2);this.currentGrid=this.createEmptyGrid();let i=e-t.expansion,r=e+t.expansion;for(let s=Math.max(0,i);s<=Math.min(a-1,r);s++)for(let n=0;n<h;n++)this.currentGrid[s][n]=this.finalGrid[s][n];return t.expansion++,t.expansion>a}tickGlitch(){let t=this.effectState;return t.phase<t.glitchFrames?(this.currentGrid=this.finalGrid.map(e=>{let i=Math.floor(Math.random()*7)-3,r=[...e];if(Math.random()<.3)return r.slice(i).concat(r.slice(0,i)).slice(0,h);if(Math.random()<.2){let s=Math.floor(Math.random()*a);return[...this.finalGrid[s]]}return r}),t.phase++,!1):(this.currentGrid=this.finalGrid.map(e=>[...e]),!0)}tickDissolve(){let t=this.effectState,e=20;for(let i=0;i<e;i++){if(t.idx>=t.positions.length)return!0;let[r,s]=t.positions[t.idx];this.currentGrid[r][s]=this.finalGrid[r][s],t.idx++}return!1}updateDisplay(){this.gridVersion++}dispose(){this.stopAnimation()}};export{u as ARMIN_HEIGHT,d as ARMIN_WIDTH,w as ArminComponent,o as isArminPixel};
@@ -1 +1 @@
1
- var $=Object.defineProperty;var p=(e,r)=>$(e,"name",{value:r,configurable:!0});import{createRequire as h}from"node:module";const q=h(import.meta.url);import{isRecord as u,parseClassifierUsage as y,postClassifierRequest as b,requiredNumber as f}from"./chunk-IDZ3QKHZ.js";import{formatProviderError as E,normalizeProviderError as _}from"./chunk-33MCYYJ3.js";var l={"TypeSafe-Danger-Zone-Images":"true"};function I(e,r,a){if(!u(r))throw new Error(`${e} returned invalid probabilities for ${a}`);return Object.fromEntries(Object.entries(r).map(([o,t])=>[o,f(e,t,`probability for ${a}.${o}`)]))}p(I,"probabilities");function O(e,r,a){if(!u(r))throw new Error(`${e} returned an unexpected response`);let o=[];for(let[t,s]of Object.entries(a.questions)){let i=r[t];if(!u(i))throw new Error(`${e} did not return an answer for ${t}`);if(s.type==="choice"){if(i.type!=="choice"||typeof i.choice!="string")throw new Error(`${e} did not return a choice answer for ${t}`);o.push([t,{type:"choice",choice:i.choice,probabilities:I(e,i.probabilities,t),confidence:f(e,i.confidence,`confidence for ${t}`)}])}else if(s.type==="score"){if(i.type!=="score")throw new Error(`${e} did not return a score answer for ${t}`);o.push([t,{type:"score",score:f(e,i.score,`score for ${t}`),confidence:f(e,i.confidence,`confidence for ${t}`)}])}else{if(i.type!=="noul")throw new Error(`${e} did not return a bool answer for ${t}`);o.push([t,{type:"bool",probability:f(e,i.noul,`probability for ${t}`)}])}}return Object.fromEntries(o)}p(O,"parseAnswers");var T={"image/png":"png","image/jpeg":"jpeg"},A=new Set(["image/png","image/jpeg","image/webp"]),w=4;function R(e,r,a,o,t){if(a==="images"){if(o.length>w)throw new Error(`${e} accepts at most ${w} images for ${r.id}, got ${o.length}`);t.images=o.map(i=>{if(!A.has(i.mimeType))throw new Error(`${e} accepts PNG, JPEG, and WebP images for ${r.id}, got ${i.mimeType}`);return`data:${i.mimeType};base64,${i.data}`});return}if(a==="state-image-urls"){let i=o.map(n=>({type:"image_url",image_url:{url:`data:${n.mimeType};base64,${n.data}`}}));t.state=[...i,t.state];return}let s={};o.forEach((i,n)=>{let c=T[i.mimeType];if(!c)throw new Error(`${e} accepts PNG and JPEG images for ${r.id}, got ${i.mimeType}`);s[`<image-${n+1}>`]={type:"image",format:c,data_base64:i.data}}),t.assets=s,t.state=[...Object.keys(s),t.state]}p(R,"addImages");function j(e){return{state:e.state,questions:Object.fromEntries(Object.entries(e.questions).map(([r,a])=>[r,a.type==="bool"?{...a,type:"noul"}:a]))}}p(j,"wireRequest");async function P(e,r,a,o){let t={api:r.api,provider:r.provider,model:r.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(r.api!==e.api)throw new Error(`Unsupported classifier API: ${r.api}`);let s=j(a),i=o;if(a.images?.length){if(!r.input.includes("image"))throw new Error(`${e.label} does not support image input for ${r.id}`);let m=e.detectCompat(r),g=r.compat?.imageInput??m.imageInput;R(e.label,r,g,a.images,s),(r.compat?.sendImageOptInHeader??m.sendImageOptInHeader)&&(i={...o,headers:{...l,...o?.headers}})}let n=await b(e.label,e.url(r),r,e.payload(r,s),i),c=e.output(n),d=y(c.usage,r);return d&&(t.usage=d),t.answers=O(e.label,c.answers,a),t}catch(s){return t.stopReason=o?.signal?.aborted?"aborted":"error",t.errorMessage=E(_(s),`${e.label} error`),t}}p(P,"classifySystemOne");export{P as classifySystemOne};
1
+ var $=Object.defineProperty;var p=(e,r)=>$(e,"name",{value:r,configurable:!0});import{createRequire as h}from"node:module";const q=h(import.meta.url);import{isRecord as u,parseClassifierUsage as y,postClassifierRequest as b,requiredNumber as f}from"./chunk-DBT5OS5V.js";import{formatProviderError as E,normalizeProviderError as _}from"./chunk-SMPERFJU.js";var l={"TypeSafe-Danger-Zone-Images":"true"};function I(e,r,a){if(!u(r))throw new Error(`${e} returned invalid probabilities for ${a}`);return Object.fromEntries(Object.entries(r).map(([o,t])=>[o,f(e,t,`probability for ${a}.${o}`)]))}p(I,"probabilities");function O(e,r,a){if(!u(r))throw new Error(`${e} returned an unexpected response`);let o=[];for(let[t,s]of Object.entries(a.questions)){let i=r[t];if(!u(i))throw new Error(`${e} did not return an answer for ${t}`);if(s.type==="choice"){if(i.type!=="choice"||typeof i.choice!="string")throw new Error(`${e} did not return a choice answer for ${t}`);o.push([t,{type:"choice",choice:i.choice,probabilities:I(e,i.probabilities,t),confidence:f(e,i.confidence,`confidence for ${t}`)}])}else if(s.type==="score"){if(i.type!=="score")throw new Error(`${e} did not return a score answer for ${t}`);o.push([t,{type:"score",score:f(e,i.score,`score for ${t}`),confidence:f(e,i.confidence,`confidence for ${t}`)}])}else{if(i.type!=="noul")throw new Error(`${e} did not return a bool answer for ${t}`);o.push([t,{type:"bool",probability:f(e,i.noul,`probability for ${t}`)}])}}return Object.fromEntries(o)}p(O,"parseAnswers");var T={"image/png":"png","image/jpeg":"jpeg"},A=new Set(["image/png","image/jpeg","image/webp"]),w=4;function R(e,r,a,o,t){if(a==="images"){if(o.length>w)throw new Error(`${e} accepts at most ${w} images for ${r.id}, got ${o.length}`);t.images=o.map(i=>{if(!A.has(i.mimeType))throw new Error(`${e} accepts PNG, JPEG, and WebP images for ${r.id}, got ${i.mimeType}`);return`data:${i.mimeType};base64,${i.data}`});return}if(a==="state-image-urls"){let i=o.map(n=>({type:"image_url",image_url:{url:`data:${n.mimeType};base64,${n.data}`}}));t.state=[...i,t.state];return}let s={};o.forEach((i,n)=>{let c=T[i.mimeType];if(!c)throw new Error(`${e} accepts PNG and JPEG images for ${r.id}, got ${i.mimeType}`);s[`<image-${n+1}>`]={type:"image",format:c,data_base64:i.data}}),t.assets=s,t.state=[...Object.keys(s),t.state]}p(R,"addImages");function j(e){return{state:e.state,questions:Object.fromEntries(Object.entries(e.questions).map(([r,a])=>[r,a.type==="bool"?{...a,type:"noul"}:a]))}}p(j,"wireRequest");async function P(e,r,a,o){let t={api:r.api,provider:r.provider,model:r.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(r.api!==e.api)throw new Error(`Unsupported classifier API: ${r.api}`);let s=j(a),i=o;if(a.images?.length){if(!r.input.includes("image"))throw new Error(`${e.label} does not support image input for ${r.id}`);let m=e.detectCompat(r),g=r.compat?.imageInput??m.imageInput;R(e.label,r,g,a.images,s),(r.compat?.sendImageOptInHeader??m.sendImageOptInHeader)&&(i={...o,headers:{...l,...o?.headers}})}let n=await b(e.label,e.url(r),r,e.payload(r,s),i),c=e.output(n),d=y(c.usage,r);return d&&(t.usage=d),t.answers=O(e.label,c.answers,a),t}catch(s){return t.stopReason=o?.signal?.aborted?"aborted":"error",t.errorMessage=E(_(s),`${e.label} error`),t}}p(P,"classifySystemOne");export{P as classifySystemOne};
@@ -1 +1 @@
1
- var H=Object.defineProperty;var o=(e,r)=>H(e,"name",{value:r,configurable:!0});import{createRequire as U}from"node:module";const xe=U(import.meta.url);import{clampThinkingLevel as B}from"./chunk-K4B5ABCQ.js";import{getSystemMessageText as F}from"./chunk-SCYK4XNE.js";var d=class extends Error{static{o(this,"UnsupportedStrictJsonSchemaError")}},z=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function w(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(w,"isJsonSchemaObject");function K(e){if(!w(e))return!1;let r=typeof e.type=="string"?[e.type]:Array.isArray(e.type)?e.type:[];return r.includes("object")||r.includes("array")||e.properties!==void 0||e.items!==void 0}o(K,"isStructuredSchema");function O(e){return w(e)?e.type==="null"||Array.isArray(e.type)&&e.type.includes("null")||e.const===null||Array.isArray(e.enum)&&e.enum.includes(null)?!0:Array.isArray(e.anyOf)&&e.anyOf.some(r=>O(r)):!1}o(O,"schemaAllowsNull");function v(e,r){if(!w(e))throw new d("boolean schemas are unsupported");for(let s of z)if(e[s]!==void 0)throw new d(`${s} schemas are unsupported`);if(r){for(let[s,m]of Object.entries(e))if(r(s,m))throw new d(`${s}: ${JSON.stringify(m)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new d("anyOf must contain at least one schema");for(let s of e.anyOf){if(K(s))throw new d("object and array unions are unsupported");v(s,r)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new d("tuple schemas are unsupported");v(e.items,r)}let t=e.type==="object";if(e.properties!==void 0&&!t)throw new d("properties require type object");if(!t)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new d("schema-valued or true additionalProperties is unsupported");if(e.properties!==void 0&&!w(e.properties))throw new d("object properties must be a schema map");if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some(s=>typeof s!="string")))throw new d("object required must be a string array");let n=e.properties??{},i=Object.keys(n),a=new Set(Array.isArray(e.required)?e.required:[]);if([...a].some(s=>!i.includes(s)))throw new d("required contains an unknown property");for(let[s,m]of Object.entries(n))v(m,r),!a.has(s)&&!O(m)&&(n[s]={anyOf:[m,{type:"null"}]});e.required=i,e.additionalProperties=!1}o(v,"makeJsonSchemaNodeStrict");function R(e,r){let t=structuredClone(e);if(!w(t))throw new d("root schema must have type object");if(v(t,r),t.type!=="object")throw new d("root schema must have type object");return t}o(R,"makeStrictJsonSchema");function Y(e){let r=e.constrainedSampling;return!!r&&r.type==="json_schema"&&r.strict==="prefer"}o(Y,"prefersJsonSchemaStrictSampling");function V(e,r){return r===!0?R(e.parameters):e.parameters}o(V,"getJsonSchemaToolParameters");function X(e,r,t){let n=r[t];if(typeof n!="string")throw new Error(`Grammar tool call "${e}" requires argument "${t}" to be a string.`);return n}o(X,"getGrammarToolInput");function Q(e,r,t){if(e.closed)throw new Error(`grammar tool input for property "${r}" changed after it was closed`);if(t.length!==0)return e.input+=t,_(e,r)+JSON.stringify(t).slice(1,-1)}o(Q,"appendGrammarToolInputJsonDelta");function Z(e,r,t){if(e.closed){if(t===void 0||t===e.input)return;throw new Error(`grammar tool input for property "${r}" changed after it was closed`)}if(t!==void 0&&!t.startsWith(e.input))throw new Error(`grammar tool input for property "${r}" changed non-monotonically`);let n=t===void 0?"":t.slice(e.input.length);return t!==void 0&&(e.input=t),e.closed=!0,`${_(e,r)}${JSON.stringify(n).slice(1,-1)}"}`}o(Z,"closeGrammarToolInputJson");function _(e,r){return e.started?"":(e.started=!0,`{${JSON.stringify(r)}:"`)}o(_,"grammarToolInputJsonStart");function ee(e){let r=e.parameters;if(r.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(r.required)||r.required.length!==1||typeof r.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let t=r.required[0];if(!r.properties?.[t])throw new Error(`grammar constrained sampling requires a properties entry for ${t}`);if(r.properties[t]?.type!=="string")throw new Error(`grammar constrained sampling property ${t} must have type string`);return t}o(ee,"inferGrammarInputProperty");function te(e,r,t){let n=e.constrainedSampling;if(!(!n||n.type!=="json_schema")){if(r)try{return R(e.parameters,t),!0}catch(i){if(!(i instanceof d))throw i;if(n.strict!=="require")return;throw new Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${i.message}.`)}if(n.strict==="require")throw new Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}o(te,"resolveJsonSchemaStrictSampling");function N(e,r){let t=e.constrainedSampling;if(!t||t.type!=="grammar"||!r)return;let n=t.variants.openai_lark,i=t.variants.openai_regex,a=typeof n=="string"&&n.trim().length>0,s=typeof i=="string"&&i.trim().length>0;if(!a&&!s)throw new Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:a?"lark":"regex",definition:a?n:i,inputProperty:ee(e)}}catch(m){let f=m instanceof Error?m.message:String(m);throw new Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${f}.`)}}o(N,"resolveGrammarConstrainedSampling");function re(e,r){let t=new Map;for(let n of e??[]){let i=N(n,r);i&&t.set(n.name,i.inputProperty)}return t}o(re,"createGrammarToolInputProperties");var M=3.5,ne=4800;function C(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}o(C,"calculateContextTokens");function k(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}o(k,"safeJsonStringify");function ie(e){if(typeof e=="string")return e.length;let r=0;for(let t of e)r+=t.type==="text"?t.text.length:ne;return r}o(ie,"estimateTextAndImageContentChars");function P(e){return Math.ceil(e.length/M)}o(P,"estimateTextTokens");function oe(e){return Math.ceil(ie(e)/M)}o(oe,"estimateTextAndImageContentTokens");function q(e){let r=0;if(e.role==="system")return P(F(e))+$(e.toolsAdded)+$(e.toolsRemoved);if(e.role==="user"||e.role==="toolResult")return oe(e.content);for(let t of e.content)t.type==="text"?r+=t.text.length:t.type==="thinking"?r+=t.thinking.length:r+=t.name.length+k(t.arguments).length;return Math.ceil(r/M)}o(q,"estimateMessageTokens");function ae(e){let r=Number.NEGATIVE_INFINITY,t;for(let n=0;n<e.length;n++){let i=e[n];if(i.role==="assistant"){let a=i;a.timestamp>=r&&a.stopReason!=="aborted"&&a.stopReason!=="error"&&C(a.usage)>0&&(t={usage:a.usage,index:n})}r=Math.max(r,i.timestamp)}return t}o(ae,"getLastAssistantUsageInfo");function se(e){let r="messages"in e?e.messages:e,t=ae(r);if(t){let i=C(t.usage),a=0;for(let s=t.index+1;s<r.length;s++)a+=q(r[s]);return{tokens:i+a,usageTokens:i,trailingTokens:a,lastUsageIndex:t.index}}let n=0;for(let i of r)n+=q(i);return{tokens:n,usageTokens:0,trailingTokens:n,lastUsageIndex:null}}o(se,"estimateContextTokens");function $(e){return!e||e.length===0?0:P(k(e))}o($,"estimateToolsTokens");var j=4096,le=.15,J=32768,L=1;function b(e,r,t){if(e.contextWindow<=0)return Math.max(L,t);let n=se(r).tokens,i=Math.max(j,Math.ceil(n*le)),a=e.contextWindow-n-i;return a<J&&(a=Math.min(J,e.contextWindow-n-j)),Math.min(t,Math.max(L,a))}o(b,"clampMaxTokensToContext");function G(e,r,t){let n=B(e,r),i=e.samplingParamsByThinkingLevel?.[n];return e.samplingParams||i||t?{...e.samplingParams,...i,...t}:void 0}o(G,"resolveSamplingParams");function ue(e,r,t,n){let i=G(e,t?.reasoning??"off",t?.samplingParams);return{temperature:t?.temperature,samplingParams:i,maxTokens:b(e,r,t?.maxTokens??e.maxTokens),signal:t?.signal,telemetry:t?.telemetry,apiKey:n||t?.apiKey,fetch:t?.fetch,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,disableContinuation:t?.disableContinuation,headers:t?.headers,identity:t?.identity,onPayload:t?.onPayload,onResponse:t?.onResponse,onProviderStreamEvent:t?.onProviderStreamEvent,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata,env:t?.env}}o(ue,"buildBaseOptions");var pe=1024,de={minimal:1024,low:2048,medium:8192,high:16384};function me(e){return e==="xhigh"||e==="max"?"high":e}o(me,"clampReasoning");function D(e,r){let t={...de,...r},n=me(e);return t[n]}o(D,"thinkingBudgetForLevel");function W(e,r){return Math.min(e,Math.max(0,r-pe))}o(W,"clampThinkingBudgetToAnswerRoom");function fe(e,r,t,n){let i=D(t,n),a=e===void 0?r:Math.min(e+i,r);return a<=i&&(i=W(i,a)),{maxTokens:a,thinkingBudget:i}}o(fe,"adjustMaxTokensForThinking");var ce="(image omitted: model does not support images)",ge="(tool image omitted: model does not support images)",he="(image attached after the tool results)";function ye(e){if(!e.isError)return;let r=e.content.filter(t=>t.type==="image");if(r.length!==0)return{content:I(e.content,he),caption:`Images from the error result of tool call ${e.toolCallId} (${e.toolName}):`,images:r}}o(ye,"splitErrorToolResultImages");function I(e,r){let t=[],n=!1;for(let i of e){if(i.type==="image"){n||t.push({type:"text",text:r}),n=!0;continue}t.push(i),n=i.text===r}return t}o(I,"replaceImagesWithPlaceholder");function we(e,r){return r.input.includes("image")?e:e.map(t=>t.role==="user"&&Array.isArray(t.content)?{...t,content:I(t.content,ce)}:t.role==="toolResult"?{...t,content:I(t.content,ge)}:t)}o(we,"downgradeUnsupportedImages");function Te(e,r){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="assistant"&&!(n.provider!==r.provider||n.api!==r.api||n.model!==r.id)&&!(n.stopReason==="error"||n.stopReason==="aborted"))return n.responseModel}}o(Te,"latestAnsweringModel");function Se(e,r,t){let n=new Map,i=e.map(u=>u.content==null?{...u,content:[]}:u),a=we(i,r),s=Te(a,r),m=a.map(u=>{if(u.role==="system"||u.role==="user")return u;if(u.role==="toolResult"){let l=n.get(u.toolCallId);return l&&l!==u.toolCallId?{...u,toolCallId:l}:u}if(u.role==="assistant"){let l=u,c=l.provider===r.provider&&l.api===r.api&&l.model===r.id&&(s===void 0||l.responseModel===void 0||l.responseModel===s),S=l.content.flatMap(p=>{if(p.type==="thinking")return c?p.redacted||p.thinkingSignature?p:!p.thinking||p.thinking.trim()===""?[]:p:[];if(p.type==="text")return c?p:{type:"text",text:p.text};if(p.type==="toolCall"){let g=p,y=g;if(!c&&g.thoughtSignature&&(y={...g},delete y.thoughtSignature),!c&&t){let A=t(g.id,r,l);A!==g.id&&(n.set(g.id,A),y={...y,id:A})}return y}return p});return{...l,content:S}}return u}),f=[],h=[],T=new Set,E=[],x=o(()=>{if(h.length>0){for(let u of h)T.has(u.id)||f.push({role:"toolResult",toolCallId:u.id,toolName:u.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});h=[],T=new Set}f.push(...E),E.length=0},"closePendingToolCalls");for(let u=0;u<m.length;u++){let l=m[u];if(l.role==="assistant"){x();let c=l;if(c.stopReason==="error"||c.stopReason==="aborted")continue;let S=c.content.filter(p=>p.type==="toolCall");S.length>0&&(h=S,T=new Set),f.push(l)}else l.role==="toolResult"?(T.add(l.toolCallId),f.push(l)):l.role==="system"?h.length>0?E.push(l):f.push(l):(l.role==="user"&&x(),f.push(l))}return x(),f}o(Se,"transformMessages");export{fe as adjustMaxTokensForThinking,Q as appendGrammarToolInputJsonDelta,ue as buildBaseOptions,b as clampMaxTokensToContext,W as clampThinkingBudgetToAnswerRoom,Z as closeGrammarToolInputJson,re as createGrammarToolInputProperties,X as getGrammarToolInput,V as getJsonSchemaToolParameters,Y as prefersJsonSchemaStrictSampling,N as resolveGrammarConstrainedSampling,te as resolveJsonSchemaStrictSampling,G as resolveSamplingParams,ye as splitErrorToolResultImages,D as thinkingBudgetForLevel,Se as transformMessages};
1
+ var H=Object.defineProperty;var o=(e,r)=>H(e,"name",{value:r,configurable:!0});import{createRequire as U}from"node:module";const xe=U(import.meta.url);import{clampThinkingLevel as B}from"./chunk-2XX4WZT6.js";import{getSystemMessageText as F}from"./chunk-44EXLOHK.js";var d=class extends Error{static{o(this,"UnsupportedStrictJsonSchemaError")}},z=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function w(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(w,"isJsonSchemaObject");function K(e){if(!w(e))return!1;let r=typeof e.type=="string"?[e.type]:Array.isArray(e.type)?e.type:[];return r.includes("object")||r.includes("array")||e.properties!==void 0||e.items!==void 0}o(K,"isStructuredSchema");function O(e){return w(e)?e.type==="null"||Array.isArray(e.type)&&e.type.includes("null")||e.const===null||Array.isArray(e.enum)&&e.enum.includes(null)?!0:Array.isArray(e.anyOf)&&e.anyOf.some(r=>O(r)):!1}o(O,"schemaAllowsNull");function v(e,r){if(!w(e))throw new d("boolean schemas are unsupported");for(let s of z)if(e[s]!==void 0)throw new d(`${s} schemas are unsupported`);if(r){for(let[s,m]of Object.entries(e))if(r(s,m))throw new d(`${s}: ${JSON.stringify(m)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new d("anyOf must contain at least one schema");for(let s of e.anyOf){if(K(s))throw new d("object and array unions are unsupported");v(s,r)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new d("tuple schemas are unsupported");v(e.items,r)}let t=e.type==="object";if(e.properties!==void 0&&!t)throw new d("properties require type object");if(!t)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new d("schema-valued or true additionalProperties is unsupported");if(e.properties!==void 0&&!w(e.properties))throw new d("object properties must be a schema map");if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some(s=>typeof s!="string")))throw new d("object required must be a string array");let n=e.properties??{},i=Object.keys(n),a=new Set(Array.isArray(e.required)?e.required:[]);if([...a].some(s=>!i.includes(s)))throw new d("required contains an unknown property");for(let[s,m]of Object.entries(n))v(m,r),!a.has(s)&&!O(m)&&(n[s]={anyOf:[m,{type:"null"}]});e.required=i,e.additionalProperties=!1}o(v,"makeJsonSchemaNodeStrict");function R(e,r){let t=structuredClone(e);if(!w(t))throw new d("root schema must have type object");if(v(t,r),t.type!=="object")throw new d("root schema must have type object");return t}o(R,"makeStrictJsonSchema");function Y(e){let r=e.constrainedSampling;return!!r&&r.type==="json_schema"&&r.strict==="prefer"}o(Y,"prefersJsonSchemaStrictSampling");function V(e,r){return r===!0?R(e.parameters):e.parameters}o(V,"getJsonSchemaToolParameters");function X(e,r,t){let n=r[t];if(typeof n!="string")throw new Error(`Grammar tool call "${e}" requires argument "${t}" to be a string.`);return n}o(X,"getGrammarToolInput");function Q(e,r,t){if(e.closed)throw new Error(`grammar tool input for property "${r}" changed after it was closed`);if(t.length!==0)return e.input+=t,_(e,r)+JSON.stringify(t).slice(1,-1)}o(Q,"appendGrammarToolInputJsonDelta");function Z(e,r,t){if(e.closed){if(t===void 0||t===e.input)return;throw new Error(`grammar tool input for property "${r}" changed after it was closed`)}if(t!==void 0&&!t.startsWith(e.input))throw new Error(`grammar tool input for property "${r}" changed non-monotonically`);let n=t===void 0?"":t.slice(e.input.length);return t!==void 0&&(e.input=t),e.closed=!0,`${_(e,r)}${JSON.stringify(n).slice(1,-1)}"}`}o(Z,"closeGrammarToolInputJson");function _(e,r){return e.started?"":(e.started=!0,`{${JSON.stringify(r)}:"`)}o(_,"grammarToolInputJsonStart");function ee(e){let r=e.parameters;if(r.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(r.required)||r.required.length!==1||typeof r.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let t=r.required[0];if(!r.properties?.[t])throw new Error(`grammar constrained sampling requires a properties entry for ${t}`);if(r.properties[t]?.type!=="string")throw new Error(`grammar constrained sampling property ${t} must have type string`);return t}o(ee,"inferGrammarInputProperty");function te(e,r,t){let n=e.constrainedSampling;if(!(!n||n.type!=="json_schema")){if(r)try{return R(e.parameters,t),!0}catch(i){if(!(i instanceof d))throw i;if(n.strict!=="require")return;throw new Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${i.message}.`)}if(n.strict==="require")throw new Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}o(te,"resolveJsonSchemaStrictSampling");function N(e,r){let t=e.constrainedSampling;if(!t||t.type!=="grammar"||!r)return;let n=t.variants.openai_lark,i=t.variants.openai_regex,a=typeof n=="string"&&n.trim().length>0,s=typeof i=="string"&&i.trim().length>0;if(!a&&!s)throw new Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:a?"lark":"regex",definition:a?n:i,inputProperty:ee(e)}}catch(m){let f=m instanceof Error?m.message:String(m);throw new Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${f}.`)}}o(N,"resolveGrammarConstrainedSampling");function re(e,r){let t=new Map;for(let n of e??[]){let i=N(n,r);i&&t.set(n.name,i.inputProperty)}return t}o(re,"createGrammarToolInputProperties");var M=3.5,ne=4800;function C(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}o(C,"calculateContextTokens");function k(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}o(k,"safeJsonStringify");function ie(e){if(typeof e=="string")return e.length;let r=0;for(let t of e)r+=t.type==="text"?t.text.length:ne;return r}o(ie,"estimateTextAndImageContentChars");function P(e){return Math.ceil(e.length/M)}o(P,"estimateTextTokens");function oe(e){return Math.ceil(ie(e)/M)}o(oe,"estimateTextAndImageContentTokens");function q(e){let r=0;if(e.role==="system")return P(F(e))+$(e.toolsAdded)+$(e.toolsRemoved);if(e.role==="user"||e.role==="toolResult")return oe(e.content);for(let t of e.content)t.type==="text"?r+=t.text.length:t.type==="thinking"?r+=t.thinking.length:r+=t.name.length+k(t.arguments).length;return Math.ceil(r/M)}o(q,"estimateMessageTokens");function ae(e){let r=Number.NEGATIVE_INFINITY,t;for(let n=0;n<e.length;n++){let i=e[n];if(i.role==="assistant"){let a=i;a.timestamp>=r&&a.stopReason!=="aborted"&&a.stopReason!=="error"&&C(a.usage)>0&&(t={usage:a.usage,index:n})}r=Math.max(r,i.timestamp)}return t}o(ae,"getLastAssistantUsageInfo");function se(e){let r="messages"in e?e.messages:e,t=ae(r);if(t){let i=C(t.usage),a=0;for(let s=t.index+1;s<r.length;s++)a+=q(r[s]);return{tokens:i+a,usageTokens:i,trailingTokens:a,lastUsageIndex:t.index}}let n=0;for(let i of r)n+=q(i);return{tokens:n,usageTokens:0,trailingTokens:n,lastUsageIndex:null}}o(se,"estimateContextTokens");function $(e){return!e||e.length===0?0:P(k(e))}o($,"estimateToolsTokens");var j=4096,le=.15,J=32768,L=1;function b(e,r,t){if(e.contextWindow<=0)return Math.max(L,t);let n=se(r).tokens,i=Math.max(j,Math.ceil(n*le)),a=e.contextWindow-n-i;return a<J&&(a=Math.min(J,e.contextWindow-n-j)),Math.min(t,Math.max(L,a))}o(b,"clampMaxTokensToContext");function G(e,r,t){let n=B(e,r),i=e.samplingParamsByThinkingLevel?.[n];return e.samplingParams||i||t?{...e.samplingParams,...i,...t}:void 0}o(G,"resolveSamplingParams");function ue(e,r,t,n){let i=G(e,t?.reasoning??"off",t?.samplingParams);return{temperature:t?.temperature,samplingParams:i,maxTokens:b(e,r,t?.maxTokens??e.maxTokens),signal:t?.signal,telemetry:t?.telemetry,apiKey:n||t?.apiKey,fetch:t?.fetch,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,disableContinuation:t?.disableContinuation,headers:t?.headers,identity:t?.identity,onPayload:t?.onPayload,onResponse:t?.onResponse,onProviderStreamEvent:t?.onProviderStreamEvent,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata,env:t?.env}}o(ue,"buildBaseOptions");var pe=1024,de={minimal:1024,low:2048,medium:8192,high:16384};function me(e){return e==="xhigh"||e==="max"?"high":e}o(me,"clampReasoning");function D(e,r){let t={...de,...r},n=me(e);return t[n]}o(D,"thinkingBudgetForLevel");function W(e,r){return Math.min(e,Math.max(0,r-pe))}o(W,"clampThinkingBudgetToAnswerRoom");function fe(e,r,t,n){let i=D(t,n),a=e===void 0?r:Math.min(e+i,r);return a<=i&&(i=W(i,a)),{maxTokens:a,thinkingBudget:i}}o(fe,"adjustMaxTokensForThinking");var ce="(image omitted: model does not support images)",ge="(tool image omitted: model does not support images)",he="(image attached after the tool results)";function ye(e){if(!e.isError)return;let r=e.content.filter(t=>t.type==="image");if(r.length!==0)return{content:I(e.content,he),caption:`Images from the error result of tool call ${e.toolCallId} (${e.toolName}):`,images:r}}o(ye,"splitErrorToolResultImages");function I(e,r){let t=[],n=!1;for(let i of e){if(i.type==="image"){n||t.push({type:"text",text:r}),n=!0;continue}t.push(i),n=i.text===r}return t}o(I,"replaceImagesWithPlaceholder");function we(e,r){return r.input.includes("image")?e:e.map(t=>t.role==="user"&&Array.isArray(t.content)?{...t,content:I(t.content,ce)}:t.role==="toolResult"?{...t,content:I(t.content,ge)}:t)}o(we,"downgradeUnsupportedImages");function Te(e,r){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="assistant"&&!(n.provider!==r.provider||n.api!==r.api||n.model!==r.id)&&!(n.stopReason==="error"||n.stopReason==="aborted"))return n.responseModel}}o(Te,"latestAnsweringModel");function Se(e,r,t){let n=new Map,i=e.map(u=>u.content==null?{...u,content:[]}:u),a=we(i,r),s=Te(a,r),m=a.map(u=>{if(u.role==="system"||u.role==="user")return u;if(u.role==="toolResult"){let l=n.get(u.toolCallId);return l&&l!==u.toolCallId?{...u,toolCallId:l}:u}if(u.role==="assistant"){let l=u,c=l.provider===r.provider&&l.api===r.api&&l.model===r.id&&(s===void 0||l.responseModel===void 0||l.responseModel===s),S=l.content.flatMap(p=>{if(p.type==="thinking")return c?p.redacted||p.thinkingSignature?p:!p.thinking||p.thinking.trim()===""?[]:p:[];if(p.type==="text")return c?p:{type:"text",text:p.text};if(p.type==="toolCall"){let g=p,y=g;if(!c&&g.thoughtSignature&&(y={...g},delete y.thoughtSignature),!c&&t){let A=t(g.id,r,l);A!==g.id&&(n.set(g.id,A),y={...y,id:A})}return y}return p});return{...l,content:S}}return u}),f=[],h=[],T=new Set,E=[],x=o(()=>{if(h.length>0){for(let u of h)T.has(u.id)||f.push({role:"toolResult",toolCallId:u.id,toolName:u.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});h=[],T=new Set}f.push(...E),E.length=0},"closePendingToolCalls");for(let u=0;u<m.length;u++){let l=m[u];if(l.role==="assistant"){x();let c=l;if(c.stopReason==="error"||c.stopReason==="aborted")continue;let S=c.content.filter(p=>p.type==="toolCall");S.length>0&&(h=S,T=new Set),f.push(l)}else l.role==="toolResult"?(T.add(l.toolCallId),f.push(l)):l.role==="system"?h.length>0?E.push(l):f.push(l):(l.role==="user"&&x(),f.push(l))}return x(),f}o(Se,"transformMessages");export{fe as adjustMaxTokensForThinking,Q as appendGrammarToolInputJsonDelta,ue as buildBaseOptions,b as clampMaxTokensToContext,W as clampThinkingBudgetToAnswerRoom,Z as closeGrammarToolInputJson,re as createGrammarToolInputProperties,X as getGrammarToolInput,V as getJsonSchemaToolParameters,Y as prefersJsonSchemaStrictSampling,N as resolveGrammarConstrainedSampling,te as resolveJsonSchemaStrictSampling,G as resolveSamplingParams,ye as splitErrorToolResultImages,D as thinkingBudgetForLevel,Se as transformMessages};