dal-code 1.0.58 → 1.0.60

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 (136) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/bundle/chunks/{anthropic-messages-FOIJU7LX.js → anthropic-messages-XQHIW2F5.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-7NBJZKX5.js → azure-openai-responses-2STR7FU2.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-4PBY6OYS.js → chunk-2SQ577MS.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-T5PI6B5P.js → chunk-2TJCPBNY.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-QU2VEHMW.js → chunk-3KEFLXX2.js} +2 -2
  8. package/dist/bundle/chunks/{chunk-4BOWD7PQ.js → chunk-425HIJ4E.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-5MF5GEDD.js → chunk-4KCKRVPN.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-CCU76UL3.js → chunk-4TEICWYC.js} +7 -7
  11. package/dist/bundle/chunks/{chunk-HF334NQU.js → chunk-B66W54NL.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-JK74OC6W.js → chunk-CIJDL6I3.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-QFBU27TM.js → chunk-E6RWRE6C.js} +1 -1
  14. package/dist/bundle/chunks/chunk-EXWCUM6H.js +9 -0
  15. package/dist/bundle/chunks/{chunk-C5ELI234.js → chunk-H3KG4L7I.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-B7KZDIWA.js → chunk-HZWPNFQO.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-DVEPGKL5.js → chunk-KMTIPRJ5.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-F5SIUTR7.js → chunk-LGD3AMTG.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-AL3DFAIM.js → chunk-NRQYSXAU.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-IONGABQF.js → chunk-O5BJV54H.js} +1 -1
  21. package/dist/bundle/chunks/chunk-P3KSBU23.js +17 -0
  22. package/dist/bundle/chunks/{chunk-R47JBGS3.js → chunk-QM5JU2GS.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-LMZYTWXD.js → chunk-RNSD5PAD.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-3QG7FIE4.js → chunk-RRLI6IMC.js} +1 -1
  25. package/dist/bundle/chunks/{chunk-PMFHJN7I.js → chunk-SI4QX273.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-X7I3V6OA.js → chunk-THJSXCE4.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-NYSVXLKF.js → chunk-X2O23QIN.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-XQF5XDEM.js → chunk-XQ6Z77K4.js} +2 -2
  29. package/dist/bundle/chunks/{cli-NQ7B7BGV.js → cli-H3PJUN3W.js} +1 -1
  30. package/dist/bundle/chunks/{cli-RY666QAD.js → cli-OEEFOWRC.js} +1 -1
  31. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-CFGOMWWZ.js → cloudflare-workers-ai-system-one-55VRUHTE.js} +1 -1
  32. package/dist/bundle/chunks/{easter-egg-3d-W2F3ROZ6.js → easter-egg-3d-JQUBBOXE.js} +1 -1
  33. package/dist/bundle/chunks/{execute-NJRE4WBO.js → execute-DAF3F222.js} +1 -1
  34. package/dist/bundle/chunks/{google-generative-ai-ZA2RHPNE.js → google-generative-ai-BQMG6OLH.js} +1 -1
  35. package/dist/bundle/chunks/{google-vertex-Y2GRWOK7.js → google-vertex-WUZF5EYV.js} +1 -1
  36. package/dist/bundle/chunks/{llama-cpp-classify-G2JDOFHY.js → llama-cpp-classify-MADWJYHP.js} +1 -1
  37. package/dist/bundle/chunks/{mcp-45D7KCZZ.js → mcp-GYBI424O.js} +1 -1
  38. package/dist/bundle/chunks/{mistral-conversations-MLV32BRV.js → mistral-conversations-GSSWAQLZ.js} +1 -1
  39. package/dist/bundle/chunks/{office-UBOUFRAU.js → office-OKOPPNJS.js} +1 -1
  40. package/dist/bundle/chunks/{openai-codex-responses-BDK3PY6G.js → openai-codex-responses-LJCENL64.js} +1 -1
  41. package/dist/bundle/chunks/{openai-completions-BLXHKAB3.js → openai-completions-MT4XYSLH.js} +1 -1
  42. package/dist/bundle/chunks/{openai-decisions-IGVID576.js → openai-decisions-Y3TPPQUQ.js} +1 -1
  43. package/dist/bundle/chunks/{openai-responses-KHZOEDF2.js → openai-responses-5EXHN2JI.js} +1 -1
  44. package/dist/bundle/chunks/{openrouter-images-SA6PUASF.js → openrouter-images-4YZGO774.js} +1 -1
  45. package/dist/bundle/chunks/{pi-messages-3VAOLQ2Y.js → pi-messages-EGKKYUGE.js} +1 -1
  46. package/dist/bundle/chunks/{review-RZXLHPUZ.js → review-GXC4JNBH.js} +1 -1
  47. package/dist/bundle/chunks/{router-YBVXODIL.js → router-6IBMTBKX.js} +1 -1
  48. package/dist/bundle/chunks/{runtime-FNCZJKOC.js → runtime-MD23I2NI.js} +1 -1
  49. package/dist/bundle/chunks/{sdk-X6RX7FNE.js → sdk-Z2BPQBYQ.js} +1 -1
  50. package/dist/bundle/chunks/sync-Q7ZHP4AB.js +21 -0
  51. package/dist/bundle/chunks/{typesafe-system-one-ER3DLYNF.js → typesafe-system-one-ZIS4YIPV.js} +1 -1
  52. package/dist/bundle/chunks/{usage-LMRFS2HV.js → usage-WQOCA772.js} +1 -1
  53. package/dist/bundle/chunks/{virtual-modules-XIUNRFOZ.js → virtual-modules-SEIIF76E.js} +1 -1
  54. package/dist/bundle/cli-runtime.js +1 -1
  55. package/dist/bundle/index.js +1 -1
  56. package/dist/bundle/rpc-entry.js +1 -1
  57. package/dist/config.d.ts +1 -0
  58. package/dist/config.js +1 -1
  59. package/dist/index.d.ts +1 -1
  60. package/dist/index.js +1 -1
  61. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  62. package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
  63. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  64. package/dist/node_modules/@dalcode/dal-bridge/src/index.js +1 -1
  65. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  66. package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
  67. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  68. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  69. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  70. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  71. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  72. package/dist/node_modules/@dalcode/dal-guard/src/attribution.js +1 -1
  73. package/dist/node_modules/@dalcode/dal-guard/src/index.js +4 -4
  74. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  75. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  76. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  77. package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
  78. package/dist/node_modules/@dalcode/dal-learn/src/lessons.js +4 -4
  79. package/dist/node_modules/@dalcode/dal-learn/src/project-map.js +2 -2
  80. package/dist/node_modules/@dalcode/dal-learn/src/signals.js +6 -6
  81. package/dist/node_modules/@dalcode/dal-lsp/package.json +4 -4
  82. package/dist/node_modules/@dalcode/dal-mcp/package.json +6 -6
  83. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  84. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
  85. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  86. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +3 -3
  87. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  88. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  89. package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
  90. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  91. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  92. package/dist/node_modules/@dalcode/dal-router/package.json +6 -6
  93. package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
  94. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  95. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  96. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  97. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  98. package/dist/node_modules/@dalcode/dal-sync/package.json +4 -4
  99. package/dist/node_modules/@dalcode/dal-telemetry/package.json +4 -4
  100. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  101. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  102. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  103. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  104. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  105. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  106. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  107. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  108. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  109. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  110. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  111. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  112. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  113. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  114. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  115. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
  116. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  117. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  118. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -1
  119. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -1
  120. package/dist/node_modules/@earendil-works/pi-ai/package.json +3 -3
  121. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  122. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  123. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  124. package/dist/node_modules/@earendil-works/pi-schema/package.json +1 -1
  125. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  126. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  127. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  128. package/examples/extensions/gondolin/package-lock.json +2 -2
  129. package/examples/extensions/gondolin/package.json +1 -1
  130. package/examples/extensions/with-deps/package-lock.json +2 -2
  131. package/examples/extensions/with-deps/package.json +1 -1
  132. package/npm-shrinkwrap.json +2 -2
  133. package/package.json +1 -1
  134. package/dist/bundle/chunks/chunk-JXAFVEE4.js +0 -17
  135. package/dist/bundle/chunks/chunk-SCZEDPDC.js +0 -9
  136. package/dist/bundle/chunks/sync-CRV6BXXC.js +0 -21
@@ -1,4 +1,4 @@
1
- var J=Object.defineProperty;var l=(e,n)=>J(e,"name",{value:n,configurable:!0});import{createRequire as Q}from"node:module";const De=Q(import.meta.url);import{getBinDir as ee}from"./chunk-R47JBGS3.js";var H=["*KEY*","*SECRET*","*TOKEN*","*PASSWORD*","*CREDENTIAL*","AWS_*","AZURE_*","GOOGLE_APPLICATION_CREDENTIALS","GH_*","GITHUB_TOKEN","NPM_TOKEN"],te=["PATH","HOME","USER","LOGNAME","SHELL","TMPDIR","TMP","TEMP","LANG","LC_*","TERM","COLORTERM","NO_COLOR","TZ","XDG_*","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT","USERPROFILE","APPDATA","LOCALAPPDATA"];function C(e){let n=e.map(t=>new RegExp(`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`,"i"));return t=>n.some(r=>r.test(t))}l(C,"patternMatcher");var ne=C(H),re=C(te);function B(e){return/^(DALCODE_|DAL_HOST_)/i.test(e)&&/(TOKEN|SECRET|KEY|PASSWORD|CREDENTIAL)/i.test(e)}l(B,"isDalCodeCredentialName");function ie(e){let n={};for(let[t,r]of Object.entries(e))B(t)||(n[t]=r);return n}l(ie,"withoutDalCodeCredentials");function k(e,n={}){let t=n.inherit??"all",r=C(n.include??[]),o=C(n.exclude??[]),u={};for(let[s,a]of Object.entries(e))t==="none"||t==="core"&&!re(s)||B(s)||ne(s)&&!r(s)||o(s)||(u[s]=a);for(let[s,a]of Object.entries(n.set??{}))B(s)||(u[s]=a);return u}l(k,"applyShellEnvironmentPolicy");var j={};function se(e){j=e??{}}l(se,"configureShellEnvironment");function le(){return j}l(le,"currentShellEnvironmentPolicy");import{accessSync as oe,constants as ae}from"node:fs";import{delimiter as G,join as ue,win32 as T}from"node:path";import{spawn as he,spawnSync as U}from"child_process";function fe(e){let n=T.normalize(e).toLowerCase(),t=process.env.SystemRoot;return t?/^[a-z]:[\\/]/i.test(t)?["System32","Sysnative"].some(r=>n===T.join(t,r,"bash.exe").toLowerCase()):!1:/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(n)}l(fe,"isLegacyWslBashPath");function y(e){return fe(e)?{shell:e,args:["-s"],commandTransport:"stdin"}:{shell:e,args:["-c"]}}l(y,"getBashShellConfig");function P(e){try{return oe(e,ae.F_OK),!0}catch{return!1}}l(P,"shellPathExists");function O(e){if(process.platform==="win32"){try{let n=U("where",[e],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(n.status===0&&n.stdout){let t=n.stdout.trim().split(/\r?\n/)[0];if(t&&P(t))return t}}catch{}return null}try{let n=U("which",[e],{encoding:"utf-8",timeout:5e3});if(n.status===0&&n.stdout){let t=n.stdout.trim().split(/\r?\n/)[0];if(t)return t}}catch{}return null}l(O,"findExecutableOnPath");function ce(e){if(e){if(P(e))return y(e);throw new Error(`Custom shell path not found: ${e}`)}if(process.platform==="win32"){let t=[],r=process.env.ProgramFiles;r&&t.push(`${r}\\Git\\bin\\bash.exe`);let o=process.env["ProgramFiles(x86)"];o&&t.push(`${o}\\Git\\bin\\bash.exe`);for(let s of t)if(P(s))return y(s);let u=O("bash.exe");if(u)return y(u);throw new Error(`No bash shell found. Options:
1
+ var J=Object.defineProperty;var l=(e,n)=>J(e,"name",{value:n,configurable:!0});import{createRequire as Q}from"node:module";const De=Q(import.meta.url);import{getBinDir as ee}from"./chunk-QM5JU2GS.js";var H=["*KEY*","*SECRET*","*TOKEN*","*PASSWORD*","*CREDENTIAL*","AWS_*","AZURE_*","GOOGLE_APPLICATION_CREDENTIALS","GH_*","GITHUB_TOKEN","NPM_TOKEN"],te=["PATH","HOME","USER","LOGNAME","SHELL","TMPDIR","TMP","TEMP","LANG","LC_*","TERM","COLORTERM","NO_COLOR","TZ","XDG_*","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT","USERPROFILE","APPDATA","LOCALAPPDATA"];function C(e){let n=e.map(t=>new RegExp(`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`,"i"));return t=>n.some(r=>r.test(t))}l(C,"patternMatcher");var ne=C(H),re=C(te);function B(e){return/^(DALCODE_|DAL_HOST_)/i.test(e)&&/(TOKEN|SECRET|KEY|PASSWORD|CREDENTIAL)/i.test(e)}l(B,"isDalCodeCredentialName");function ie(e){let n={};for(let[t,r]of Object.entries(e))B(t)||(n[t]=r);return n}l(ie,"withoutDalCodeCredentials");function k(e,n={}){let t=n.inherit??"all",r=C(n.include??[]),o=C(n.exclude??[]),u={};for(let[s,a]of Object.entries(e))t==="none"||t==="core"&&!re(s)||B(s)||ne(s)&&!r(s)||o(s)||(u[s]=a);for(let[s,a]of Object.entries(n.set??{}))B(s)||(u[s]=a);return u}l(k,"applyShellEnvironmentPolicy");var j={};function se(e){j=e??{}}l(se,"configureShellEnvironment");function le(){return j}l(le,"currentShellEnvironmentPolicy");import{accessSync as oe,constants as ae}from"node:fs";import{delimiter as G,join as ue,win32 as T}from"node:path";import{spawn as he,spawnSync as U}from"child_process";function fe(e){let n=T.normalize(e).toLowerCase(),t=process.env.SystemRoot;return t?/^[a-z]:[\\/]/i.test(t)?["System32","Sysnative"].some(r=>n===T.join(t,r,"bash.exe").toLowerCase()):!1:/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(n)}l(fe,"isLegacyWslBashPath");function y(e){return fe(e)?{shell:e,args:["-s"],commandTransport:"stdin"}:{shell:e,args:["-c"]}}l(y,"getBashShellConfig");function P(e){try{return oe(e,ae.F_OK),!0}catch{return!1}}l(P,"shellPathExists");function O(e){if(process.platform==="win32"){try{let n=U("where",[e],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(n.status===0&&n.stdout){let t=n.stdout.trim().split(/\r?\n/)[0];if(t&&P(t))return t}}catch{}return null}try{let n=U("which",[e],{encoding:"utf-8",timeout:5e3});if(n.status===0&&n.stdout){let t=n.stdout.trim().split(/\r?\n/)[0];if(t)return t}}catch{}return null}l(O,"findExecutableOnPath");function ce(e){if(e){if(P(e))return y(e);throw new Error(`Custom shell path not found: ${e}`)}if(process.platform==="win32"){let t=[],r=process.env.ProgramFiles;r&&t.push(`${r}\\Git\\bin\\bash.exe`);let o=process.env["ProgramFiles(x86)"];o&&t.push(`${o}\\Git\\bin\\bash.exe`);for(let s of t)if(P(s))return y(s);let u=O("bash.exe");if(u)return y(u);throw new Error(`No bash shell found. Options:
2
2
  1. Install Git for Windows: https://git-scm.com/download/win
3
3
  2. Add your bash to PATH (Cygwin, MSYS2, etc.)
4
4
  3. Set shellPath in settings.json
@@ -5,4 +5,4 @@ var b=Object.defineProperty;var r=(e,o)=>b(e,"name",{value:o,configurable:!0});i
5
5
 
6
6
  ${t}`);return o.join(`
7
7
 
8
- `)}r(I,"renderSystemMessageUpdate");function P(e,o,i=e.length){return`${e.slice(o,i)} `.slice(0,-1)}r(P,"ownedSlice");var s="1.0.58",T={name:"dal",url:"https://deepailab.ai",categories:["cli-agent"]},l="dal",M="integrate.api.nvidia.com",R="opencode.ai";function p(...e){let o;for(let i of e)i&&(o={...o},i.userAgent!==void 0&&(o.userAgent=i.userAgent),i.attribution!==void 0&&(o.attribution=i.attribution),i.version!==void 0&&(o.version=i.version));return o}r(p,"mergeClientIdentity");function f(e){return e?.version??s}r(f,"getClientVersion");function $(){if(typeof process>"u")return;let e=process.versions;if(e?.bun)return`bun/${e.bun}`;if(e?.node)return`node/${process.version}`}r($,"runtimeDescription");function g(e){let o=e?.userAgent??"detailed";if(typeof o=="object")return o.custom;if(o==="short")return l;let i=`${l}/${f(e)}`,a=$();return a?`${i} (${process.platform}; ${a}; ${process.arch})`:`${i} (browser)`}r(g,"formatUserAgent");function d(e,o){try{return new URL(e).hostname===o}catch{return!1}}r(d,"matchesHost");function S(e){return e.provider==="openrouter"||e.baseUrl.includes("openrouter.ai")}r(S,"isOpenRouter");function U(e){return e.provider==="nvidia"||d(e.baseUrl,M)}r(U,"isNvidiaNim");function v(e){return e.provider==="opencode"||e.provider==="opencode-go"||d(e.baseUrl,R)}r(v,"isOpenCode");function h(e,o){let i=o?.attribution;if(!i)return{};let{name:a,url:t,categories:n}=i;return S(e)?{"HTTP-Referer":t,"X-OpenRouter-Title":a,...n===void 0||n.length===0?{}:{"X-OpenRouter-Categories":n.join(",")}}:U(e)?{"X-BILLING-INVOKE-ORIGIN":a.charAt(0).toUpperCase()+a.slice(1)}:v(e)?{"x-opencode-client":a}:{}}r(h,"getAttributionHeaders");function m(e,o){return o&&v(e)?{"x-opencode-session":o}:void 0}r(m,"getOpenCodeSessionHeaders");function N(e,o){return{"User-Agent":g(o),...h(e,o)}}r(N,"getIdentityHeaders");function C(e){return"setProvider"in e&&"deleteProvider"in e&&"clearProviders"in e}r(C,"isMutableModels");function D(e,o){let i=r(t=>({...t,identity:p(o,t?.identity)}),"withIdentity"),a={getProviders:r(()=>e.getProviders(),"getProviders"),getProvider:r(t=>e.getProvider(t),"getProvider"),getModels:r(t=>e.getModels(t),"getModels"),getModel:r((t,n)=>e.getModel(t,n),"getModel"),getModelsOfType:r((t,n)=>e.getModelsOfType(t,n),"getModelsOfType"),getModelOfType:r((t,n,u)=>e.getModelOfType(t,n,u),"getModelOfType"),getAllModels:r(t=>e.getAllModels(t),"getAllModels"),refresh:r(t=>e.refresh(t),"refresh"),checkAuth:r((t,n)=>e.checkAuth(t,n),"checkAuth"),getAvailable:r((t,n)=>e.getAvailable(t,n),"getAvailable"),getAvailableOfType:r((t,n,u)=>e.getAvailableOfType(t,n,u),"getAvailableOfType"),getAllAvailable:r((t,n)=>e.getAllAvailable(t,n),"getAllAvailable"),getAuth:e.getAuth.bind(e),login:r((t,n,u,A)=>e.login(t,n,u,A),"login"),logout:r((t,n)=>e.logout(t,n),"logout"),stream:r((t,n,u)=>e.stream(t,n,i(u)),"stream"),complete:r((t,n,u)=>e.complete(t,n,i(u)),"complete"),streamSimple:r((t,n,u)=>e.streamSimple(t,n,i(u)),"streamSimple"),completeSimple:r((t,n,u)=>e.completeSimple(t,n,i(u)),"completeSimple"),streamDeferred:r((t,n,u)=>e.streamDeferred(t,n,i(u)),"streamDeferred"),fetchDeferred:r((t,n,u)=>e.fetchDeferred(t,n,i(u)),"fetchDeferred"),cancelDeferred:r((t,n,u)=>e.cancelDeferred(t,n,i(u)),"cancelDeferred"),generateImages:r((t,n,u)=>e.generateImages(t,n,i(u)),"generateImages"),classify:r((t,n,u)=>e.classify(t,n,i(u)),"classify")};return C(e)?{...a,setProvider:r(t=>e.setProvider(t),"setProvider"),deleteProvider:r(t=>e.deleteProvider(t),"deleteProvider"),clearProviders:r(()=>e.clearProviders(),"clearProviders")}:a}r(D,"withClientIdentity");export{s as PI_AI_VERSION,T as PI_ATTRIBUTION,c as contentText,g as formatUserAgent,h as getAttributionHeaders,f as getClientVersion,N as getIdentityHeaders,m as getOpenCodeSessionHeaders,y as getSystemMessageText,p as mergeClientIdentity,P as ownedSlice,I as renderSystemMessageUpdate,D as withClientIdentity};
8
+ `)}r(I,"renderSystemMessageUpdate");function P(e,o,i=e.length){return`${e.slice(o,i)} `.slice(0,-1)}r(P,"ownedSlice");var s="1.0.60",T={name:"dal",url:"https://deepailab.ai",categories:["cli-agent"]},l="dal",M="integrate.api.nvidia.com",R="opencode.ai";function p(...e){let o;for(let i of e)i&&(o={...o},i.userAgent!==void 0&&(o.userAgent=i.userAgent),i.attribution!==void 0&&(o.attribution=i.attribution),i.version!==void 0&&(o.version=i.version));return o}r(p,"mergeClientIdentity");function f(e){return e?.version??s}r(f,"getClientVersion");function $(){if(typeof process>"u")return;let e=process.versions;if(e?.bun)return`bun/${e.bun}`;if(e?.node)return`node/${process.version}`}r($,"runtimeDescription");function g(e){let o=e?.userAgent??"detailed";if(typeof o=="object")return o.custom;if(o==="short")return l;let i=`${l}/${f(e)}`,a=$();return a?`${i} (${process.platform}; ${a}; ${process.arch})`:`${i} (browser)`}r(g,"formatUserAgent");function d(e,o){try{return new URL(e).hostname===o}catch{return!1}}r(d,"matchesHost");function S(e){return e.provider==="openrouter"||e.baseUrl.includes("openrouter.ai")}r(S,"isOpenRouter");function U(e){return e.provider==="nvidia"||d(e.baseUrl,M)}r(U,"isNvidiaNim");function v(e){return e.provider==="opencode"||e.provider==="opencode-go"||d(e.baseUrl,R)}r(v,"isOpenCode");function h(e,o){let i=o?.attribution;if(!i)return{};let{name:a,url:t,categories:n}=i;return S(e)?{"HTTP-Referer":t,"X-OpenRouter-Title":a,...n===void 0||n.length===0?{}:{"X-OpenRouter-Categories":n.join(",")}}:U(e)?{"X-BILLING-INVOKE-ORIGIN":a.charAt(0).toUpperCase()+a.slice(1)}:v(e)?{"x-opencode-client":a}:{}}r(h,"getAttributionHeaders");function m(e,o){return o&&v(e)?{"x-opencode-session":o}:void 0}r(m,"getOpenCodeSessionHeaders");function N(e,o){return{"User-Agent":g(o),...h(e,o)}}r(N,"getIdentityHeaders");function C(e){return"setProvider"in e&&"deleteProvider"in e&&"clearProviders"in e}r(C,"isMutableModels");function D(e,o){let i=r(t=>({...t,identity:p(o,t?.identity)}),"withIdentity"),a={getProviders:r(()=>e.getProviders(),"getProviders"),getProvider:r(t=>e.getProvider(t),"getProvider"),getModels:r(t=>e.getModels(t),"getModels"),getModel:r((t,n)=>e.getModel(t,n),"getModel"),getModelsOfType:r((t,n)=>e.getModelsOfType(t,n),"getModelsOfType"),getModelOfType:r((t,n,u)=>e.getModelOfType(t,n,u),"getModelOfType"),getAllModels:r(t=>e.getAllModels(t),"getAllModels"),refresh:r(t=>e.refresh(t),"refresh"),checkAuth:r((t,n)=>e.checkAuth(t,n),"checkAuth"),getAvailable:r((t,n)=>e.getAvailable(t,n),"getAvailable"),getAvailableOfType:r((t,n,u)=>e.getAvailableOfType(t,n,u),"getAvailableOfType"),getAllAvailable:r((t,n)=>e.getAllAvailable(t,n),"getAllAvailable"),getAuth:e.getAuth.bind(e),login:r((t,n,u,A)=>e.login(t,n,u,A),"login"),logout:r((t,n)=>e.logout(t,n),"logout"),stream:r((t,n,u)=>e.stream(t,n,i(u)),"stream"),complete:r((t,n,u)=>e.complete(t,n,i(u)),"complete"),streamSimple:r((t,n,u)=>e.streamSimple(t,n,i(u)),"streamSimple"),completeSimple:r((t,n,u)=>e.completeSimple(t,n,i(u)),"completeSimple"),streamDeferred:r((t,n,u)=>e.streamDeferred(t,n,i(u)),"streamDeferred"),fetchDeferred:r((t,n,u)=>e.fetchDeferred(t,n,i(u)),"fetchDeferred"),cancelDeferred:r((t,n,u)=>e.cancelDeferred(t,n,i(u)),"cancelDeferred"),generateImages:r((t,n,u)=>e.generateImages(t,n,i(u)),"generateImages"),classify:r((t,n,u)=>e.classify(t,n,i(u)),"classify")};return C(e)?{...a,setProvider:r(t=>e.setProvider(t),"setProvider"),deleteProvider:r(t=>e.deleteProvider(t),"deleteProvider"),clearProviders:r(()=>e.clearProviders(),"clearProviders")}:a}r(D,"withClientIdentity");export{s as PI_AI_VERSION,T as PI_ATTRIBUTION,c as contentText,g as formatUserAgent,h as getAttributionHeaders,f as getClientVersion,N as getIdentityHeaders,m as getOpenCodeSessionHeaders,y as getSystemMessageText,p as mergeClientIdentity,P as ownedSlice,I as renderSystemMessageUpdate,D as withClientIdentity};
@@ -1,4 +1,4 @@
1
- var Te=Object.defineProperty;var d=(s,e)=>Te(s,"name",{value:e,configurable:!0});import{createRequire as Fe}from"node:module";const It=Fe(import.meta.url);import{fill as De}from"./chunk-G5AMLGXC.js";import{APP_NAME as Me,APP_TITLE as Ne,getAgentDir as $,getSessionsDir as Ae,normalizePath as b,pathsEqual as Re,resolvePath as S}from"./chunk-R47JBGS3.js";import{reportNewerDataFormat as Be,t as Oe,writeFileAtomicSync as Le}from"./chunk-QU2VEHMW.js";import{uuidv7 as $e}from"./chunk-IEBK4HQA.js";import{getCurrentSystemMessage as Pe}from"./chunk-5MF5GEDD.js";var je=`The conversation history before this point was compacted into the following summary:
1
+ var Te=Object.defineProperty;var d=(s,e)=>Te(s,"name",{value:e,configurable:!0});import{createRequire as Fe}from"node:module";const It=Fe(import.meta.url);import{fill as De}from"./chunk-G5AMLGXC.js";import{APP_NAME as Me,APP_TITLE as Ne,getAgentDir as $,getSessionsDir as Ae,normalizePath as b,pathsEqual as Re,resolvePath as S}from"./chunk-QM5JU2GS.js";import{reportNewerDataFormat as Be,t as Oe,writeFileAtomicSync as Le}from"./chunk-3KEFLXX2.js";import{uuidv7 as $e}from"./chunk-IEBK4HQA.js";import{getCurrentSystemMessage as Pe}from"./chunk-4KCKRVPN.js";var je=`The conversation history before this point was compacted into the following summary:
2
2
 
3
3
  <summary>
4
4
  `,ke=`
@@ -0,0 +1,9 @@
1
+ var ye=Object.defineProperty;var e=(o,t)=>ye(o,"name",{value:t,configurable:!0});import{createRequire as Le}from"node:module";const Pi=Le(import.meta.url);import{ADAPTATION_FILE as Ie,AgentSession as Fe,AgentSessionRuntime as Oe,AssistantMessageComponent as Ne,BackgroundProcessManager as we,BashExecutionComponent as ve,BorderedLoader as Me,BranchSummaryMessageComponent as He,CompactionSummaryMessageComponent as xe,CustomEditor as be,CustomMessageComponent as Be,DEFAULT_COMPACTION_SETTINGS as Ue,DefaultPackageManager as je,DefaultResourceLoader as Ke,DynamicBorder as We,ENGINE_MARKET_CACHE_FILE as Ge,ExtensionEditorComponent as $e,ExtensionFatalError as Ve,ExtensionInputComponent as ze,ExtensionRunner as Je,ExtensionSelectorComponent as Xe,FooterComponent as Ye,HOST_CAPABILITIES_ENV as qe,HOST_TOKEN_ENV as Qe,HOST_TOKEN_HEADER as Ze,HOST_URL_ENV as et,HostCallError as tt,HostCapabilities as ot,InteractiveMode as rt,LoginDialogComponent as nt,MARKET_SECTIONS as it,MAX_BACKGROUND_PROCESSES as st,ModelRegistry as at,ModelSelectorComponent as lt,OAuthSelectorComponent as ut,PROTECTED_WRITE_NAMES as ct,REQUIRED_EXTENSION_FAILED as dt,RequiredExtensionError as mt,RpcClient as pt,RpcCommandError as Et,SANDBOX_ENV as St,SessionSelectorComponent as gt,SettingsManager as ht,SettingsSelectorComponent as ft,ShellSandbox as Tt,SkillInvocationMessageComponent as Ct,ThinkingSelectorComponent as kt,ToolExecutionComponent as _t,TreeSelectorComponent as Dt,UserMessageComponent as At,UserMessageSelectorComponent as Pt,adaptPackage as Rt,adaptationState as yt,agentLogPath as Lt,appendAgentLog as It,applyCommunityEnv as Ft,buildProjectMap as Ot,buildRuleSet as Nt,calculateContextTokens as wt,chromeBottom as te,chromeTop as oe,collectEntriesForBranchSummary as vt,communityEnv as Mt,compact as Ht,convertToPng as xt,copyToClipboard as bt,createAgentSession as Bt,createAgentSessionFromServices as Ut,createAgentSessionRuntime as jt,createAgentSessionServices as Kt,createBashTool as Wt,createBashToolDefinition as Gt,createCodemodeExtension as $t,createCodingTools as Vt,createEditTool as zt,createEditToolDefinition as Jt,createEventBus as Xt,createExtensionRuntime as Yt,createFindTool as qt,createFindToolDefinition as Qt,createGrepTool as Zt,createGrepToolDefinition as eo,createLocalBashOperations as to,createLocalPowerShellOperations as oo,createLsTool as ro,createLsToolDefinition as no,createMcpExtension as io,createPowerShellTool as so,createPowerShellToolDefinition as ao,createProcessToolDefinition as lo,createReadOnlyTools as uo,createReadTool as co,createReadToolDefinition as mo,createSyntheticSourceInfo as po,createToolSearchExtension as Eo,createWriteTool as So,createWriteToolDefinition as go,defineTool as ho,describeProjectFacts as fo,detectProjectFacts as To,detectSandboxAvailability as Co,detectSupportedImageMimeTypeFromFile as ko,discoverAndLoadExtensions as _o,ensurePackageAdapted as Do,estimateTokens as Ao,evaluateToolPolicy as Po,expandTempDirVariable as Ro,fetchSignedMarket as yo,findCutPoint as Lo,findTurnStartIndex as Io,formatDimensionNote as Fo,formatProjectMapPrompt as Oo,formatSkillsForPrompt as No,generateBranchSummary as wo,generateDiffString as vo,generateSummary as Mo,generateSummaryWithUsage as Ho,generateUnifiedPatch as xo,getHostCapabilities as bo,getLastAssistantUsage as Bo,getProcessShellSandbox as Uo,getToolDenial as jo,isAdaptablePackage as Ko,isBashToolResult as Wo,isEditToolResult as Go,isFatalExtensionError as $o,isFindToolResult as Vo,isGrepToolResult as zo,isHostExtensionPath as Jo,isLsToolResult as Xo,isPowerShellToolResult as Yo,isReadOnlyBashCommand as qo,isReadToolResult as Qo,isToolCallEventType as Zo,isWriteToolResult as er,loadMcpRuntime as tr,loadProjectContextFiles as or,loadSkills as rr,loadSkillsFromDir as nr,main as ir,markHostExtensionPaths as sr,marketCacheDir as ar,matchPermissionRules as lr,normalizeForFuzzyMatch as ur,parseArgs as cr,parseFrontmatter as dr,parseHostCapabilities as mr,parsePermissionRule as pr,parseSkillBlock as Er,prepareBranchEntries as Sr,projectPackageManager as gr,readAccessDenial as hr,readAdaptation as fr,readSignedSection as Tr,registerPermissionAskHandler as Cr,registerSandboxEscalationHandler as kr,registerShellExecutionGuard as _r,renderDiff as Dr,resizeImage as Ar,resolveCliModel as Pr,resolveMarketEndpoint as Rr,resolveModelScopeWithDiagnostics as yr,resolveSandboxPolicy as Lr,resolveToCwd as Ir,runPrintMode as Fr,runRpcMode as Or,scanHardcodedPiPaths as Nr,serializeConversation as wr,shellExecutionRefusal as vr,shouldCompact as Mr,simpleCommands as Hr,stripFrontmatter as xr,systemTempDirs as br,tryEnsurePackageAdapted as Br,unwrapCommand as Ur,verifyAdaptation as jr,verifySignedSection as Kr,withFileMutationQueue as Wr,wrapRegisteredTool as Gr,wrapRegisteredTools as $r}from"./chunk-4TEICWYC.js";import{CURRENT_SESSION_VERSION as Vr,SessionManager as zr,buildContextEntries as Jr,buildSessionContext as Xr,buildSessionProjection as Yr,convertToLlm as qr,getDefaultSessionDir as Qr,getDefaultSessionDirs as Zr,getLatestCompactionEntry as en,migrateSessionEntries as tn,parseSessionEntries as on,sessionEntryToContextMessages as rn}from"./chunk-E6RWRE6C.js";import{CredentialSynchronizationError as nn,DALCODE_PROJECT_DIR_NAME as sn,DEFAULT_HOOK_TIMEOUT_SECONDS as an,ModelRuntime as ln,PROJECT_HOOKS_FILE_ENV as un,ProjectTrustStore as cn,TRUST_REQUIRING_PROJECT_HOOK_FILES as dn,VIRTUAL_MODEL_STATE_ENTRY as mn,dalHookSourceFiles as pn,deriveHookName as En,hasTrustRequiringProjectResources as Sn,loadDalHooks as re,openBrowser as gn,projectFileDeclaresHooks as hn,projectHooksFileFromEnv as ne}from"./chunk-P3KSBU23.js";import{formatReadLineRange as fn,truncateToVisualLines as Tn}from"./chunk-XQ6Z77K4.js";import{readStoredCredential as Cn}from"./chunk-H3KG4L7I.js";import{DEFAULT_MAX_BYTES as kn,DEFAULT_MAX_LINES as _n,DEFAULT_SHELL_ENV_EXCLUDES as Dn,applyShellEnvironmentPolicy as An,formatSize as Pn,getPowerShellConfig as Rn,getShellConfig as yn,getShellEnv as Ln,isDalCodeCredentialName as In,truncateHead as Fn,truncateLine as On,truncateTail as Nn,withoutDalCodeCredentials as ie}from"./chunk-B66W54NL.js";import{ArminComponent as wn}from"./chunk-LGD3AMTG.js";import{Container as se,SelectList as ae,Theme as vn,getAvailableThemes as Mn,getLanguageFromPath as Hn,getMarkdownTheme as xn,getSelectListTheme as N,getSettingsListTheme as bn,highlightCode as Bn,initTheme as Un,keyHint as jn,keyText as Kn,rawKeyHint as Wn}from"./chunk-NRQYSXAU.js";import{APP_TITLE as Gn,CONFIG_DIR_NAME as $n,SHARED_SKILL_CONFIG_DIRS as Vn,VERSION as zn,getAgentDir as le,getDocsPath as Jn,getExamplesPath as Xn,getPackageDir as Yn,getReadmePath as qn}from"./chunk-QM5JU2GS.js";import{t as S}from"./chunk-3KEFLXX2.js";import{__export as Qn}from"./chunk-JXWJOIH4.js";var ue={};Qn(ue,{ADAPTATION_FILE:e(()=>Ie,"ADAPTATION_FILE"),APP_TITLE:e(()=>Gn,"APP_TITLE"),AgentSession:e(()=>Fe,"AgentSession"),AgentSessionRuntime:e(()=>Oe,"AgentSessionRuntime"),ArminComponent:e(()=>wn,"ArminComponent"),AssistantMessageComponent:e(()=>Ne,"AssistantMessageComponent"),BackgroundProcessManager:e(()=>we,"BackgroundProcessManager"),BashExecutionComponent:e(()=>ve,"BashExecutionComponent"),BorderedLoader:e(()=>Me,"BorderedLoader"),BranchSummaryMessageComponent:e(()=>He,"BranchSummaryMessageComponent"),CONFIG_DIR_NAME:e(()=>$n,"CONFIG_DIR_NAME"),CURRENT_SESSION_VERSION:e(()=>Vr,"CURRENT_SESSION_VERSION"),CompactionSummaryMessageComponent:e(()=>xe,"CompactionSummaryMessageComponent"),CredentialSynchronizationError:e(()=>nn,"CredentialSynchronizationError"),CustomEditor:e(()=>be,"CustomEditor"),CustomMessageComponent:e(()=>Be,"CustomMessageComponent"),DALCODE_PROJECT_DIR_NAME:e(()=>sn,"DALCODE_PROJECT_DIR_NAME"),DAL_HOOK_ENTRY_TYPE:e(()=>B,"DAL_HOOK_ENTRY_TYPE"),DAL_HOOK_NOTIFICATION_CHANNEL:e(()=>ee,"DAL_HOOK_NOTIFICATION_CHANNEL"),DEFAULT_COMPACTION_SETTINGS:e(()=>Ue,"DEFAULT_COMPACTION_SETTINGS"),DEFAULT_HOOK_TIMEOUT_SECONDS:e(()=>an,"DEFAULT_HOOK_TIMEOUT_SECONDS"),DEFAULT_MAX_BYTES:e(()=>kn,"DEFAULT_MAX_BYTES"),DEFAULT_MAX_LINES:e(()=>_n,"DEFAULT_MAX_LINES"),DEFAULT_SHELL_ENV_EXCLUDES:e(()=>Dn,"DEFAULT_SHELL_ENV_EXCLUDES"),DefaultPackageManager:e(()=>je,"DefaultPackageManager"),DefaultResourceLoader:e(()=>Ke,"DefaultResourceLoader"),DynamicBorder:e(()=>We,"DynamicBorder"),ENGINE_MARKET_CACHE_FILE:e(()=>Ge,"ENGINE_MARKET_CACHE_FILE"),ExtensionEditorComponent:e(()=>$e,"ExtensionEditorComponent"),ExtensionFatalError:e(()=>Ve,"ExtensionFatalError"),ExtensionInputComponent:e(()=>ze,"ExtensionInputComponent"),ExtensionRunner:e(()=>Je,"ExtensionRunner"),ExtensionSelectorComponent:e(()=>Xe,"ExtensionSelectorComponent"),FooterComponent:e(()=>Ye,"FooterComponent"),HOST_CAPABILITIES_ENV:e(()=>qe,"HOST_CAPABILITIES_ENV"),HOST_TOKEN_ENV:e(()=>Qe,"HOST_TOKEN_ENV"),HOST_TOKEN_HEADER:e(()=>Ze,"HOST_TOKEN_HEADER"),HOST_URL_ENV:e(()=>et,"HOST_URL_ENV"),HostCallError:e(()=>tt,"HostCallError"),HostCapabilities:e(()=>ot,"HostCapabilities"),InteractiveMode:e(()=>rt,"InteractiveMode"),LoginDialogComponent:e(()=>nt,"LoginDialogComponent"),MARKET_SECTIONS:e(()=>it,"MARKET_SECTIONS"),MAX_BACKGROUND_PROCESSES:e(()=>st,"MAX_BACKGROUND_PROCESSES"),ModelRegistry:e(()=>at,"ModelRegistry"),ModelRuntime:e(()=>ln,"ModelRuntime"),ModelSelectorComponent:e(()=>lt,"ModelSelectorComponent"),OAuthSelectorComponent:e(()=>ut,"OAuthSelectorComponent"),PROJECT_HOOKS_FILE_ENV:e(()=>un,"PROJECT_HOOKS_FILE_ENV"),PROTECTED_WRITE_NAMES:e(()=>ct,"PROTECTED_WRITE_NAMES"),ProjectTrustStore:e(()=>cn,"ProjectTrustStore"),REQUIRED_EXTENSION_FAILED:e(()=>dt,"REQUIRED_EXTENSION_FAILED"),RequiredExtensionError:e(()=>mt,"RequiredExtensionError"),RpcClient:e(()=>pt,"RpcClient"),RpcCommandError:e(()=>Et,"RpcCommandError"),SANDBOX_ENV:e(()=>St,"SANDBOX_ENV"),SHARED_SKILL_CONFIG_DIRS:e(()=>Vn,"SHARED_SKILL_CONFIG_DIRS"),STALE_AFTER_MS:e(()=>H,"STALE_AFTER_MS"),SessionManager:e(()=>zr,"SessionManager"),SessionSelectorComponent:e(()=>gt,"SessionSelectorComponent"),SettingsManager:e(()=>ht,"SettingsManager"),SettingsSelectorComponent:e(()=>ft,"SettingsSelectorComponent"),ShellSandbox:e(()=>Tt,"ShellSandbox"),ShowImagesSelectorComponent:e(()=>Pe,"ShowImagesSelectorComponent"),SkillInvocationMessageComponent:e(()=>Ct,"SkillInvocationMessageComponent"),TRUST_REQUIRING_PROJECT_HOOK_FILES:e(()=>dn,"TRUST_REQUIRING_PROJECT_HOOK_FILES"),Theme:e(()=>vn,"Theme"),ThemeSelectorComponent:e(()=>Re,"ThemeSelectorComponent"),ThinkingSelectorComponent:e(()=>kt,"ThinkingSelectorComponent"),ToolExecutionComponent:e(()=>_t,"ToolExecutionComponent"),TreeSelectorComponent:e(()=>Dt,"TreeSelectorComponent"),UserMessageComponent:e(()=>At,"UserMessageComponent"),UserMessageSelectorComponent:e(()=>Pt,"UserMessageSelectorComponent"),VERSION:e(()=>zn,"VERSION"),VIRTUAL_MODEL_STATE_ENTRY:e(()=>mn,"VIRTUAL_MODEL_STATE_ENTRY"),WORKSPACE_LOCK_DIR_NAME:e(()=>v,"WORKSPACE_LOCK_DIR_NAME"),WORKSPACE_LOCK_FILE:e(()=>L,"WORKSPACE_LOCK_FILE"),adaptPackage:e(()=>Rt,"adaptPackage"),adaptationState:e(()=>yt,"adaptationState"),agentLogPath:e(()=>Lt,"agentLogPath"),appendAgentLog:e(()=>It,"appendAgentLog"),applyCommunityEnv:e(()=>Ft,"applyCommunityEnv"),applyShellEnvironmentPolicy:e(()=>An,"applyShellEnvironmentPolicy"),buildContextEntries:e(()=>Jr,"buildContextEntries"),buildDalHookInput:e(()=>V,"buildDalHookInput"),buildProjectMap:e(()=>Ot,"buildProjectMap"),buildRuleSet:e(()=>Nt,"buildRuleSet"),buildSessionContext:e(()=>Xr,"buildSessionContext"),buildSessionProjection:e(()=>Yr,"buildSessionProjection"),calculateContextTokens:e(()=>wt,"calculateContextTokens"),claimWorkspace:e(()=>pe,"claimWorkspace"),collectEntriesForBranchSummary:e(()=>vt,"collectEntriesForBranchSummary"),communityEnv:e(()=>Mt,"communityEnv"),compact:e(()=>Ht,"compact"),convertToLlm:e(()=>qr,"convertToLlm"),convertToPng:e(()=>xt,"convertToPng"),copyToClipboard:e(()=>bt,"copyToClipboard"),createAgentSession:e(()=>Bt,"createAgentSession"),createAgentSessionFromServices:e(()=>Ut,"createAgentSessionFromServices"),createAgentSessionRuntime:e(()=>jt,"createAgentSessionRuntime"),createAgentSessionServices:e(()=>Kt,"createAgentSessionServices"),createBashTool:e(()=>Wt,"createBashTool"),createBashToolDefinition:e(()=>Gt,"createBashToolDefinition"),createCodemodeExtension:e(()=>$t,"createCodemodeExtension"),createCodingTools:e(()=>Vt,"createCodingTools"),createEditTool:e(()=>zt,"createEditTool"),createEditToolDefinition:e(()=>Jt,"createEditToolDefinition"),createEventBus:e(()=>Xt,"createEventBus"),createExtensionRuntime:e(()=>Yt,"createExtensionRuntime"),createFindTool:e(()=>qt,"createFindTool"),createFindToolDefinition:e(()=>Qt,"createFindToolDefinition"),createGrepTool:e(()=>Zt,"createGrepTool"),createGrepToolDefinition:e(()=>eo,"createGrepToolDefinition"),createLocalBashOperations:e(()=>to,"createLocalBashOperations"),createLocalPowerShellOperations:e(()=>oo,"createLocalPowerShellOperations"),createLsTool:e(()=>ro,"createLsTool"),createLsToolDefinition:e(()=>no,"createLsToolDefinition"),createMcpExtension:e(()=>io,"createMcpExtension"),createPowerShellTool:e(()=>so,"createPowerShellTool"),createPowerShellToolDefinition:e(()=>ao,"createPowerShellToolDefinition"),createProcessToolDefinition:e(()=>lo,"createProcessToolDefinition"),createReadOnlyTools:e(()=>uo,"createReadOnlyTools"),createReadTool:e(()=>co,"createReadTool"),createReadToolDefinition:e(()=>mo,"createReadToolDefinition"),createSyntheticSourceInfo:e(()=>po,"createSyntheticSourceInfo"),createToolSearchExtension:e(()=>Eo,"createToolSearchExtension"),createWriteTool:e(()=>So,"createWriteTool"),createWriteToolDefinition:e(()=>go,"createWriteToolDefinition"),dalHookActivity:e(()=>g,"dalHookActivity"),dalHookSourceFiles:e(()=>pn,"dalHookSourceFiles"),dalHooksExtension:e(()=>Ae,"dalHooksExtension"),decideDalHooks:e(()=>$,"decideDalHooks"),defaultWorkspaceLockDir:e(()=>M,"defaultWorkspaceLockDir"),defineTool:e(()=>ho,"defineTool"),deriveHookName:e(()=>En,"deriveHookName"),describeProjectFacts:e(()=>fo,"describeProjectFacts"),detectProjectFacts:e(()=>To,"detectProjectFacts"),detectSandboxAvailability:e(()=>Co,"detectSandboxAvailability"),detectSupportedImageMimeTypeFromFile:e(()=>ko,"detectSupportedImageMimeTypeFromFile"),discoverAndLoadExtensions:e(()=>_o,"discoverAndLoadExtensions"),engineToolInput:e(()=>j,"engineToolInput"),ensurePackageAdapted:e(()=>Do,"ensurePackageAdapted"),estimateTokens:e(()=>Ao,"estimateTokens"),evaluateToolPolicy:e(()=>Po,"evaluateToolPolicy"),expandTempDirVariable:e(()=>Ro,"expandTempDirVariable"),fetchSignedMarket:e(()=>yo,"fetchSignedMarket"),findCutPoint:e(()=>Lo,"findCutPoint"),findTurnStartIndex:e(()=>Io,"findTurnStartIndex"),formatDalHookActivity:e(()=>U,"formatDalHookActivity"),formatDimensionNote:e(()=>Fo,"formatDimensionNote"),formatProjectMapPrompt:e(()=>Oo,"formatProjectMapPrompt"),formatReadLineRange:e(()=>fn,"formatReadLineRange"),formatSize:e(()=>Pn,"formatSize"),formatSkillsForPrompt:e(()=>No,"formatSkillsForPrompt"),generateBranchSummary:e(()=>wo,"generateBranchSummary"),generateDiffString:e(()=>vo,"generateDiffString"),generateSummary:e(()=>Mo,"generateSummary"),generateSummaryWithUsage:e(()=>Ho,"generateSummaryWithUsage"),generateUnifiedPatch:e(()=>xo,"generateUnifiedPatch"),getAgentDir:e(()=>le,"getAgentDir"),getDefaultSessionDir:e(()=>Qr,"getDefaultSessionDir"),getDefaultSessionDirs:e(()=>Zr,"getDefaultSessionDirs"),getDocsPath:e(()=>Jn,"getDocsPath"),getExamplesPath:e(()=>Xn,"getExamplesPath"),getHostCapabilities:e(()=>bo,"getHostCapabilities"),getLanguageFromPath:e(()=>Hn,"getLanguageFromPath"),getLastAssistantUsage:e(()=>Bo,"getLastAssistantUsage"),getLatestCompactionEntry:e(()=>en,"getLatestCompactionEntry"),getMarkdownTheme:e(()=>xn,"getMarkdownTheme"),getPackageDir:e(()=>Yn,"getPackageDir"),getPowerShellConfig:e(()=>Rn,"getPowerShellConfig"),getProcessShellSandbox:e(()=>Uo,"getProcessShellSandbox"),getReadmePath:e(()=>qn,"getReadmePath"),getSelectListTheme:e(()=>N,"getSelectListTheme"),getSettingsListTheme:e(()=>bn,"getSettingsListTheme"),getShellConfig:e(()=>yn,"getShellConfig"),getShellEnv:e(()=>Ln,"getShellEnv"),getToolDenial:e(()=>jo,"getToolDenial"),gitDirOf:e(()=>x,"gitDirOf"),hasTrustRequiringProjectResources:e(()=>Sn,"hasTrustRequiringProjectResources"),highlightCode:e(()=>Bn,"highlightCode"),hookToolInput:e(()=>F,"hookToolInput"),hookToolName:e(()=>P,"hookToolName"),initTheme:e(()=>Un,"initTheme"),isAdaptablePackage:e(()=>Ko,"isAdaptablePackage"),isBashToolResult:e(()=>Wo,"isBashToolResult"),isDalCodeCredentialName:e(()=>In,"isDalCodeCredentialName"),isDalHookActivity:e(()=>ge,"isDalHookActivity"),isEditToolResult:e(()=>Go,"isEditToolResult"),isFatalExtensionError:e(()=>$o,"isFatalExtensionError"),isFindToolResult:e(()=>Vo,"isFindToolResult"),isGrepToolResult:e(()=>zo,"isGrepToolResult"),isHostExtensionPath:e(()=>Jo,"isHostExtensionPath"),isLsToolResult:e(()=>Xo,"isLsToolResult"),isPowerShellToolResult:e(()=>Yo,"isPowerShellToolResult"),isReadOnlyBashCommand:e(()=>qo,"isReadOnlyBashCommand"),isReadToolResult:e(()=>Qo,"isReadToolResult"),isToolCallEventType:e(()=>Zo,"isToolCallEventType"),isWriteToolResult:e(()=>er,"isWriteToolResult"),keyHint:e(()=>jn,"keyHint"),keyText:e(()=>Kn,"keyText"),loadDalHooks:e(()=>re,"loadDalHooks"),loadMcpRuntime:e(()=>tr,"loadMcpRuntime"),loadProjectContextFiles:e(()=>or,"loadProjectContextFiles"),loadSkills:e(()=>rr,"loadSkills"),loadSkillsFromDir:e(()=>nr,"loadSkillsFromDir"),main:e(()=>ir,"main"),markHostExtensionPaths:e(()=>sr,"markHostExtensionPaths"),marketCacheDir:e(()=>ar,"marketCacheDir"),matchPermissionRules:e(()=>lr,"matchPermissionRules"),migrateSessionEntries:e(()=>tn,"migrateSessionEntries"),normalizeForFuzzyMatch:e(()=>ur,"normalizeForFuzzyMatch"),openBrowser:e(()=>gn,"openBrowser"),parseArgs:e(()=>cr,"parseArgs"),parseFrontmatter:e(()=>dr,"parseFrontmatter"),parseHostCapabilities:e(()=>mr,"parseHostCapabilities"),parsePermissionRule:e(()=>pr,"parsePermissionRule"),parseSessionEntries:e(()=>on,"parseSessionEntries"),parseSkillBlock:e(()=>Er,"parseSkillBlock"),prepareBranchEntries:e(()=>Sr,"prepareBranchEntries"),projectFileDeclaresHooks:e(()=>hn,"projectFileDeclaresHooks"),projectHooksFileFromEnv:e(()=>ne,"projectHooksFileFromEnv"),projectPackageManager:e(()=>gr,"projectPackageManager"),rawKeyHint:e(()=>Wn,"rawKeyHint"),readAccessDenial:e(()=>hr,"readAccessDenial"),readAdaptation:e(()=>fr,"readAdaptation"),readSignedSection:e(()=>Tr,"readSignedSection"),readStoredCredential:e(()=>Cn,"readStoredCredential"),readWorkspaceLock:e(()=>de,"readWorkspaceLock"),registerPermissionAskHandler:e(()=>Cr,"registerPermissionAskHandler"),registerSandboxEscalationHandler:e(()=>kr,"registerSandboxEscalationHandler"),registerShellExecutionGuard:e(()=>_r,"registerShellExecutionGuard"),releaseWorkspace:e(()=>Ee,"releaseWorkspace"),renderDiff:e(()=>Dr,"renderDiff"),reportDalHookProblems:e(()=>z,"reportDalHookProblems"),resizeImage:e(()=>Ar,"resizeImage"),resolveCliModel:e(()=>Pr,"resolveCliModel"),resolveMarketEndpoint:e(()=>Rr,"resolveMarketEndpoint"),resolveModelScopeWithDiagnostics:e(()=>yr,"resolveModelScopeWithDiagnostics"),resolveSandboxPolicy:e(()=>Lr,"resolveSandboxPolicy"),resolveToCwd:e(()=>Ir,"resolveToCwd"),runDalCommandHook:e(()=>W,"runDalCommandHook"),runDalHookEvent:e(()=>T,"runDalHookEvent"),runDalHooks:e(()=>G,"runDalHooks"),runNotificationHooks:e(()=>Z,"runNotificationHooks"),runPostToolUseHooks:e(()=>X,"runPostToolUseHooks"),runPreToolUseHooks:e(()=>J,"runPreToolUseHooks"),runPrintMode:e(()=>Fr,"runPrintMode"),runRpcMode:e(()=>Or,"runRpcMode"),runSessionStartHooks:e(()=>Y,"runSessionStartHooks"),runStopHooks:e(()=>Q,"runStopHooks"),runUserPromptSubmitHooks:e(()=>q,"runUserPromptSubmitHooks"),scanHardcodedPiPaths:e(()=>Nr,"scanHardcodedPiPaths"),selectDalHooks:e(()=>K,"selectDalHooks"),serializeConversation:e(()=>wr,"serializeConversation"),sessionEntryToContextMessages:e(()=>rn,"sessionEntryToContextMessages"),shellCommandDirectory:e(()=>Se,"shellCommandDirectory"),shellExecutionRefusal:e(()=>vr,"shellExecutionRefusal"),shouldCompact:e(()=>Mr,"shouldCompact"),simpleCommands:e(()=>Hr,"simpleCommands"),stripFrontmatter:e(()=>xr,"stripFrontmatter"),systemTempDirs:e(()=>br,"systemTempDirs"),toolMatchNames:e(()=>O,"toolMatchNames"),truncateHead:e(()=>Fn,"truncateHead"),truncateLine:e(()=>On,"truncateLine"),truncateTail:e(()=>Nn,"truncateTail"),truncateToVisualLines:e(()=>Tn,"truncateToVisualLines"),tryEnsurePackageAdapted:e(()=>Br,"tryEnsurePackageAdapted"),unwrapCommand:e(()=>Ur,"unwrapCommand"),verifyAdaptation:e(()=>jr,"verifyAdaptation"),verifySignedSection:e(()=>Kr,"verifySignedSection"),withFileMutationQueue:e(()=>Wr,"withFileMutationQueue"),withoutDalCodeCredentials:e(()=>ie,"withoutDalCodeCredentials"),workspaceLockIsLive:e(()=>I,"workspaceLockIsLive"),workspaceLockPath:e(()=>D,"workspaceLockPath"),workspaceOwnerSessionId:e(()=>b,"workspaceOwnerSessionId"),wrapRegisteredTool:e(()=>Gr,"wrapRegisteredTool"),wrapRegisteredTools:e(()=>$r,"wrapRegisteredTools")});import{execFileSync as Zn}from"node:child_process";import{createHash as ei}from"node:crypto";import{mkdirSync as ti,readFileSync as oi,realpathSync as ri,renameSync as ni,rmSync as ii,writeFileSync as si}from"node:fs";import{hostname as R}from"node:os";import{basename as w,isAbsolute as ai,join as y,resolve as k}from"node:path";var v="workspace-locks",L="dal-workspace.lock";function M(){return y(le(),v)}e(M,"defaultWorkspaceLockDir");function D(o,t=M()){let r=k(o);try{r=ri.native(r)}catch{}let n=ei("sha256").update(r).digest("hex").slice(0,16),a=w(r)===".git"?w(k(r,"..")):w(r);return y(t,`${a.replace(/[^\w.-]/g,"_").slice(0,40)||"repo"}-${n}.lock`)}e(D,"workspaceLockPath");var H=7200*1e3,li=60*1e3,ui="DALCODE_PARENT_SESSION_ID",ce=new Map;function x(o){let t=k(o),r=ce.get(t);if(r!==void 0)return r??void 0;let n=null;try{let a=Zn("git",["rev-parse","--git-dir","--show-toplevel"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim().split(`
2
+ `),l=a[0]?.trim();l&&(n={gitDir:ai(l)?l:k(t,l),worktree:a[1]?.trim()})}catch{n=null}return ce.set(t,n),n??void 0}e(x,"gitDirOf");function b(o,t=process.env){return t[ui]||o}e(b,"workspaceOwnerSessionId");function A(o){try{let t=JSON.parse(oi(o,"utf8"));return typeof t.pid!="number"||typeof t.sessionId!="string"||typeof t.host!="string"?void 0:{pid:t.pid,host:t.host,sessionId:t.sessionId,startedAt:typeof t.startedAt=="string"?t.startedAt:new Date(0).toISOString(),refreshedAt:typeof t.refreshedAt=="string"?t.refreshedAt:new Date(0).toISOString(),...typeof t.worktree=="string"?{worktree:t.worktree}:{}}}catch{return}}e(A,"readLockFile");function de(o,t){return A(D(o,t))??A(y(o,L))}e(de,"readWorkspaceLock");function ci(o){try{return process.kill(o,0),!0}catch(t){return t.code==="EPERM"}}e(ci,"processAlive");function I(o,t=Date.now()){let r=Date.parse(o.refreshedAt);return!Number.isFinite(r)||t-r>H?!1:o.host===R()?ci(o.pid):!0}e(I,"workspaceLockIsLive");function me(o,t){ti(k(o,".."),{recursive:!0});let r=`${o}.${process.pid}.tmp`;si(r,`${JSON.stringify(t,null,2)}
3
+ `),ni(r,o)}e(me,"writeLock");function pe(o,t,r={}){let n=x(o);if(!n)return;let a=r.now??Date.now(),l=b(t,r.env),d=D(n.gitDir,r.lockDir),c=A(d),u={gitDir:n.gitDir,...n.worktree?{worktree:n.worktree}:{}},i=A(y(n.gitDir,L));for(let s of[c,i])if(s&&s.sessionId!==l&&I(s,a)&&!r.force)return{...u,heldBy:s};if(c?.sessionId===l&&I(c,a)){if(!(c.pid===process.pid&&c.host===R())||a-Date.parse(c.refreshedAt)<li)return u;try{me(d,{...c,refreshedAt:new Date(a).toISOString()})}catch{}return u}try{me(d,{pid:process.pid,host:R(),sessionId:l,startedAt:new Date(a).toISOString(),refreshedAt:new Date(a).toISOString(),...n.worktree?{worktree:n.worktree}:{}})}catch{return}return u}e(pe,"claimWorkspace");function Ee(o,t){let r=D(o,t),n=A(r);if(!(!n||n.pid!==process.pid||n.host!==R()))try{ii(r,{force:!0})}catch{}}e(Ee,"releaseWorkspace");function Se(o,t){let r=t;for(let a of o.split(/&&|;|\n/)){let l=/^\s*cd\s+("([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(a);if(!l)break;let d=(l[2]??l[3]??l[4]??"").replace(/^~(?=\/|$)/,process.env.HOME??"~");r=k(r,d)}let n=/\bgit\s+-C\s+("([^"]+)"|'([^']+)'|(\S+))/.exec(o);return n&&(r=k(r,n[2]??n[3]??n[4]??".")),r}e(Se,"shellCommandDirectory");var B="dal-hook";function h(o,t){return o.replace(/\{(\w+)\}/g,(r,n)=>String(t[n]??""))}e(h,"fill");function di(o,t=300){let r=(o??"").replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}\u2026`:r}e(di,"oneLine");function U(o){let t={name:o.hookName??"",tool:o.toolName??"",event:o.event,detail:di(o.detail),path:o.path??"",seconds:o.timeoutSeconds??""};switch(o.kind){case"blocked":return o.toolName?h(S("\u94A9\u5B50 {name} \u62E6\u622A\u4E86 {tool}\uFF1A{detail}"),t):h(S("\u94A9\u5B50 {name} \u62E6\u622A\u4E86\u8FD9\u6761\u6D88\u606F\uFF1A{detail}"),t);case"modified":return h(S("\u94A9\u5B50 {name} \u4FEE\u6539\u4E86 {tool} \u7684\u8F93\u5165"),t);case"context":return h(S("\u94A9\u5B50 {name} \u4E3A {event} \u8865\u5145\u4E86\u4E0A\u4E0B\u6587"),t);case"message":return h(S("\u94A9\u5B50 {name}\uFF1A{detail}"),t);case"stop-ignored":return h(S("\u94A9\u5B50 {name} \u8981\u6C42\u7EE7\u7EED\u5DE5\u4F5C\uFF0C\u4F46 Stop \u94A9\u5B50\u4E0D\u80FD\u8BA9\u56DE\u5408\u7EED\u8DD1\uFF0C\u5DF2\u5FFD\u7565\uFF1A{detail}"),t);case"failed":return h(S("\u94A9\u5B50 {name}\uFF08{event}\uFF09\u8FD0\u884C\u5931\u8D25\uFF0C\u5DF2\u7EE7\u7EED\uFF1A{detail}"),t);case"timeout":return h(S("\u94A9\u5B50 {name}\uFF08{event}\uFF09\u8D85\u8FC7 {seconds} \u79D2\u672A\u7ED3\u675F\uFF0C\u5DF2\u7EC8\u6B62\u5E76\u7EE7\u7EED"),t);case"config":return h(S("\u94A9\u5B50\u914D\u7F6E\u6709\u8BEF\uFF08{path}\uFF09\uFF1A{detail}"),t)}}e(U,"formatDalHookActivity");var mi=new Set(["stop-ignored","failed","timeout","config"]);function g(o){return{...o,text:U(o),level:mi.has(o.kind)?"warning":"info"}}e(g,"dalHookActivity");function ge(o){if(typeof o!="object"||o===null)return!1;let t=o;return typeof t.kind=="string"&&typeof t.event=="string"&&typeof t.text=="string"}e(ge,"isDalHookActivity");import{spawn as he}from"node:child_process";var fe=64*1024,pi={bash:"Bash",powershell:"PowerShell",read:"Read",write:"Write",edit:"Edit",grep:"Grep",find:"Glob",ls:"LS",task:"Task"},Te=new Set(["read","write","edit"]);function P(o){return pi[o]??o}e(P,"hookToolName");function F(o,t){return Te.has(o)&&typeof t.path=="string"&&t.file_path===void 0?{...t,file_path:t.path}:{...t}}e(F,"hookToolInput");function j(o,t){if(!Te.has(o)||!("file_path"in t))return{...t};let{file_path:r,...n}=t;return typeof r=="string"?{...n,path:r}:n}e(j,"engineToolInput");function Ei(o,t){if(/^[A-Za-z0-9_|-]+$/.test(o)){let n=o.split("|").filter(Boolean);return t.some(a=>n.includes(a))}let r;try{r=new RegExp(`^(?:${o})$`)}catch{return!1}return t.some(n=>r.test(n))}e(Ei,"matcherAccepts");function K(o,t,r){return o.filter(n=>n.event!==t?!1:n.matcher===void 0||r===void 0?!0:Ei(n.matcher,r))}e(K,"selectDalHooks");function O(o){return[o,P(o)]}e(O,"toolMatchNames");function Ce(o){if(o!==void 0)try{process.platform==="win32"?he("taskkill",["/pid",String(o),"/t","/f"],{stdio:"ignore"}):process.kill(-o,"SIGKILL")}catch{}}e(Ce,"killTree");function Si(o){let t=o.trim();if(t.startsWith("{"))try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0}catch{return}}e(Si,"parseJsonObject");function W(o,t,r){let n=Date.now();return new Promise(a=>{let l="",d="",c=!1,u=!1,i=he(o.command,{cwd:r.cwd,shell:!0,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"],env:{...ie(process.env),...r.env,DAL_PROJECT_DIR:r.cwd,CLAUDE_PROJECT_DIR:r.cwd}}),s=e(m=>{c||(c=!0,clearTimeout(p),r.signal?.removeEventListener("abort",E),a({hook:o,stdout:l,stderr:d,durationMs:Date.now()-n,...m}))},"finish"),p=setTimeout(()=>{u=!0,Ce(i.pid)},o.timeoutSeconds*1e3),E=e(()=>Ce(i.pid),"onAbort");r.signal?.addEventListener("abort",E,{once:!0}),i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",m=>{l.length<fe&&(l+=m)}),i.stderr.on("data",m=>{d.length<fe&&(d+=m)}),i.stdin.on("error",()=>{}),i.stdin.end(JSON.stringify(t)),i.on("error",m=>{s({status:"failed",exitCode:null,error:m.message})}),i.on("close",m=>{if(u){s({status:"timeout",exitCode:m,error:`timed out after ${o.timeoutSeconds}s`});return}if(r.signal?.aborted){s({status:"failed",exitCode:m,error:"cancelled"});return}if(m===2){s({status:"blocked",exitCode:m});return}if(m!==0){s({status:"failed",exitCode:m,error:`exited with code ${m}`});return}let C=Si(l);s({status:"success",exitCode:0,...C?{output:C}:{}})})})}e(W,"runDalCommandHook");function G(o,t,r){return Promise.all(o.map(n=>W(n,t,r)))}e(G,"runDalHooks");function _(o,t){let r=o?.[t];return typeof r=="string"&&r.trim()!==""?r:void 0}e(_,"stringField");var gi=new Set(["SessionStart","UserPromptSubmit"]);function $(o,t){let r,n,a,l=[],d=[],c=[];for(let u of t){if(u.status==="failed"||u.status==="timeout"){c.push(u);continue}if(u.status==="blocked"){r??={hook:u.hook,reason:u.stderr.trim()||`hook ${u.hook.name} blocked (exit 2)`};continue}let i=u.output;if(!i){gi.has(o)&&u.stdout.trim()!==""&&l.push({hook:u.hook,text:u.stdout.trim()});continue}let s=typeof i.hookSpecificOutput=="object"&&i.hookSpecificOutput!==null?i.hookSpecificOutput:void 0,p=_(s,"permissionDecisionReason")??_(i,"reason");i.continue===!1&&(n??={hook:u.hook,reason:_(i,"stopReason")??p??u.hook.name}),(_(s,"permissionDecision")==="deny"||i.decision==="block")&&(r??={hook:u.hook,reason:p??`hook ${u.hook.name} blocked`});let E=s?.updatedInput;typeof E=="object"&&E!==null&&!Array.isArray(E)&&(a={hook:u.hook,input:E});let m=_(s,"additionalContext");m&&l.push({hook:u.hook,text:m});let C=_(i,"systemMessage");C&&d.push({hook:u.hook,text:C})}return{...r?{blocked:r}:{},...n?{stop:n}:{},...a?{updatedInput:a}:{},additionalContext:l,systemMessages:d,failures:c}}e($,"decideDalHooks");function V(o,t,r={}){return{session_id:t.sessionId,transcript_path:t.transcriptPath??"",cwd:t.cwd,...t.permissionMode?{permission_mode:t.permissionMode}:{},...t.agentId?{agent_id:t.agentId}:{},...t.agentType?{agent_type:t.agentType}:{},hook_event_name:o,...r}}e(V,"buildDalHookInput");function f(o){return{hookName:o.name,scope:o.scope}}e(f,"scopeOf");function hi(o,t,r){for(let n of t.failures)r(g({kind:n.status==="timeout"?"timeout":"failed",event:o,...f(n.hook),detail:fi(n),timeoutSeconds:n.hook.timeoutSeconds}));for(let n of t.systemMessages)r(g({kind:"message",event:o,...f(n.hook),detail:n.text}))}e(hi,"reportCommon");function fi(o){let t=o.stderr.trim();return t?`${o.error??""} ${t}`.trim():o.error??""}e(fi,"failureDetail");function z(o,t){for(let r of o.problems)t(g({kind:"config",event:r.event??"",path:r.path,detail:r.message}))}e(z,"reportDalHookProblems");async function T(o,t,r,n){let a=K(o.config.hooks,t,n);if(a.length===0)return;let l=await G(a,V(t,o.base,r),{cwd:o.base.cwd,...o.signal?{signal:o.signal}:{}}),d=$(t,l);return hi(t,d,o.report),d}e(T,"runDalHookEvent");async function J(o,t){let r=await T(o,"PreToolUse",{tool_name:P(t.toolName),tool_input:F(t.toolName,t.input),tool_use_id:t.toolCallId},O(t.toolName));if(!r)return{};let n=r.stop??r.blocked;return n?(o.report(g({kind:"blocked",event:"PreToolUse",...f(n.hook),toolName:t.toolName,detail:n.reason})),{blockReason:`[hook ${n.hook.name}] ${n.reason}`,...r.stop?{stop:!0}:{}}):r.updatedInput?(o.report(g({kind:"modified",event:"PreToolUse",...f(r.updatedInput.hook),toolName:t.toolName})),{input:j(t.toolName,r.updatedInput.input)}):{}}e(J,"runPreToolUseHooks");async function X(o,t){let r=t.isError?"PostToolUseFailure":"PostToolUse",n=await T(o,r,{tool_name:P(t.toolName),tool_input:F(t.toolName,t.input),tool_use_id:t.toolCallId,...t.isError?{error:t.output}:{tool_response:{content:t.output,...t.details!==void 0?{details:t.details}:{}}}},O(t.toolName));if(!n)return{};let a=[],l=n.stop??n.blocked;l&&(o.report(g({kind:"blocked",event:r,...f(l.hook),toolName:t.toolName,detail:l.reason})),a.push(`[hook ${l.hook.name}] ${l.reason}`));for(let d of n.additionalContext)o.report(g({kind:"context",event:r,...f(d.hook),toolName:t.toolName})),a.push(`[hook ${d.hook.name}] ${d.text}`);return a.length>0?{appendText:a.join(`
4
+ `)}:{}}e(X,"runPostToolUseHooks");async function Y(o,t){let r=await T(o,"SessionStart",{source:t},[t]);return ke("SessionStart",r,o.report)}e(Y,"runSessionStartHooks");function ke(o,t,r){if(!(!t||t.additionalContext.length===0)){for(let n of t.additionalContext)r(g({kind:"context",event:o,...f(n.hook)}));return t.additionalContext.map(n=>n.text).join(`
5
+
6
+ `)}}e(ke,"contextOf");async function q(o,t){let r=await T(o,"UserPromptSubmit",{prompt:t});if(!r)return{};let n=r.stop??r.blocked;if(n)return o.report(g({kind:"blocked",event:"UserPromptSubmit",...f(n.hook),detail:n.reason})),{blockReason:n.reason};let a=ke("UserPromptSubmit",r,o.report);return a?{additionalContext:a}:{}}e(q,"runUserPromptSubmitHooks");async function Q(o){let t=await T(o,"Stop",{stop_hook_active:!1}),r=t?.blocked??t?.stop;r&&o.report(g({kind:"stop-ignored",event:"Stop",...f(r.hook),detail:r.reason}))}e(Q,"runStopHooks");async function Z(o,t){await T(o,"Notification",{message:t.message,notification_type:t.type},[t.type])}e(Z,"runNotificationHooks");var _e="dal-hook-context",ee="dal:hook-notification";function De(o=process.env){return o.DALCODE_BRIDGE_URL?!1:Number.parseInt(o.DAL_SUBAGENT_DEPTH??"0",10)<=0}e(De,"runsPromptHooksHere");function Ti(o){if(typeof o!="object"||o===null)return!1;let{type:t,message:r}=o;return typeof t=="string"&&typeof r=="string"}e(Ti,"isNotification");function Ci(o){return o.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
7
+ `)}e(Ci,"textOf");function Ae(o){let t,r="",n,a,l=e(i=>{n=n?`${n}
8
+
9
+ ${i}`:i},"queueContext"),d=e(i=>s=>{o.appendEntry(B,s),i.hasUI&&i.ui.notify(s.text,s.level)},"report"),c=e(i=>{t=re({cwd:i.cwd,projectTrusted:i.isProjectTrusted(),projectHooksFile:ne()});let s=JSON.stringify(t.problems);return s!==r&&(r=s,z(t,d(i))),t},"refresh"),u=e((i,s)=>({config:s,base:{sessionId:i.sessionManager.getSessionId(),transcriptPath:i.sessionManager.getSessionFile()??"",cwd:i.cwd},report:d(i),...i.signal?{signal:i.signal}:{}}),"callContext");o.on("session_start",async(i,s)=>{a=s;let p=c(s),E=await Y(u(s,p),i.reason);E&&l(E)}),o.on("input",async(i,s)=>{if(i.source==="extension"||!De())return;a=s;let p=await q(u(s,c(s)),i.text);if(p.blockReason!==void 0)return{action:"handled"};p.additionalContext&&(i.streamingBehavior?o.sendMessage({customType:_e,content:p.additionalContext,display:!1},{deliverAs:i.streamingBehavior}):l(p.additionalContext))}),o.events.on(ee,async i=>{let s=a;!s||!Ti(i)||!De()||await Z(u(s,t??c(s)),i)}),o.on("before_agent_start",async(i,s)=>{if(c(s),!n)return;let p=n;return n=void 0,{message:{customType:_e,content:p,display:!1}}}),o.on("tool_call",async(i,s)=>{a=s;let p=t??c(s),E=await J(u(s,p),{toolName:i.toolName,toolCallId:i.toolCallId,input:i.input});if(E.blockReason!==void 0)return{block:!0,reason:E.blockReason,...E.stop?{terminate:!0}:{}};if(E.input){let m=i.input;for(let C of Object.keys(m))delete m[C];Object.assign(m,E.input)}}),o.on("tool_result",async(i,s)=>{let p=t??c(s),{appendText:E}=await X(u(s,p),{toolName:i.toolName,toolCallId:i.toolCallId,input:i.input,output:Ci(i.content),isError:i.isError,details:i.details});if(E)return{content:[...i.content,{type:"text",text:E}]}}),o.on("agent_end",async(i,s)=>{let p=t??c(s);await Q(u(s,p))})}e(Ae,"dalHooksExtension");var ki={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},Pe=class extends se{static{e(this,"ShowImagesSelectorComponent")}selectList;constructor(o,t,r){super();let n=[{value:"yes",label:S("\u662F"),description:S("\u5728\u7EC8\u7AEF\u91CC\u76F4\u63A5\u663E\u793A\u56FE\u7247")},{value:"no",label:S("\u5426"),description:S("\u6539\u4E3A\u663E\u793A\u6587\u5B57\u5360\u4F4D")}];this.addChild(oe(S("\u56FE\u7247\u663E\u793A"))),this.selectList=new ae(n,5,N(),ki),this.selectList.setSelectedIndex(o?0:1),this.selectList.onSelect=a=>{t(a.value==="yes")},this.selectList.onCancel=()=>{r()},this.addChild(this.selectList),this.addChild(te())}getSelectList(){return this.selectList}},_i={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},Re=class extends se{static{e(this,"ThemeSelectorComponent")}selectList;onPreview;constructor(o,t,r,n){super(),this.onPreview=n;let a=Mn(),l=a.map(c=>({value:c,label:c,description:c===o?S("(\u5F53\u524D)"):void 0}));this.addChild(oe(S("\u9009\u62E9\u4E3B\u9898"))),this.selectList=new ae(l,10,N(),_i);let d=a.indexOf(o);d!==-1&&this.selectList.setSelectedIndex(d),this.selectList.onSelect=c=>{t(c.value)},this.selectList.onCancel=()=>{r()},this.selectList.onSelectionChange=c=>{this.onPreview(c.value)},this.addChild(this.selectList),this.addChild(te())}getSelectList(){return this.selectList}};export{B as DAL_HOOK_ENTRY_TYPE,ee as DAL_HOOK_NOTIFICATION_CHANNEL,H as STALE_AFTER_MS,Pe as ShowImagesSelectorComponent,Re as ThemeSelectorComponent,v as WORKSPACE_LOCK_DIR_NAME,L as WORKSPACE_LOCK_FILE,V as buildDalHookInput,pe as claimWorkspace,g as dalHookActivity,Ae as dalHooksExtension,$ as decideDalHooks,M as defaultWorkspaceLockDir,ue as dist_exports,j as engineToolInput,U as formatDalHookActivity,x as gitDirOf,F as hookToolInput,P as hookToolName,ge as isDalHookActivity,de as readWorkspaceLock,Ee as releaseWorkspace,z as reportDalHookProblems,W as runDalCommandHook,T as runDalHookEvent,G as runDalHooks,Z as runNotificationHooks,X as runPostToolUseHooks,J as runPreToolUseHooks,Y as runSessionStartHooks,Q as runStopHooks,q as runUserPromptSubmitHooks,K as selectDalHooks,Se as shellCommandDirectory,O as toolMatchNames,I as workspaceLockIsLive,D as workspaceLockPath,b as workspaceOwnerSessionId};
@@ -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 Dr=st(import.meta.url);import{getShellConfig as nt}from"./chunk-HF334NQU.js";import{getAgentDir as U,getFileRevision as N,normalizePath as V,require_cross_spawn as ot,stripBom as te}from"./chunk-R47JBGS3.js";import{require_graceful_fs as fe}from"./chunk-XJFQKN3N.js";import{writeFileAtomicSync as pe}from"./chunk-QU2VEHMW.js";import{__commonJS as P,__require as re,__toESM as me}from"./chunk-JXWJOIH4.js";var at=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}}}),lt=P({"node_modules/proper-lockfile/node_modules/retry/lib/retry.js"(e){var t=at();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}}}}),ut=P({"node_modules/proper-lockfile/node_modules/retry/index.js"(e,t){t.exports=lt()}}),ct=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")}}),dt=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=ct(),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}}),ht=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}}),ft=P({"node_modules/proper-lockfile/lib/lockfile.js"(e,t){"use strict";var r=re("path"),i=fe(),s=ut(),n=dt(),a=ht(),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,R=>{if(!R)return a.probe(E,c.fs,(_,C,M)=>{if(_)return c.fs.rmdir(E,()=>{}),d(_);d(null,C,M)});if(R.code!=="EEXIST")return d(R);if(c.stale<=0)return d(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:p}));c.fs.stat(E,(_,C)=>{if(_)return _.code==="ENOENT"?f(p,{...c,stale:0},d):d(_);if(!g(C,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,R)=>{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()!==R.mtime.getTime())return v(p,d,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let C=a.getMtime(d.mtimePrecision);c.fs.utimes(d.lockfilePath,C,C,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=C,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,R)=>{if(E)return d(E);let _=s.operation(c.retries);_.attempt(()=>{f(R,c,(C,M,Q)=>{if(_.retry(C))return;if(C)return d(_.mainError());let rt=l[R]={lockfilePath:u(R,c),mtime:M,mtimePrecision:Q,options:c,lastUpdate:Date.now()};w(R,c),d(null,ee=>{if(rt.released)return ee&&ee(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));b(R,{...c,realpath:!1},ee)})})})})}o(x,"lock");function b(p,c,d){c={fs:i,realpath:!0,...c},h(p,c,(E,R)=>{if(E)return d(E);let _=l[R];if(!_)return d(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));_.updateTimeout&&clearTimeout(_.updateTimeout),_.released=!0,delete l[R],m(R,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,R)=>{if(E)return d(E);c.fs.stat(u(R,c),(_,C)=>_?_.code==="ENOENT"?d(null,!1):d(_):d(null,!g(C,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}}),pt=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=ft(),{toPromise:i,toSync:s,toSyncOptions:n}=pt();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"}},mt=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 B(e){return e instanceof Error?e:new Error(String(e))}o(B,"toError");function F(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}o(F,"isJsonRpcId");function se(e){return T(e)&&e.jsonrpc==="2.0"&&F(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"||!F(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",yt=[oe,"2025-06-18","2025-03-26","2024-11-05"],gt=3e4,ve=1e3;function vt(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(vt,"validateInitializeResult");function j(e){return new A(L.invalidRequest,e)}o(j,"invalid");function wt(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(wt,"validateListPage");var Et=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 St(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(St,"validateReadResourceResult");function _t(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(_t,"validateCallToolResult");var xt=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=vt(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(!yt.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",Et,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 St(await this.request("resources/read",{uri:e},t))}async listPage(e,t,r,i,s){return wt(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 _t(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??gt,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:B(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)||!F(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)&&F(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 mt(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=B(e);for(let r of this.errorListeners)r(t)}disposeTransportListeners(){for(let e of this.disposers.splice(0))e()}},bt=me(ot(),1);import{spawn as Tt}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=B(e);for(let r of this.errorListeners)r(t)}emitClose(){if(!this.closeEmitted){this.closeEmitted=!0;for(let e of this.closeListeners)e()}}},Rt=64*1024,Ct=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??Rt;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}},Mt=2e3,Pt=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;Tt("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 Lt(){Te||(Te=!0,O.once("exit",()=>{for(let e of ae)try{O.kill(-e,"SIGTERM")}catch{}}))}o(Lt,"installExitHook");var At=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 Ct({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,bt.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&&(Lt(),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 Dr=st(import.meta.url);import{getShellConfig as nt}from"./chunk-B66W54NL.js";import{getAgentDir as U,getFileRevision as N,normalizePath as V,require_cross_spawn as ot,stripBom as te}from"./chunk-QM5JU2GS.js";import{require_graceful_fs as fe}from"./chunk-XJFQKN3N.js";import{writeFileAtomicSync as pe}from"./chunk-3KEFLXX2.js";import{__commonJS as P,__require as re,__toESM as me}from"./chunk-JXWJOIH4.js";var at=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}}}),lt=P({"node_modules/proper-lockfile/node_modules/retry/lib/retry.js"(e){var t=at();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}}}}),ut=P({"node_modules/proper-lockfile/node_modules/retry/index.js"(e,t){t.exports=lt()}}),ct=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")}}),dt=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=ct(),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}}),ht=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}}),ft=P({"node_modules/proper-lockfile/lib/lockfile.js"(e,t){"use strict";var r=re("path"),i=fe(),s=ut(),n=dt(),a=ht(),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,R=>{if(!R)return a.probe(E,c.fs,(_,C,M)=>{if(_)return c.fs.rmdir(E,()=>{}),d(_);d(null,C,M)});if(R.code!=="EEXIST")return d(R);if(c.stale<=0)return d(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:p}));c.fs.stat(E,(_,C)=>{if(_)return _.code==="ENOENT"?f(p,{...c,stale:0},d):d(_);if(!g(C,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,R)=>{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()!==R.mtime.getTime())return v(p,d,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let C=a.getMtime(d.mtimePrecision);c.fs.utimes(d.lockfilePath,C,C,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=C,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,R)=>{if(E)return d(E);let _=s.operation(c.retries);_.attempt(()=>{f(R,c,(C,M,Q)=>{if(_.retry(C))return;if(C)return d(_.mainError());let rt=l[R]={lockfilePath:u(R,c),mtime:M,mtimePrecision:Q,options:c,lastUpdate:Date.now()};w(R,c),d(null,ee=>{if(rt.released)return ee&&ee(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));b(R,{...c,realpath:!1},ee)})})})})}o(x,"lock");function b(p,c,d){c={fs:i,realpath:!0,...c},h(p,c,(E,R)=>{if(E)return d(E);let _=l[R];if(!_)return d(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));_.updateTimeout&&clearTimeout(_.updateTimeout),_.released=!0,delete l[R],m(R,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,R)=>{if(E)return d(E);c.fs.stat(u(R,c),(_,C)=>_?_.code==="ENOENT"?d(null,!1):d(_):d(null,!g(C,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}}),pt=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=ft(),{toPromise:i,toSync:s,toSyncOptions:n}=pt();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"}},mt=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 B(e){return e instanceof Error?e:new Error(String(e))}o(B,"toError");function F(e){return typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}o(F,"isJsonRpcId");function se(e){return T(e)&&e.jsonrpc==="2.0"&&F(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"||!F(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",yt=[oe,"2025-06-18","2025-03-26","2024-11-05"],gt=3e4,ve=1e3;function vt(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(vt,"validateInitializeResult");function j(e){return new A(L.invalidRequest,e)}o(j,"invalid");function wt(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(wt,"validateListPage");var Et=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 St(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(St,"validateReadResourceResult");function _t(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(_t,"validateCallToolResult");var xt=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=vt(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(!yt.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",Et,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 St(await this.request("resources/read",{uri:e},t))}async listPage(e,t,r,i,s){return wt(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 _t(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??gt,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:B(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)||!F(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)&&F(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 mt(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=B(e);for(let r of this.errorListeners)r(t)}disposeTransportListeners(){for(let e of this.disposers.splice(0))e()}},bt=me(ot(),1);import{spawn as Tt}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=B(e);for(let r of this.errorListeners)r(t)}emitClose(){if(!this.closeEmitted){this.closeEmitted=!0;for(let e of this.closeListeners)e()}}},Rt=64*1024,Ct=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??Rt;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}},Mt=2e3,Pt=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;Tt("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 Lt(){Te||(Te=!0,O.once("exit",()=>{for(let e of ae)try{O.kill(-e,"SIGTERM")}catch{}}))}o(Lt,"installExitHook");var At=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 Ct({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,bt.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&&(Lt(),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??Mt;await new Promise(r=>{let i=[];e.once("close",()=>{for(let n of i)clearTimeout(n);le(e,"SIGTERM"),r()});let s=Math.min(Pt,t);i.push(setTimeout(()=>le(e,"SIGTERM"),s)),i.push(setTimeout(()=>le(e,"SIGKILL"),s+t)),e.stdin?.end()})}},It=8*1024,Re=500,kt=1e3,Ot=3e4,$t=5;async function Dt(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 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-5MF5GEDD.js";import{getSystemMessageText as F}from"./chunk-JK74OC6W.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-4KCKRVPN.js";import{getSystemMessageText as F}from"./chunk-CIJDL6I3.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,4 +1,4 @@
1
- var L=Object.defineProperty;var c=(a,n)=>L(a,"name",{value:n,configurable:!0});import{createRequire as F}from"node:module";const _e=F(import.meta.url);import{shortHash as N}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta as D,closeGrammarToolInputJson as H,getGrammarToolInput as V,getJsonSchemaToolParameters as Z,resolveGrammarConstrainedSampling as K,resolveJsonSchemaStrictSampling as Q,transformMessages as X}from"./chunk-B7KZDIWA.js";import{sanitizeSurrogates as w}from"./chunk-L2ZPNLYD.js";import{ToolCallArgumentsStream as Y}from"./chunk-FFMDRXC4.js";import{calculateCost as ee,resolveTranscript as te,resolveTranscriptTools as ne}from"./chunk-5MF5GEDD.js";import{getSystemMessageText as oe,renderSystemMessageUpdate as ae}from"./chunk-JK74OC6W.js";function se(a,n){let s={v:1,id:a};return n&&(s.phase=n),JSON.stringify(s)}c(se,"encodeTextSignatureV1");function le(a){if(a){if(a.startsWith("{"))try{let n=JSON.parse(a);if(n.v===1&&typeof n.id=="string")return n.phase==="commentary"||n.phase==="final_answer"?{id:n.id,phase:n.phase}:{id:n.id}}catch{}return{id:a}}}c(le,"parseTextSignature");function ie(a,n){let s=n.filter(p=>p.type==="text").map(p=>p.text).join(`
1
+ var L=Object.defineProperty;var c=(a,n)=>L(a,"name",{value:n,configurable:!0});import{createRequire as F}from"node:module";const _e=F(import.meta.url);import{shortHash as N}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta as D,closeGrammarToolInputJson as H,getGrammarToolInput as V,getJsonSchemaToolParameters as Z,resolveGrammarConstrainedSampling as K,resolveJsonSchemaStrictSampling as Q,transformMessages as X}from"./chunk-HZWPNFQO.js";import{sanitizeSurrogates as w}from"./chunk-L2ZPNLYD.js";import{ToolCallArgumentsStream as Y}from"./chunk-FFMDRXC4.js";import{calculateCost as ee,resolveTranscript as te,resolveTranscriptTools as ne}from"./chunk-4KCKRVPN.js";import{getSystemMessageText as oe,renderSystemMessageUpdate as ae}from"./chunk-CIJDL6I3.js";function se(a,n){let s={v:1,id:a};return n&&(s.phase=n),JSON.stringify(s)}c(se,"encodeTextSignatureV1");function le(a){if(a){if(a.startsWith("{"))try{let n=JSON.parse(a);if(n.v===1&&typeof n.id=="string")return n.phase==="commentary"||n.phase==="final_answer"?{id:n.id,phase:n.phase}:{id:n.id}}catch{}return{id:a}}}c(le,"parseTextSignature");function ie(a,n){let s=n.filter(p=>p.type==="text").map(p=>p.text).join(`
2
2
  `),u=n.filter(p=>p.type==="image"),f=s.trim().length>0;if(u.length===0||!a.input.includes("image"))return w(f?s:u.length>0?"(see attached image)":"(no tool output)");let r=[];f&&r.push({type:"input_text",text:w(s)});for(let p of u)r.push({type:"input_image",detail:"auto",image_url:`data:${p.mimeType};base64,${p.data}`});return r}c(ie,"convertToolResultOutput");function G(a){return a.supportsMidConvoSystemMessages&&a.supportsAdditionalTools?"changes":a.supportsToolSearch?"additions":"none"}c(G,"getResponsesToolSupport");function re(a){let n="This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.";return a.size>0?`${n}
3
3
  Still unavailable: ${[...a].join(", ")}.`:n}c(re,"renderIncrementalToolsNotice");function pe(a){return`The following tools are no longer available. Do not call them:
4
4
  ${a.map(n=>`- ${n}`).join(`
@@ -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-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
+ 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-NRQYSXAU.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};