@maincode-ai/matilda-code 0.21.12 → 0.21.13

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 (150) hide show
  1. package/bundled/mainy/docs/configuration/model-providers.md +0 -82
  2. package/bundled/mainy/docs/configuration/settings.md +30 -2
  3. package/bundled/mainy/docs/features/auto-mode.md +1 -1
  4. package/bundled/mainy/docs/features/channels/_meta.ts +0 -3
  5. package/bundled/mainy/docs/features/channels/overview.md +8 -16
  6. package/bundled/mainy/docs/features/commands.md +4 -4
  7. package/bundled/mainy/docs/features/hooks.md +9 -7
  8. package/bundled/mainy/docs/features/language.md +2 -29
  9. package/bundled/mainy/docs/features/worktree.md +0 -2
  10. package/bundled/mainy/docs/integration-github-action.md +3 -3
  11. package/bundled/mainy/docs/quickstart.md +2 -2
  12. package/bundled/mainy/docs/support/troubleshooting.md +1 -1
  13. package/chunks/agent-SRAIVZEE.js +3 -0
  14. package/chunks/agent-headless-XRDOZESG.js +3 -0
  15. package/chunks/{anthropicContentGenerator-VKFTAIU3.js → anthropicContentGenerator-LLDIKDMQ.js} +3 -3
  16. package/chunks/{askUserQuestion-2QI4NSFJ.js → askUserQuestion-BNSWGD26.js} +1 -1
  17. package/chunks/{ca-I2HEEIL7.js → ca-NPYL24ME.js} +2 -2
  18. package/chunks/{chunk-YJAKOETP.js → chunk-27HUYW23.js} +2 -2
  19. package/chunks/{chunk-EQGA7LH7.js → chunk-3B2HABK7.js} +1 -1
  20. package/chunks/{chunk-CSJTA7NE.js → chunk-3MTZTNAU.js} +18 -18
  21. package/chunks/{chunk-YRQP3SLC.js → chunk-5OHGYMKP.js} +1 -1
  22. package/chunks/chunk-6I6VGTKD.js +8 -0
  23. package/chunks/{chunk-MCQUPLRE.js → chunk-6M5G5FBH.js} +1 -1
  24. package/chunks/chunk-7ZODGQO6.js +4 -0
  25. package/chunks/chunk-AOOZREGV.js +9 -0
  26. package/chunks/chunk-DHDD5YJC.js +207 -0
  27. package/chunks/{chunk-WV3IUPZS.js → chunk-EZDV7A76.js} +1 -1
  28. package/chunks/{chunk-QVCGLQCI.js → chunk-IJEGHQ7Z.js} +3 -3
  29. package/chunks/{chunk-5C2RJ5RR.js → chunk-LWARA7JY.js} +1 -1
  30. package/chunks/{chunk-VTGICC67.js → chunk-MEV5XQI2.js} +1 -1
  31. package/chunks/{chunk-DOOFGSRV.js → chunk-P5TG5CON.js} +1 -1
  32. package/chunks/{chunk-JRECUFB3.js → chunk-PEKAUGYV.js} +552 -561
  33. package/chunks/chunk-PGUG43HG.js +24 -0
  34. package/chunks/{chunk-CZGZ3KK7.js → chunk-QZI2ZGZY.js} +1 -1
  35. package/chunks/chunk-RI54U73U.js +56 -0
  36. package/chunks/chunk-RPFSFS7Z.js +39 -0
  37. package/chunks/chunk-SOEIVSM5.js +113 -0
  38. package/chunks/{chunk-4J6DC24J.js → chunk-SVSY6AWS.js} +1 -1
  39. package/chunks/{chunk-6E766NPX.js → chunk-TWJLOEAI.js} +1 -1
  40. package/chunks/{chunk-HYVP4472.js → chunk-V6UPUMP3.js} +1 -1
  41. package/chunks/chunk-W4QSMIWO.js +9 -0
  42. package/chunks/chunk-ZX34M2GF.js +14 -0
  43. package/chunks/{computer-use-WKDNUTLD.js → computer-use-J4GAM4M6.js} +1 -1
  44. package/chunks/contextCommand-5F5M7NA4.js +3 -0
  45. package/chunks/{cron-create-F2LXM2OA.js → cron-create-IDWSZENI.js} +1 -1
  46. package/chunks/{cron-delete-DE6Q2S2L.js → cron-delete-NQCDZDUI.js} +1 -1
  47. package/chunks/{cron-list-IAQEJVV7.js → cron-list-Z4XMC3TO.js} +1 -1
  48. package/chunks/{de-AQXFJYZI.js → de-34YZHGC6.js} +2 -2
  49. package/chunks/{devtools-5JRKK3E7.js → devtools-XRQ4YJ5S.js} +1 -1
  50. package/chunks/{dist-P6SLWL5V.js → dist-PH6JW7XD.js} +1 -1
  51. package/chunks/{edit-QQNJZ55P.js → edit-X2S2ZXRN.js} +1 -1
  52. package/chunks/{en-EJLDYIBM.js → en-QLGMD6OS.js} +3 -3
  53. package/chunks/{enter-worktree-5X5SAMBJ.js → enter-worktree-TUCGNCLO.js} +1 -1
  54. package/chunks/{enterPlanMode-HP35SPLN.js → enterPlanMode-SQEZAAIR.js} +1 -1
  55. package/chunks/{exit-worktree-SRKZBEYF.js → exit-worktree-7FLITFZI.js} +1 -1
  56. package/chunks/{exitPlanMode-WSPTGGVN.js → exitPlanMode-O5UUJ3GM.js} +1 -1
  57. package/chunks/{fr-6TDHK7F2.js → fr-EDNBQACJ.js} +3 -3
  58. package/chunks/geminiContentGenerator-FIZFLPU3.js +8 -0
  59. package/chunks/glob-GSFTYAS2.js +22 -0
  60. package/chunks/{goal-tools-C6BSBHCF.js → goal-tools-YQOA6OKU.js} +1 -1
  61. package/chunks/{grep-MVCOBUYW.js → grep-VAB2VSXM.js} +1 -1
  62. package/chunks/{ja-GGNJR7AR.js → ja-LV4RLM3M.js} +2 -2
  63. package/chunks/{ls-JYJXFSXN.js → ls-IZJ3CKZY.js} +1 -1
  64. package/chunks/{lsp-DYDK6XCS.js → lsp-NGLDRHZU.js} +1 -1
  65. package/chunks/matildaAgentContentGenerator-QQHPCFJ5.js +8 -0
  66. package/chunks/matildaContentGenerator-W7Z33ONU.js +8 -0
  67. package/chunks/mcp-client-DXUNIEIB.js +3 -0
  68. package/chunks/monitor-4PFIGAGG.js +32 -0
  69. package/chunks/notebook-edit-MWJYAATJ.js +17 -0
  70. package/chunks/{openaiContentGenerator-2EALAM3U.js → openaiContentGenerator-NDVJL6QL.js} +1 -1
  71. package/chunks/{pt-D6L2QTDM.js → pt-5SQ4DGL7.js} +2 -2
  72. package/chunks/read-file-WPZKPXWA.js +3 -0
  73. package/chunks/ripGrep-7LZDZFTX.js +3 -0
  74. package/chunks/{ru-BNJCHDYO.js → ru-7K24S53N.js} +2 -2
  75. package/chunks/scheduler-DK2MVKXX.js +8 -0
  76. package/chunks/{send-message-P3SMWNEE.js → send-message-TCPX5UDU.js} +1 -1
  77. package/chunks/{serve-FXH6EBQ6.js → serve-GSZPJI2O.js} +59 -48
  78. package/chunks/shell-PRS47PDP.js +3 -0
  79. package/chunks/{skill-HZPFEAPF.js → skill-ETQM5NI3.js} +1 -1
  80. package/chunks/src-UB7DZRYK.js +3 -0
  81. package/chunks/{symbol-search-EAIZPWN7.js → symbol-search-HARHZ5AH.js} +1 -1
  82. package/chunks/{syntheticOutput-432LXITX.js → syntheticOutput-WZDPECYS.js} +1 -1
  83. package/chunks/task-create-XRNIDT4T.js +3 -0
  84. package/chunks/{task-detach-XMSJ3HBM.js → task-detach-TBAVUOTC.js} +1 -1
  85. package/chunks/task-list-Z6BDZZID.js +9 -0
  86. package/chunks/{task-stop-NTS62FLG.js → task-stop-HDSARSJ6.js} +1 -1
  87. package/chunks/{task-update-AR26UFYZ.js → task-update-MW2VT2XV.js} +1 -1
  88. package/chunks/{team-create-PYXFVIR5.js → team-create-VMYNLZCC.js} +1 -1
  89. package/chunks/team-delete-F7QDC2TE.js +8 -0
  90. package/chunks/{todoWrite-5NZ7CHTC.js → todoWrite-SCF5M24M.js} +1 -1
  91. package/chunks/{tool-search-RKZDSRYS.js → tool-search-WX6FOE35.js} +1 -1
  92. package/chunks/{web-fetch-VW3SVDQ6.js → web-fetch-CKYBHGLF.js} +1 -1
  93. package/chunks/{web-search-XQUIZARL.js → web-search-67DFNS5V.js} +1 -1
  94. package/chunks/{workflow-YXNXDRWZ.js → workflow-WBSRQG3N.js} +2 -2
  95. package/chunks/write-file-S5FAX4JJ.js +15 -0
  96. package/cli.js +436 -439
  97. package/locales/ca.js +0 -3
  98. package/locales/de.js +0 -3
  99. package/locales/en.js +0 -3
  100. package/locales/fr.js +0 -3
  101. package/locales/ja.js +0 -3
  102. package/locales/pt.js +0 -3
  103. package/locales/ru.js +0 -3
  104. package/package.json +2 -2
  105. package/sandbox-macos-permissive-closed.sb +0 -1
  106. package/sandbox-macos-permissive-open.sb +0 -1
  107. package/sandbox-macos-permissive-proxied.sb +0 -1
  108. package/sandbox-macos-restrictive-closed.sb +0 -1
  109. package/sandbox-macos-restrictive-open.sb +0 -1
  110. package/sandbox-macos-restrictive-proxied.sb +0 -1
  111. package/bundled/mainy/docs/features/channels/dingtalk.md +0 -134
  112. package/bundled/mainy/docs/features/channels/feishu.md +0 -186
  113. package/bundled/mainy/docs/features/channels/weixin.md +0 -106
  114. package/chunks/agent-WM63A6NK.js +0 -3
  115. package/chunks/agent-headless-QIUBDKPW.js +0 -3
  116. package/chunks/chunk-2MOGYHWM.js +0 -8
  117. package/chunks/chunk-3IRGBRSP.js +0 -113
  118. package/chunks/chunk-6GBNB5Z2.js +0 -3
  119. package/chunks/chunk-6Z2MV7ZY.js +0 -186
  120. package/chunks/chunk-BVOCFLC4.js +0 -56
  121. package/chunks/chunk-FPO57O66.js +0 -39
  122. package/chunks/chunk-LJR4RZZ2.js +0 -3
  123. package/chunks/chunk-MO2HXJG5.js +0 -9
  124. package/chunks/chunk-PA6532AY.js +0 -6
  125. package/chunks/chunk-S3CWEVTS.js +0 -15
  126. package/chunks/chunk-U347OO7S.js +0 -9
  127. package/chunks/chunk-UIRBHC5X.js +0 -3
  128. package/chunks/chunk-WVY2P6WH.js +0 -26
  129. package/chunks/chunk-WZ75OGYY.js +0 -14
  130. package/chunks/chunk-XMZIY7XX.js +0 -13
  131. package/chunks/contextCommand-DAB3HOHY.js +0 -3
  132. package/chunks/dist-ME6647DQ.js +0 -195
  133. package/chunks/dist-VG3ZDJ2A.js +0 -28
  134. package/chunks/dist-YTCHM57U.js +0 -23
  135. package/chunks/geminiContentGenerator-RJ73DQAP.js +0 -8
  136. package/chunks/glob-QQ6LGKDX.js +0 -22
  137. package/chunks/matildaAgentContentGenerator-YUYS4336.js +0 -8
  138. package/chunks/matildaContentGenerator-O4Z2QPCP.js +0 -8
  139. package/chunks/mcp-client-RXVQU5VI.js +0 -3
  140. package/chunks/monitor-77KXDXPR.js +0 -32
  141. package/chunks/notebook-edit-TKJD2EQZ.js +0 -17
  142. package/chunks/read-file-3KUAH6ND.js +0 -3
  143. package/chunks/ripGrep-U2PLKXMY.js +0 -3
  144. package/chunks/scheduler-J7VU2V5Y.js +0 -8
  145. package/chunks/shell-PXR2AXDD.js +0 -3
  146. package/chunks/src-RFAEPLY7.js +0 -3
  147. package/chunks/task-create-Z3QRCMX4.js +0 -3
  148. package/chunks/task-list-GXAJW3JP.js +0 -9
  149. package/chunks/team-delete-OMYVUAQU.js +0 -8
  150. package/chunks/write-file-XDDLTGSG.js +0 -15
@@ -0,0 +1,113 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{a as un,b as St,c as cn,d as pn}from"./chunk-DC7LAFZZ.js";import{a as q,d as ln}from"./chunk-4F4DA5UI.js";import{b as nn}from"./chunk-3YLXGE6T.js";import{b as on,d as rn,g as Et,j as sn,k as an,s as dn,v as pe}from"./chunk-JCE3JAVC.js";import{b as A,e as V}from"./chunk-SVSY6AWS.js";import{a as Jt,d as Xt}from"./chunk-SDTWBD62.js";import{$a as we,Eb as ce,Pb as mt,Pc as Tt,Qa as No,Qc as yt,Sa as Uo,Sb as ht,Sc as At,Ta as Q,Ub as Ct,Za as ke,_a as Ie,a as M,db as gt,f as F,hb as Oe,ib as B,oa as ft,wb as Pe,xb as De}from"./chunk-DHDD5YJC.js";import{Q as ve,U as tn,W as pt,ba as O,c as Qt,d as Zt,e as U,f as de,k as dt}from"./chunk-27Q5KW3A.js";import{b as ut,c as b,f as ct,g as ue,h as _,i as xe,k as en,l as k,n as X}from"./chunk-FWDMPRKU.js";import{b as f}from"./chunk-GZPNIYVZ.js";import{f as Lo}from"./chunk-OWGSC52X.js";f();function Z(e){return!Number.isFinite(e)||e<=0?0:Math.ceil(e/4)}function Le(e){let t=e.candidates||0,n=e.thoughts||0;return n>t?t+n:Math.max(t,n)}function Fo(e){return e.total&&e.total>0?Math.max(e.total,(e.prompt||0)+Le(e)):(e.prompt||0)+Le(e)}function Go(e){let t=Math.max(0,e.thoughtsTokens||0),n=Le({candidates:e.outputTokens||0,thoughts:t}),o=Math.max(e.totalTokens||0,(e.inputTokens||0)+n);return{...e,outputTokens:n,thoughtsTokens:t,totalTokens:o}}f();f();var Ko=/[A-Za-z\u00C0-\u024F]/g;function $o(e){return e>=1024&&e<=1279||e>=1280&&e<=1327||e>=11744&&e<=11775||e>=42560&&e<=42655||e>=12352&&e<=12543||e>=13312&&e<=19903||e>=19968&&e<=40959||e>=63744&&e<=64255||e>=44032&&e<=55215}function Mt(e){let t=e.codePointAt(0);return t!==void 0&&$o(t)}function Ho(e){let t=e.match(Ko)?.length??0;if(t<24)return!1;let n=0;for(let o of e)Mt(o)&&n++;return n===0||t>=n*8}function Ne(e){if(!e||!Ho(e))return e;let t="",n=0,o=[...e];for(;n<o.length;){if(!Mt(o[n])){t+=o[n],n++;continue}let r=n;for(;r>0&&o[r-1]===" ";)r--;let i=n+1;for(;i<o.length&&Mt(o[i]);)i++;for(;i<o.length&&o[i]===" ";)i++;let s=r>0?o[r-1]:"",a=i<o.length?o[i]:"";(/[A-Za-z0-9]/.test(s)&&/[A-Za-z0-9]/.test(a)||o[r]===" "||o[i-1]===" ")&&(t+=" "),n=i,r<n&&o[r]===" "&&t.endsWith(" ")&&(t=t.slice(0,-1))}return t.replace(/ {2,}/g," ")}f();var ee=O("TAGGED_THINKING_PARSER"),ge=["<think>","<thinking>"],me=["</think>","</thinking>"],jo=Math.max(...ge.map(e=>e.length),...me.map(e=>e.length));function fe(e,t,n){t&&e.push(n==="thought"?{text:t,thought:!0}:{text:t})}function Ue(e,t,n){let o=e.length-t;return o<=0||o>jo?!1:n.some(r=>r.startsWith(e.slice(t,t+o)))}function Fe(e,t,n){return n.find(o=>e.startsWith(o,t))}function Rt(e){if(!e)return e;let t=e;return t=t.replace(/<\/?think(?:ing)?>/gi,""),t=t.replace(/[A-Za-z]*long[_-]?message[_-]?THINKING/gi,""),t=t.replace(/\bM?long[_-]?message\b/gi,""),t=t.replace(/(^|[\s>])THINKING(?=[\sA-Z<]|$)/g,"$1"),t!==e&&(t=t.replace(/[ \t]{2,}/g," ")),t}function fn(e){let t=[];for(let n of e){if(n.thought===!0||typeof n.text!="string"){t.push(n);continue}let o=Ne(Rt(n.text));(o.length>0||/^\s+$/.test(n.text))&&t.push({text:o.length>0?o:n.text})}return t}var _t=class{mode="text";buffer="";parse(t,n=!1){this.buffer+=t;let o=this.buffer.toLowerCase(),r=[],i="",s=0;for(;s<this.buffer.length;){if(this.mode==="text"){let a=Fe(o,s,ge);if(a){ee.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),fe(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=Fe(o,s,me);if(l){ee.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),fe(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(Ue(o,s,ge)||Ue(o,s,me)))break}else{let a=Fe(o,s,me);if(a){ee.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),fe(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=Fe(o,s,ge);if(l){s+=l.length;continue}if(!n&&(Ue(o,s,me)||Ue(o,s,ge)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(fe(r,i,this.mode),this.buffer=this.buffer.slice(s),ee.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),fn(r)):(this.buffer="",this.mode==="thought"&&i&&ee.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),fe(r,i,this.mode),ee.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),fn(r))}};function gn(e){return new _t().parse(e,!0)}var D=O("CONVERTER"),En="(attached media from previous tool call)";function Sn(e,t={}){let n=e.prompt_tokens||0,o=e.completion_tokens||0,r=e.total_tokens||0,i=e.prompt_tokens_details,s=i?.cached_tokens??i?.cachedTokens??e.cached_tokens??e.prompt_cache_hit_tokens??e.cache_read_input_tokens??0,a=e.completion_tokens_details,l=a?.reasoning_tokens??a?.reasoningTokens??e.reasoning_tokens??0,c=Math.max(0,t.estimatedReasoningTokens??0),d=Math.max(0,t.estimatedContentTokens??0),p=l>0?l:c,u=o;p>0&&(o>=p?u=o:u=o+p),(d>0||c>0)&&(u=Math.max(u,d+(l>0?0:c),d+p)),r>n&&(n>0||o>0||p>0)&&(u=Math.max(u,r-n)),p===0&&c>0&&(p=c),p>u&&(p=u);let h=e.usage_is_incomplete===!0||o>0&&n===0||r>0&&n===0&&o===0,m=n,g=r;return(g===0&&(m>0||u>0)||g>0&&m>0&&g<m+u)&&(g=m+u),{promptTokenCount:m,candidatesTokenCount:u,totalTokenCount:g,cachedContentTokenCount:s,thoughtsTokenCount:p,...h?{usageIsIncomplete:!0}:{}}}var Vo=64,mn=1024;function hn(e,t){if(e.length===0)return"";if(t.emittedText.length===0)return t.emittedText=e,t.emittedLength=e.length,e;if(t.cumulativeMode){if(e.startsWith(t.emittedText)){let n=e.slice(t.emittedText.length);return t.emittedText=e,t.emittedLength=e.length,n}return t.emittedText.startsWith(e)?(D.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${t.emittedText.length}b, chunk=${e.length}b)`),""):(D.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),t.cumulativeMode=!1,t.emittedText=e,t.emittedLength+=e.length,e)}if(e.length>t.emittedText.length&&e.startsWith(t.emittedText)){let n=t.emittedText.length,r=n>=mn&&t.emittedLength>n?t.emittedLength:n;if(e.length>r){let i=e.slice(r);return t.emittedText=e,t.emittedLength=e.length,t.cumulativeMode=!0,D.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${e.length}b)`),i}}return e===t.emittedText?e.length>=Vo?(t.cumulativeMode=!0,D.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${e.length}b)`),""):(t.emittedLength+=e.length,e):(t.emittedText.length<mn&&(t.emittedText+=e),t.emittedLength+=e.length,e)}function Mn(e){if(!e||typeof e!="object")return e;let t=JSON.parse(JSON.stringify(e)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let r={};for(let[i,s]of Object.entries(o))if(i==="type"&&typeof s=="string"){let a=s.toLowerCase();a==="integer"?r[i]="integer":a==="number"?r[i]="number":r[i]=a}else i==="minimum"||i==="maximum"||i==="multipleOf"?typeof s=="string"&&!isNaN(Number(s))?r[i]=Number(s):r[i]=s:i==="minLength"||i==="maxLength"||i==="minItems"||i==="maxItems"?typeof s=="string"&&!isNaN(Number(s))?r[i]=parseInt(s,10):r[i]=s:typeof s=="object"?r[i]=n(s):r[i]=s;return r};return n(t)}async function Bo(e,t="auto"){let n=[];for(let o of e){let r;if("tool"in o?r=await o.tool():r=o,r.functionDeclarations){for(let i of r.functionDeclarations)if(i.name&&i.description){let s;i.parametersJsonSchema?s={...i.parametersJsonSchema}:i.parameters&&(s=Mn(i.parameters)),s&&(s=rn(s,t)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function qo(e,t,n={cleanOrphanToolCalls:!0}){let o=[];return Wo(e,o),Yo(e.contents,o,t),o=An(o),n.cleanOrphanToolCalls&&(o=ir(o),o=An(o)),o}function zo(e,t){let n=e.candidates?.[0],o=n?.content?.parts||[],r=[],i=[],s=[],a=0;for(let g of o)typeof g=="string"?i.push(g):"text"in g&&g.text?"thought"in g&&g.thought?r.push(g.text):i.push(g.text):"functionCall"in g&&g.functionCall&&(s.push({id:g.functionCall.id||`call_${a}`,type:"function",function:{name:g.functionCall.name||"",arguments:JSON.stringify(g.functionCall.args||{})}}),a+=1);let l={role:"assistant",content:i.join("")||null,refusal:null},c=r.join("");c&&(l.reasoning_content=c),s.length>0&&(l.tool_calls=s);let d=rr(n?.finishReason),p=e.usageMetadata,u={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(u.prompt_tokens_details={cached_tokens:p.cachedContentTokenCount});let h=e.createTime?Number(e.createTime):Date.now(),m=Number.isFinite(h)?Math.floor(h/1e3):Math.floor(Date.now()/1e3);return{id:e.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:m,model:e.modelVersion||t.model,choices:[{index:0,message:l,finish_reason:d,logprobs:null}],usage:u}}function Wo(e,t){if(!e.config?.systemInstruction)return;let n=Rn(e.config.systemInstruction);n&&t.push({role:"system",content:n})}function Yo(e,t,n){if(Array.isArray(e))for(let o of e)Cn(o,t,n);else e&&Cn(e,t,n)}function Cn(e,t,n){if(typeof e=="string"){t.push({role:"user",content:e});return}if(!Zo(e))return;let o=e.parts||[],r=e.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,c=new Set,d=new Set,p=[];for(let u of o){if(typeof u=="string"){i.push({type:"text",text:u});continue}"text"in u&&"thought"in u&&u.thought&&r==="assistant"&&u.text&&s.push(u.text),"text"in u&&u.text&&!("thought"in u&&u.thought)&&i.push({type:"text",text:u.text});let h=_n(u,n);if(h&&r==="user"&&i.push(h),"functionCall"in u&&u.functionCall&&r==="assistant"){let m=u.functionCall.id;if(m){if(c.has(m)){D.debug(`Dropping duplicate functionCall id=${m} while converting content`);continue}c.add(m)}a.push({id:m||`call_${l}`,type:"function",function:{name:u.functionCall.name||"",arguments:JSON.stringify(u.functionCall.args||{})}}),l+=1}if(u.functionResponse&&r==="user"){let m=u.functionResponse.id;if(m){if(d.has(m))continue;d.add(m)}let g=Xo(u.functionResponse,n);if(g){if(n.splitToolMedia&&Array.isArray(g.content)){let C=[],T=[];for(let y of g.content)y&&(y.type==="image_url"||y.type==="input_audio"||y.type==="video_url"||y.type==="file")?C.push(y):y&&y.type==="text"&&T.push(y);if(C.length>0){let y=T.map(E=>E.text).join(`
4
+ `);g.content=y||"[media attached in following user message]",p.push(...C)}}t.push(g)}}}if(p.length>0&&t.push({role:"user",content:[{type:"text",text:En},...p]}),r==="assistant"){if(i.length===0&&a.length===0&&s.length===0)return;let h={role:"assistant",content:i.filter(g=>g.type==="text").map(g=>g.text).join("")||(s.length>0?"":null)};a.length>0&&(h.tool_calls=a);let m=s.join("");m&&(h.reasoning_content=m),t.push(h);return}i.length>0&&t.push({role:"user",content:i})}function Jo(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e,n=t.output;if(typeof n=="string")return n;let o=t.error;if(typeof o=="string")return o}try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Xo(e,t){let n=Jo(e.response),o=[];n&&o.push({type:"text",text:n});for(let r of e.parts||[]){if("text"in r&&typeof r.text=="string"){r.text.length>0&&o.push({type:"text",text:r.text});continue}let i=_n(r,t);i&&o.push(i)}return o.length===0?{role:"tool",tool_call_id:e.id||"",content:""}:{role:"tool",tool_call_id:e.id||"",content:o}}function _n(e,t){let{modalities:n}=t;if(e.inlineData?.mimeType&&e.inlineData?.data){let o=e.inlineData.mimeType,r=Tn(o),i=e.inlineData.displayName||o;if(r==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${e.inlineData.data}`}}:z("image",i,t);if(o==="application/pdf")return n.pdf?{type:"file",file:{filename:e.inlineData.displayName||"document.pdf",file_data:`data:${o};base64,${e.inlineData.data}`}}:z("pdf",i,t);if(r==="audio"){if(!n.audio)return z("audio",i,t);let s=Qo(o);if(s)return{type:"input_audio",input_audio:{data:`data:${o};base64,${e.inlineData.data}`,format:s}}}return r==="video"?n.video?{type:"video_url",video_url:{url:`data:${o};base64,${e.inlineData.data}`}}:z("video",i,t):{type:"text",text:`Unsupported inline media type: ${o} (${i}).`}}if(e.fileData?.mimeType&&e.fileData?.fileUri){let o=e.fileData.displayName||"file",r=e.fileData.fileUri,i=e.fileData.mimeType,s=Tn(i);if(s==="image")return n.image?{type:"image_url",image_url:{url:r}}:z("image",o,t);if(i==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:r}}:z("pdf",o,t);if(s==="video")return n.video?{type:"video_url",video_url:{url:r}}:z("video",o,t);let a=e.fileData.displayName?` (${e.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${i}${a}.`}}return null}function z(e,t,n){D.warn(`Model '${n.model}' does not support ${e} input. Replacing with text placeholder: ${t}`);let o;return e==="pdf"?o=`This model does not support PDF input directly. The read_file tool cannot extract PDF content either. To extract text from the PDF file, try using skills if applicable, or guide user to install pdf skill by running this slash command:
5
+ /extensions install https://github.com/anthropics/skills:document-skills`:o=`This model does not support ${e} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`,{type:"text",text:`[Unsupported ${e} file: "${t}". ${o}]`}}function Tn(e){return e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":e.startsWith("video/")?"video":"file"}function Qo(e){return e.includes("wav")?"wav":e.includes("mp3")||e.includes("mpeg")?"mp3":null}function Zo(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&Array.isArray(e.parts)}function Rn(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>Rn(t)).filter(Boolean).join(`
6
+ `):typeof e=="object"&&e!==null&&"parts"in e&&e.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
7
+ `)||""}function Ge(e,t,n=!0){if(t.taggedThinkingParser)return t.taggedThinkingParser.parse(e,n);if(t.responseParsingOptions?.taggedThinkingTags)return gn(e);if(!e)return[];let o=Ne(Rt(e));return o?[{text:o}]:[]}function er(e,t){let n=e.choices?.[0],o=new V;if(n){let r=[];if(!t.responseParsingOptions?.taggedThinkingTags){let i=n.message.reasoning_content??n.message.reasoning;i&&r.push({text:i,thought:!0})}if(n.message.content&&r.push(...Ge(n.message.content,t)),n.message.tool_calls){for(let i of n.message.tool_calls)if(i.function){let s=on(i.function.arguments);if(s===null)continue;r.push({functionCall:{id:i.id,name:i.function.name,args:s}})}}o.candidates=[{content:{parts:r,role:"model"},finishReason:bn(n.finish_reason),index:0,safetyRatings:[]}]}else o.candidates=[];if(o.responseId=e.id,o.createTime=e.created?e.created.toString():new Date().getTime().toString(),o.modelVersion=t.model,o.promptFeedback={safetyRatings:[]},e.usage){let r=e.choices?.[0]?.message,i=r?.reasoning_content??r?.reasoning??"",s=typeof r?.content=="string"?r.content:"";o.usageMetadata=Sn(e.usage,{estimatedReasoningTokens:Z(i.length),estimatedContentTokens:Z(s.length)})}return o}function tr(e,t){let n=e.choices?.[0],o=new V,r=t.toolCallParser;if(!r)throw new Error("convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start.");if(n){let i=[];if(!t.responseParsingOptions?.taggedThinkingTags){let c=n.delta?.reasoning_content??n.delta?.reasoning;if(c){let d=hn(c,t.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});d&&i.push({text:d,thought:!0})}}if(typeof n.delta?.content=="string"){let c=hn(n.delta.content,t.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(c||n.finish_reason)&&i.push(...Ge(c,t,!!n.finish_reason))}else n.finish_reason&&i.push(...Ge("",t,!0));if(n.delta?.tool_calls)for(let c of n.delta.tool_calls){let d=c.index??0;c.function?.arguments?r.addChunk(d,c.function.arguments,c.id,c.function.name):r.addChunk(d,"",c.id,c.function?.name)}let s=!1;if(n.finish_reason){s=r.hasIncompleteToolCalls();let c=r.getCompletedToolCalls();for(let d of c)d.name&&i.push({functionCall:{id:d.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:d.name,args:d.args}})}let a=s&&n.finish_reason!=="length"?"length":n.finish_reason,l={content:{parts:i,role:"model"},index:0,safetyRatings:[]};a&&(l.finishReason=bn(a)),o.candidates=[l]}else o.candidates=[];return o.responseId=e.id,o.createTime=e.created?e.created.toString():new Date().getTime().toString(),o.modelVersion=t.model,o.promptFeedback={safetyRatings:[]},e.usage&&(o.usageMetadata=Sn(e.usage,or(t))),o}function nr(e){let t=e.toolCallParser;if(!t)return null;let n=[],o=t.getStrictCompletedToolCalls(),r=t.hasIncompleteToolCalls();for(let s of o)s.name&&n.push({functionCall:{id:s.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:s.name,args:s.args}});if(n.push(...Ge("",e,!0)),n.length===0&&!r)return null;let i=new V;return i.candidates=[{content:{parts:n,role:"model"},index:0,safetyRatings:[],finishReason:r?A.MAX_TOKENS:A.STOP}],i.responseId=`stream-flush-${Date.now()}`,i.createTime=new Date().getTime().toString(),i.modelVersion=e.model,i.promptFeedback={safetyRatings:[]},i}function or(e){return{estimatedReasoningTokens:Z(e.reasoningDeltaState?.emittedLength??0),estimatedContentTokens:Z(e.textDeltaState?.emittedLength??0)}}function bn(e){return e?{stop:A.STOP,length:A.MAX_TOKENS,content_filter:A.SAFETY,function_call:A.STOP,tool_calls:A.STOP}[e]||A.FINISH_REASON_UNSPECIFIED:A.FINISH_REASON_UNSPECIFIED}function rr(e){if(!e)return"stop";switch(e){case A.STOP:return"stop";case A.MAX_TOKENS:return"length";case A.SAFETY:case A.RECITATION:case A.BLOCKLIST:case A.PROHIBITED_CONTENT:case A.SPII:case A.IMAGE_SAFETY:case A.IMAGE_RECITATION:case A.IMAGE_PROHIBITED_CONTENT:case A.IMAGE_OTHER:return"content_filter";case A.NO_IMAGE:return"stop";default:return"stop"}}function bt(e){return e.role==="assistant"&&"tool_calls"in e&&Array.isArray(e.tool_calls)&&e.tool_calls.length>0}function yn(e){if(e.role!=="user"||!("content"in e)||!Array.isArray(e.content))return!1;let t=e.content[0];return t?.type==="text"&&t.text===En}function ir(e){let t=[],n=new Map,o=new Map,r=new Map,i=new Set,s=new Set;for(let a=0;a<e.length;a+=1){let l=e[a];if(bt(l)){let c=[],d=new Set;for(let C of l.tool_calls){let T=C.id;!T||s.has(T)||d.has(T)||(d.add(T),c.push(C))}let p=new Set,u=[],h=[],m=!1;for(let C=a+1;C<e.length;C+=1){let T=e[C];if(T.role==="tool"&&"tool_call_id"in T){if(!T.tool_call_id){m=!1;continue}d.has(T.tool_call_id)&&!p.has(T.tool_call_id)?(p.add(T.tool_call_id),u.push(C),m=!0):m=!1;continue}if(yn(T)){m&&h.push(C);continue}if(!(T.role==="assistant"&&!bt(T)))break}let g=c.filter(C=>p.has(C.id));for(let C of g)s.add(C.id);n.set(a,g),o.set(a,u),r.set(a,h)}}for(let a=0;a<e.length;a+=1){if(i.has(a))continue;let l=e[a];if(bt(l)){let c=l.reasoning_content,d=n.get(a)??[];if(d.length>0){let p={...l};p.tool_calls=d,t.push(p);for(let u of o.get(a)??[]){let h=e[u];h&&(t.push(h),i.add(u))}for(let u of r.get(a)??[]){let h=e[u];h&&(t.push(h),i.add(u))}}else if(typeof l.content=="string"&&l.content.trim()||c){let p={...l};delete p.tool_calls,t.push(p)}else D.debug(`cleanOrphanedToolCalls: dropping assistant with ${l.tool_calls.length} orphaned tool call(s) and no text/reasoning content`)}else l.role==="tool"&&"tool_call_id"in l?D.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):yn(l)?D.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):t.push(l)}return t}function An(e){let t=[];for(let n of e){if(n.role==="assistant"&&t.length>0){let o=t[t.length-1];if(o.role==="assistant"){let r="tool_calls"in o?o.tool_calls||[]:[],i="tool_calls"in n?n.tool_calls||[]:[],s=o.content,a=n.content,l=Array.isArray(s)||Array.isArray(a),c;if(l){let p=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[],u=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[];c=[...p,...u]}else c=[typeof s=="string"?s:"",typeof a=="string"?a:""].filter(Boolean).join("")||null;let d=[...r,...i];o.content=c||null,d.length>0&&(o.tool_calls=d);continue}}t.push(n)}return t}var Ke={convertGeminiToolParametersToOpenAI:Mn,convertGeminiToolsToOpenAI:Bo,convertGeminiRequestToOpenAI:qo,convertGeminiResponseToOpenAI:zo,convertOpenAIResponseToGemini:er,convertOpenAIChunkToGemini:tr,flushOpenAIStreamToGemini:nr};f();import*as w from"node:path";import{promises as je}from"node:fs";f();f();import sr from"crypto";var He=new Uint8Array(256),$e=He.length;function vt(){return $e>He.length-16&&(sr.randomFillSync(He),$e=0),He.slice($e,$e+=16)}f();var S=[];for(let e=0;e<256;++e)S.push((e+256).toString(16).slice(1));function vn(e,t=0){return S[e[t+0]]+S[e[t+1]]+S[e[t+2]]+S[e[t+3]]+"-"+S[e[t+4]]+S[e[t+5]]+"-"+S[e[t+6]]+S[e[t+7]]+"-"+S[e[t+8]]+S[e[t+9]]+"-"+S[e[t+10]]+S[e[t+11]]+S[e[t+12]]+S[e[t+13]]+S[e[t+14]]+S[e[t+15]]}f();f();import ar from"crypto";var xt={randomUUID:ar.randomUUID};function lr(e,t,n){if(xt.randomUUID&&!t&&!e)return xt.randomUUID();e=e||{};let o=e.random||(e.rng||vt)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,t){n=n||0;for(let r=0;r<16;++r)t[n+r]=o[r];return t}return vn(o)}var kt=lr;import*as G from"os";var Ve=O("OPENAI_LOGGER"),dr="########",ur=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function cr(e,t){let n=t||process.cwd();if(!e)return w.join(n,"logs","openai");let o=e;return e==="~"||e.startsWith("~/")?o=w.join(G.homedir(),e.slice(1)):w.isAbsolute(e)||(o=w.resolve(n,e)),w.normalize(o)}function xn(e){return e&&e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function pr(e){let t=e.split("#");if(t.length!==3)return;let[,n,o]=t;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function fr(e){if(e)return Q(e)?xn(e):xn(pr(e))}function gr(e){if(!e)return;let t=e.indexOf(dr);if(t>0)return e.slice(0,t);if(ur.test(e))return e;let n=e.split("#");if(n.length>=3&&n[0])return n[0]}function mr(e){let t=e?.trim(),n=gr(t);return!t&&!n?null:{...t?{promptId:t}:{},...n?{sessionId:n}:{}}}var he=class{logDir;initialized=!1;constructor(t,n){this.logDir=cr(t,n)}async initialize(){if(!this.initialized)try{await je.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(t){throw Ve.error("Failed to initialize OpenAI logger:",t),new Error(`Failed to initialize OpenAI logger: ${t}`)}}async logInteraction(t,n,o,r){this.initialized||await this.initialize();let i=new Date().toISOString().replace(/:/g,"-"),s=kt().slice(0,8),a=fr(r),l=a?`openai-${i}-${s}-${a}.json`:`openai-${i}-${s}.json`,c=w.join(this.logDir,l),d={timestamp:new Date().toISOString(),request:t,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:mr(r),system:{hostname:G.hostname(),platform:G.platform(),release:G.release(),nodeVersion:process.version}};try{return await je.writeFile(c,JSON.stringify(d,null,2),"utf-8"),c}catch(p){throw Ve.error("Failed to write OpenAI log file:",p),new Error(`Failed to write OpenAI log file: ${p}`)}}async getLogFiles(t){this.initialized||await this.initialize();try{let o=(await je.readdir(this.logDir)).filter(r=>r.startsWith("openai-")&&r.endsWith(".json")).map(r=>w.join(this.logDir,r)).sort().reverse();return t?o.slice(0,t):o}catch(n){return n.code==="ENOENT"?[]:(Ve.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(t){try{let n=await je.readFile(t,"utf-8");return JSON.parse(n)}catch(n){throw Ve.error(`Failed to read log file ${t}:`,n),new Error(`Failed to read log file: ${n}`)}}},va=new he;f();f();X();Uo();f();X();var kn=Lo(No(),1);import{createHash as hr}from"node:crypto";var te="matilda.telemetry.traceparent",Be="matilda.telemetry.tracestate",Cr="matilda-code.daemon.request",In="matilda-code.daemon.bridge",Tr="matilda-code.daemon.error";function yr(e){return e instanceof Error?e.message:String(e)}function Ar(e){return e instanceof Error?e.name||"Error":typeof e}var Er="0".repeat(32),Sr="0".repeat(16);function Mr(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e;if(!(te in t)&&!(Be in t))return{...t};let n={...t};return delete n[te],delete n[Be],n}function _r(e){return hr("sha256").update(e).digest("hex").slice(0,16)}async function It(e,t,n,o={}){if(!ce())return await n(void 0);let r=o.autoOkOnSuccess??!0;return await k.getTracer(M).startActiveSpan(e,{kind:ct.INTERNAL,attributes:t},async s=>{try{let a=await n(s);return r&&s.setStatus({code:ue.OK}),a}catch(a){throw On(s,a),a}finally{s.end()}})}async function Rr(e,t){return await It(Cr,{"http.request.method":e.method,"http.route":e.route,"matilda-code.daemon.operation":"http_request",...e.workspaceHash?{"matilda-code.workspace.hash":e.workspaceHash}:{},...e.sessionId?{"session.id":e.sessionId}:{},...e.clientId?{"matilda-code.client_id":e.clientId}:{},...e.permissionRequestId?{"matilda-code.daemon.permission.request_id":e.permissionRequestId}:{}},t,{autoOkOnSuccess:!1})}async function wn(e,t,n){return await It(In,{"matilda-code.daemon.operation":e,...t},async()=>await n())}function br(e,t){try{e?.setAttribute("http.response.status_code",t)}catch{}}function vr(e,t){try{k.getSpan(_.active())?.setAttribute(e,t)}catch{}}function On(e,t,n={}){let o=e??k.getSpan(_.active());if(o)try{let r=gt(yr(t));o.recordException(t instanceof Error?t:new Error(r)),o.setAttributes({"error.type":Ar(t),"error.message":r,...n}),o.setStatus({code:ue.ERROR,message:r})}catch{}}function xr(e,t={},n){if(ce())try{kn.logs.getLogger(M).emit({body:e,timestamp:new Date,attributes:{"event.name":n?.eventName??Tr,...t},...n?.severityNumber!=null?{severityNumber:n.severityNumber}:{}})}catch{}}function Pn(){return{context:_.active()}}async function Dn(e,t){let n=e&&typeof e=="object"&&"context"in e&&e.context?e.context:void 0;return n?await _.with(n,t):await t()}function Ln(e){let t=e._meta,n=Mr(t);try{let o=tn();o&&(n[te]=pt(o))}catch{}return!t&&!n[te]?e:{...e,_meta:n}}function kr(e){let t=e?._meta;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t,o=n[te];if(typeof o!="string"||o.length===0)return;let r={traceparent:o},i=n[Be];typeof i=="string"&&i.length>0&&(r.tracestate=i);let s=en.extract(ut,r);if(k.getSpanContext(s))return s;let a=o.split("-"),l=a[1],c=a[2],d=a[3];if(!(a[0]!=="00"||!l?.match(/^[0-9a-f]{32}$/)||!c?.match(/^[0-9a-f]{16}$/)||!d?.match(/^[0-9a-f]{2}$/)||l===Er||c===Sr))return k.setSpan(ut,k.wrapSpanContext({traceId:l,spanId:c,traceFlags:Number.parseInt(d,16),isRemote:!0}))}function Ir(){return{captureContext:Pn,runWithContext:Dn,withSpan:wn,event(e,t){if(ce())try{let n=k.getSpan(_.active());if(n){n.addEvent(e,t);return}let o=k.getTracer(M).startSpan(In,{kind:ct.INTERNAL,attributes:{"event.name":e,"matilda-code.daemon.operation":`event.${e}`,...t}});o.addEvent(e,t),o.setStatus({code:ue.OK}),o.end()}catch{}},injectPromptContext:Ln}}f();X();var wr=`${M}.daemon.http.request.count`,Or=`${M}.daemon.http.request.duration`,Pr=`${M}.daemon.session.active`,Dr=`${M}.daemon.session.lifecycle`,Lr=`${M}.daemon.channel.lifecycle`,Nr=`${M}.daemon.prompt.queue_wait`,Ur=`${M}.daemon.prompt.duration`,Fr=`${M}.daemon.bridge.error.count`,Gr=`${M}.daemon.cancel.count`,Kr=`${M}.daemon.sse.active`,$r=`${M}.daemon.process.heap_used`,Hr=new Set(["SessionNotFoundError","WorkspaceMismatchError","InvalidClientIdError","SessionLimitExceededError","RestoreInProgressError","InvalidSessionScopeError","TrustGateError","WorkspaceInitConflictError","WorkspaceInitPathEscapeError","WorkspaceInitSymlinkError","WorkspaceInitRaceError","McpServerNotFoundError","McpServerRestartFailedError","PromptDeadlineExceededError","InvalidSessionMetadataError","SubscriberLimitExceededError","BridgeChannelClosedError","BridgeTimeoutError","PermissionForbiddenError"]),L=!1,Un,Fn,Gn,Kn,$n,Hn,jn,Vn;function jr(e){let t=e instanceof Error?e.name:typeof e;return Hr.has(t)?t:"unknown"}function Vr(){if(L)return;let e=ft();e&&(Un=e.createCounter(wr,{description:"Daemon HTTP request count by route and status class.",valueType:b.INT}),Fn=e.createHistogram(Or,{description:"Daemon HTTP request duration in milliseconds.",unit:"ms",valueType:b.DOUBLE,advice:{explicitBucketBoundaries:[1,2,5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4]}}),Gn=e.createCounter(Dr,{description:"Daemon session lifecycle events (spawn, close, die).",valueType:b.INT}),Kn=e.createCounter(Lr,{description:"Daemon ACP channel lifecycle events (spawn, exit).",valueType:b.INT}),$n=e.createHistogram(Nr,{description:"Time a prompt waited in the per-session FIFO queue.",unit:"ms",valueType:b.DOUBLE,advice:{explicitBucketBoundaries:[1,5,10,50,100,500,1e3,5e3,1e4,3e4,6e4]}}),Hn=e.createHistogram(Ur,{description:"End-to-end prompt duration from dispatch to completion.",unit:"ms",valueType:b.DOUBLE,advice:{explicitBucketBoundaries:[100,500,1e3,2500,5e3,1e4,3e4,6e4,12e4,3e5,6e5]}}),jn=e.createCounter(Fr,{description:"Daemon bridge error count by normalized error type.",valueType:b.INT}),Vn=e.createCounter(Gr,{description:"Daemon cancel request count.",valueType:b.INT}),L=!0)}var Nn=!1;function Br(e){if(Nn)return;let t=ft();t&&(t.createObservableGauge(Pr,{description:"Current number of active daemon sessions.",valueType:b.INT}).addCallback(n=>{try{n.observe(e.sessionCount())}catch{}}),t.createObservableGauge(Kr,{description:"Current number of active SSE connections.",valueType:b.INT}).addCallback(n=>{try{n.observe(e.sseCount())}catch{}}),t.createObservableGauge($r,{description:"Daemon process heap memory usage in bytes.",unit:"bytes",valueType:b.INT}).addCallback(n=>{try{n.observe(e.heapUsed())}catch{}}),Nn=!0)}function qr(e,t,n){if(!L)return;let o=`${Math.floor(n/100)}xx`;Un?.add(1,{route:t,status_class:o}),Fn?.record(e,{route:t})}function zr(e){L&&Gn?.add(1,{action:e})}function Wr(e,t){L&&Kn?.add(1,{action:e,...t!=null?{expected:t}:{}})}function Yr(e){L&&$n?.record(e)}function Jr(e){L&&Hn?.record(e)}function Xr(e){L&&jn?.add(1,{error_type:jr(e)})}function Qr(){L&&Vn?.add(1)}f();X();import*as $ from"node:fs";import*as lt from"node:path";f();f();f();f();X();f();import{AsyncLocalStorage as Zr}from"node:async_hooks";var Bn=new Zr;f();function qn(e){let t=e.candidates?.[0]?.content?.parts;return!t||t.length===0?!1:t.some(ei)}function ei(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.text=="string"&&t.text.length>0||t.functionCall!==void 0||t.inlineData!==void 0||t.executableCode!==void 0||t.thought===!0}function zn(){let e=Jt.getStore();return{attempt:e?.attempt??1,requestSetupMs:e?.requestSetupMs,retryTotalDelayMs:e?.retryTotalDelayMs}}var W=O("LOGGING_CONTENT_GENERATOR"),ti=4096,Wn="...[truncated]",ni=ti-Wn.length,Ce=class{constructor(t,n,o){this.wrapped=t;this.config=n;this.modalities=o.modalities,this.splitToolMedia=o.splitToolMedia,this.generatorAuthType=o.authType,o.enableOpenAILogging&&(this.openaiLogger=new he(o.openAILoggingDir,n.getWorkingDir()),this.schemaCompliance=o.schemaCompliance)}openaiLogger;schemaCompliance;modalities;splitToolMedia;generatorAuthType;getWrapped(){return this.wrapped}logApiRequest(t,n,o){let r=JSON.stringify(t);mt(this.config,new Tt(n,o,r,F.getStore()))}_logApiResponse(t,n,o,r,i,s){Ct(this.config,new At(t,o,n,r,this.generatorAuthType,i,s,F.getStore()))}_logApiError(t,n,o,r,i){let s=Zt(o),a=de(o),l=o?.requestID||o?.request_id||t,c=U(o);ht(this.config,new yt({responseId:l,model:r,durationMs:n,promptId:i,authType:this.generatorAuthType,errorMessage:s,errorType:a,statusCode:c,subagentName:F.getStore()}))}safelyLogApiError(t,n,o,r,i){try{this._logApiError(t,n,o,r,i)}catch(s){W.warn("Failed to log API error:",s)}}safelyLogApiResponse(t,n,o,r,i,s){try{this._logApiResponse(t,n,o,r,i,s)}catch(a){W.warn("Failed to log API response:",a)}}getClientVisibleModelId(t,n){return("isManagedMatildaModel"in this.config&&typeof this.config.isManagedMatildaModel=="function"?this.config.isManagedMatildaModel(t):!1)&&"getPublicModelId"in this.config&&typeof this.config.getPublicModelId=="function"?this.config.getPublicModelId(t):n||t}async generateContent(t,n){let o=zn(),r=Oe(t.model,n);try{r.setAttribute("llm_request.stream",!1)}catch{}let i=k.setSpan(_.active(),r),s=Date.now(),a=Q(n),l=this.startCaptureSession();try{Et.recordGenerateContentRequest(t,{stream:!1,source:"generateContent"}),a||(ke(this.config,r,t.config?.systemInstruction),Ie(this.config,r,t.config?.tools));let c=await _.with(i,async()=>{a||this.logApiRequest(this.toContents(t.contents),t.model,n);let d=await l.wrap(()=>this.wrapped.generateContent(t,n)),p=Date.now()-s,u=a?void 0:this.extractResponseText(d);a||we(this.config,r,u),this.safelyLogApiResponse(d.responseId??"",p,this.getClientVisibleModelId(t.model,d.modelVersion),n,d.usageMetadata,u);try{await this.safelyLogOpenAIInteraction(await l.resolve(t),d,void 0,n)}catch(h){W.warn("Failed to log OpenAI interaction:",h)}return d});return B(r,{success:!0,inputTokens:c.usageMetadata?.promptTokenCount,outputTokens:c.usageMetadata?.candidatesTokenCount,cachedInputTokens:c.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-s,responseId:c.responseId||void 0,finishReason:c.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:c.usageMetadata?.thoughtsTokenCount,subagentName:F.getStore()||void 0,...o}),c}catch(c){let d=Date.now()-s,p=t.config?.abortSignal?.aborted??!1;throw B(r,{success:!1,durationMs:d,error:p?De:Pe,errorType:de(c),errorStatusCode:U(c),subagentName:F.getStore()||void 0,...o}),await _.with(i,async()=>{this.safelyLogApiError("",d,c,this.getClientVisibleModelId(t.model),n);try{await this.safelyLogOpenAIInteraction(await l.resolve(t),void 0,c,n)}catch(u){W.warn("Failed to log OpenAI interaction:",u)}}),c}}async generateContentStream(t,n){let o=zn(),r=Oe(t.model,n);try{r.setAttribute("llm_request.stream",!0)}catch{}let i=k.setSpan(_.active(),r),s=Date.now(),a=Q(n),l=this.startCaptureSession(),c;try{Et.recordGenerateContentRequest(t,{stream:!0,source:"generateContentStream"}),a||(ke(this.config,r,t.config?.systemInstruction),Ie(this.config,r,t.config?.tools)),c=await _.with(i,async()=>(a||this.logApiRequest(this.toContents(t.contents),t.model,n),l.wrap(()=>this.wrapped.generateContentStream(t,n))))}catch(p){let u=Date.now()-s;_.with(i,()=>this.safelyLogApiError("",u,p,t.model,n));let h=t.config?.abortSignal?.aborted??!1;B(r,{success:!1,durationMs:u,error:h?De:Pe,errorType:de(p),errorStatusCode:U(p),subagentName:F.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(t),void 0,p,n)}catch(m){W.warn("Failed to log OpenAI interaction:",m)}throw p}let d;if(this.openaiLogger)try{d=await l.resolve(t)}catch(p){W.warn("Failed to resolve OpenAI request:",p)}return _.with(i,()=>this.loggingStreamWrapper(c,s,n,t.model,d,r,i,t.config?.abortSignal,o))}startCaptureSession(){let t,n=!this.openaiLogger;return{wrap:o=>n?o():Bn.run(r=>{t=r},o),resolve:async o=>this.openaiLogger?t??await this.buildOpenAIRequestForLogging(o):void 0}}async*loggingStreamWrapper(t,n,o,r,i,s,a,l,c){let d=Q(o),p=!d||!!this.openaiLogger,u=[],h="",m="",g,C=!1,T,y=!1,E,R=F.getStore(),H,j=!1,N=x=>a?_.with(a,x):x(),Po=5*6e4,v,Do=s?()=>{j||(v!==void 0&&clearTimeout(v),v=setTimeout(()=>{try{s.setAttribute("stream.timed_out",!0)}catch{}B(s,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:h||void 0,subagentName:R||void 0,...c}),j=!0},Po),v.unref())}:void 0;try{for await(let I of t){!h&&I.responseId&&(h=I.responseId),!m&&I.modelVersion&&(m=I.modelVersion),p&&u.push(I),I.usageMetadata&&(g=I.usageMetadata);let Yt=I.candidates?.[0];Yt?.finishReason&&(T=Yt.finishReason),I.functionCalls?.length&&(y=!0),H===void 0&&qn(I)&&(H=Date.now()-n),Do?.(),yield I,v!==void 0&&(clearTimeout(v),v=void 0)}v!==void 0&&(clearTimeout(v),v=void 0);let x=Date.now()-n,ae=p?this.consolidateGeminiResponsesForLogging(u):void 0,Wt=d?void 0:this.extractResponseText(ae),le=!T&&!y?new Error("Model stream ended without a finish reason"):void 0;le&&(C=!0,E=le),j||(le?(N(()=>this.safelyLogApiError(h,x,le,this.getClientVisibleModelId(r,m),o)),await N(()=>this.safelyLogOpenAIInteraction(i,ae,le,o))):(N(()=>this.safelyLogApiResponse(h,x,this.getClientVisibleModelId(r,m),o,g,Wt)),!d&&s&&we(this.config,s,Wt),await N(()=>this.safelyLogOpenAIInteraction(i,ae,void 0,o))))}catch(x){if(C=!0,E=x,!j){let ae=Date.now()-n;N(()=>this.safelyLogApiError(h,ae,x,this.getClientVisibleModelId(r,m),o)),await N(()=>this.safelyLogOpenAIInteraction(i,void 0,x,o))}throw x}finally{if(v!==void 0&&clearTimeout(v),s&&!j){let x=l?.aborted??!1;B(s,{success:!C,inputTokens:g?.promptTokenCount,outputTokens:g?.candidatesTokenCount,cachedInputTokens:g?.cachedContentTokenCount,ttftMs:H,durationMs:Date.now()-n,error:C?x?De:Pe:void 0,responseId:h||void 0,finishReason:T,thoughtsTokenCount:g?.thoughtsTokenCount,subagentName:R||void 0,errorType:E?de(E):void 0,errorStatusCode:E?U(E):void 0,...c})}}}async buildOpenAIRequestForLogging(t){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(t.model),o=Ke.convertGeminiRequestToOpenAI(t,n,{cleanOrphanToolCalls:!1}),r={model:t.model,messages:o};return t.config?.tools&&(r.tools=await Ke.convertGeminiToolsToOpenAI(t.config.tools,this.schemaCompliance??"auto")),t.config?.temperature!==void 0&&(r.temperature=t.config.temperature),t.config?.topP!==void 0&&(r.top_p=t.config.topP),t.config?.maxOutputTokens!==void 0&&(r.max_tokens=t.config.maxOutputTokens),t.config?.presencePenalty!==void 0&&(r.presence_penalty=t.config.presencePenalty),t.config?.frequencyPenalty!==void 0&&(r.frequency_penalty=t.config.frequencyPenalty),r}createLoggingRequestContext(t){return{model:t,modalities:this.modalities??{},splitToolMedia:this.splitToolMedia??!0,startTime:0}}async logOpenAIInteraction(t,n,o,r){if(!this.openaiLogger||!t)return;let i=n?this.convertGeminiResponseToOpenAIForLogging(n,t):void 0;await this.openaiLogger.logInteraction(t,i,o instanceof Error?o:o?new Error(String(o)):void 0,r)}async safelyLogOpenAIInteraction(t,n,o,r){try{await this.logOpenAIInteraction(t,n,o,r)}catch(i){W.warn("Failed to log OpenAI interaction:",i)}}convertGeminiResponseToOpenAIForLogging(t,n){let o=new V;return Object.assign(o,t),o.modelVersion=this.getClientVisibleModelId(n.model,t.modelVersion),Ke.convertGeminiResponseToOpenAI(o,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(t){if(t.length===0)return;let n=new V,o=[],r=new Map,i,s;for(let c of t){c.usageMetadata&&(s=c.usageMetadata);let d=c.candidates?.[0];d?.finishReason&&(i=d.finishReason);let p=d?.content?.parts??[];for(let u of p){if(typeof u=="string"){o.push({text:u});continue}if("text"in u){u.text&&o.push({text:u.text,...u.thought?{thought:!0}:{},...u.thoughtSignature?{thoughtSignature:u.thoughtSignature}:{}});continue}if("functionCall"in u&&u.functionCall){let h=u.functionCall.id||u.functionCall.name||"tool_call",m=r.get(h),g={functionCall:u.functionCall};m!==void 0?o[m]=g:(r.set(h,o.length),o.push(g));continue}if("functionResponse"in u&&u.functionResponse){o.push({functionResponse:u.functionResponse});continue}o.push(u)}}let a=t[t.length-1],l=a.candidates?.[0];return n.responseId=a.responseId,n.createTime=a.createTime,n.modelVersion=a.modelVersion,n.promptFeedback=a.promptFeedback,n.usageMetadata=s,n.candidates=[{content:{role:l?.content?.role||"model",parts:o},...i?{finishReason:i}:{},index:0,safetyRatings:l?.safetyRatings||[]}],n}extractResponseText(t){let n=t?.candidates?.[0]?.content?.parts;if(!n?.length)return;let o="",r=!1,i=!1,s=a=>{if(r=!0,i)return;let l=ni-o.length;if(a.length<=l){o+=a;return}o+=a.slice(0,Math.max(0,l)),i=!0};for(let a of n){if(typeof a=="string"){s(a);continue}"text"in a&&typeof a.text=="string"&&!("thought"in a&&a.thought)&&s(a.text)}if(r)return i?`${o}${Wn}`:o}async countTokens(t){return this.wrapped.countTokens(t)}async embedContent(t){return this.wrapped.embedContent(t)}useSummarizedThinking(){return this.wrapped.useSummarizedThinking()}toContents(t){return Array.isArray(t)?t.map(n=>this.toContent(n)):[this.toContent(t)]}toContent(t){return Array.isArray(t)?{role:"user",parts:this.toParts(t)}:typeof t=="string"?{role:"user",parts:[{text:t}]}:"parts"in t?{...t,parts:t.parts?this.toParts(t.parts.filter(n=>n!=null)):[]}:{role:"user",parts:[this.toPart(t)]}}toParts(t){return t.map(n=>this.toPart(n))}toPart(t){if(typeof t=="string")return{text:t};if("thought"in t&&t.thought){let n=`[Thought: ${t.thought}]`,o={...t};if(delete o.thought,"functionCall"in o||"functionResponse"in o||"inlineData"in o||"fileData"in o)return o;let i=o.text,s=i?String(i):"",a=s?`${s}
8
+ ${n}`:n;return{...o,text:a}}return t}};f();var wt="x-matilda-organization-id",oi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function hl(e){if(e!==void 0){if(typeof e!="string"||e.length!==36||!oi.test(e))throw new Error("--organization-id must be a single UUID.");return e.toLowerCase()}}function Ot(e){if(e)try{let t=new URL(e);if((t.hostname==="matilda.maincode.com"&&t.protocol==="https:"&&!t.port||t.hostname==="core-api.matilda"&&(t.protocol==="http:"||t.protocol==="https:"))&&!t.username&&!t.password&&!t.search&&!t.hash)return t}catch{}}function Pt(e,t,n){if(t===void 0&&n===void 0)return;let o=Ot(e.baseUrl);if(!o||o.pathname.replace(/\/$/,"")!=="/api/v1/code"||e.authType!=="openai"&&e.authType!=="matilda-oauth"||e.matildaAgentSdk||process.env.MATILDA_AGENT_SDK==="1")throw new Error("Organization selection and credit spending require the first-party Matilda Core Code endpoint.")}function Yn(e){for(let t of Object.keys(e??{})){let n=t.toLowerCase();if(n===wt)throw new Error("Select the organization with --organization-id, not customHeaders.");if(n.startsWith("x-matilda-usage-credit-"))throw new Error("Code credit spending through customHeaders is not supported.")}}function Cl(e,t,n,o,r){Pt(n,o,r);let i=Ot(n.baseUrl),s=Ot(e instanceof Request?e.url:String(e));if(!s||s.origin!==i.origin||s.pathname!=="/api/v1/code/chat/completions")throw new Error("The selected organization cannot be sent to this endpoint.");let a=t.get(wt);if(a!==null&&a!==o)throw new Error("The request organization conflicts with --organization-id.");o!==void 0&&t.set(wt,o)}f();function Jn(e){switch(e){case"openai":return"OPENAI_API_KEY";case"anthropic":return"ANTHROPIC_API_KEY";case"gemini":return"GEMINI_API_KEY";case"vertex-ai":return"GOOGLE_API_KEY";default:return"API_KEY"}}function Xn(e){switch(e){case"openai":return"OPENAI_MODEL";case"anthropic":return"ANTHROPIC_MODEL";case"gemini":return"GEMINI_MODEL";case"vertex-ai":return"GOOGLE_MODEL";default:return"MODEL"}}var K=class extends Error{constructor(t){super(t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},qe=class extends K{code="STRICT_MISSING_CREDENTIALS";constructor(t,n,o){let r=t||"(unknown)",i=n||"(unknown)";super(`Missing credentials for modelProviders model '${i}'. `+(o?`Current configured envKey: '${o}'. Set that environment variable, or update modelProviders.${r}[].envKey.`:`Configure modelProviders.${r}[].envKey and set that environment variable.`))}},ze=class extends K{code="STRICT_MISSING_MODEL_ID";constructor(t){super(`Missing model id for strict modelProviders resolution (authType: ${t}).`)}},We=class extends K{code="MISSING_API_KEY";constructor(t){super(`Missing API key for ${t.authType} auth. Current model: '${t.model||"(unknown)"}', baseUrl: '${t.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${t.envKey}'.`)}},Ye=class extends K{code="MISSING_MODEL";constructor(t){super(`Missing model for ${t.authType} auth. Set the environment variable '${t.envKey}'.`)}},Je=class extends K{code="MISSING_BASE_URL";constructor(t){super(`Missing baseUrl for modelProviders model '${t.model||"(unknown)"}'. Configure modelProviders.${t.authType||"(unknown)"}[].baseUrl.`)}},Xe=class extends K{code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};f();import si from"node:process";f();var Qn={image:!0,pdf:!0,audio:!0,video:!0},ri=[[/^gemini-3/,Qn],[/^gemini-/,Qn],[/^gpt-5/,{image:!0}],[/^gpt-/,{image:!0}],[/^o\d/,{image:!0}],[/^claude-/,{image:!0,pdf:!0}],[/^matilda3\.5-plus/,{image:!0,video:!0}],[/^matilda3\.6-plus/,{image:!0,video:!0}],[/^matilda3\.7-plus/,{image:!0,video:!0}],[/^coder-model$/,{image:!0,video:!0}],[/^matilda-vl-/,{image:!0,video:!0}],[/^matilda3-vl-/,{image:!0,video:!0}],[/^matilda-code$/,{}],[/^matilda3-coder-/,{}],[/^matilda3\.6-35b/,{image:!0,video:!0}],[/^matilda/,{}],[/^deepseek/,{}],[/^glm-4\.5v/,{image:!0}],[/^glm-5(?:-|$)/,{}],[/^glm-/,{}],[/^minimax-m3/i,{image:!0,video:!0}],[/^minimax-/,{}],[/^kimi-k2\.5/,{image:!0,video:!0}],[/^kimi-/,{}],[/^doubao-seed(ance|ream)/,{}],[/^doubao-seed/,{image:!0}],[/^doubao-.*(vision|vl)/,{image:!0}],[/^doubao/,{}]];function Te(e){let t=dn(e);for(let[n,o]of ri)if(n.test(t))return{...o};return{}}f();var Qe="$runtime|";function Rl(e){let t=e;for(;t.startsWith(Qe);){let n=t.split("|").slice(2).join("|");if(!n)break;t=n}return t}f();f();f();var Ze=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],Zn=["model","apiKey","apiKeyEnvKey","baseUrl"],et=[...Zn,...Ze],Il={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","MATILDA_MODEL"]},anthropic:{apiKey:["ANTHROPIC_API_KEY"],baseUrl:["ANTHROPIC_BASE_URL"],model:["ANTHROPIC_MODEL"]},gemini:{apiKey:["GEMINI_API_KEY"],baseUrl:[],model:["GEMINI_MODEL"]},"vertex-ai":{apiKey:["GOOGLE_API_KEY"],baseUrl:[],model:["GOOGLE_MODEL"]},"matilda-oauth":{apiKey:[],baseUrl:[],model:[]}},wl={openai:ln,"matilda-oauth":q},tt=[{id:"coder-model",name:"coder-model",description:"Matilda 3.6 Plus \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:!0}}],Ol=tt.map(e=>e.id);var Dt=O("MODEL_REGISTRY");function eo(e){if(Object.values(P).includes(e))return e}function ii(e){return/^minimax-m3/i.test(e.trim().toLowerCase())}function to(e,t){return t?`${e}\0${t}`:e}var nt=class{modelsByAuthType;getDefaultBaseUrl(t){switch(t){case"matilda-oauth":return"DYNAMIC_MATILDA_OAUTH_BASE_URL";case"openai":return sn;default:return""}}constructor(t){if(this.modelsByAuthType=new Map,this.registerAuthTypeModels("matilda-oauth",tt),t)for(let[n,o]of Object.entries(t)){let r=eo(n);if(!r){Dt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(P).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}registerAuthTypeModels(t,n){let o=new Map;for(let r of n){let i=to(r.id,r.baseUrl);if(o.has(i)){Dt.warn(`Duplicate model id "${r.id}"${r.baseUrl?` with baseUrl "${r.baseUrl}"`:""} for authType "${t}". Using the first registered config.`);continue}let s=this.resolveModelConfig(r,t);o.set(i,s)}this.modelsByAuthType.set(t,o)}getModelsForAuthType(t){let n=this.modelsByAuthType.get(t);return n?Array.from(n.values()).map(o=>({id:o.id,label:o.name,description:o.description,capabilities:o.capabilities,authType:o.authType,isVision:o.capabilities?.vision??!1,contextWindowSize:o.generationConfig.contextWindowSize??pe(o.id),modalities:o.generationConfig.modalities,baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(t,n,o){let r=this.modelsByAuthType.get(t);if(!r)return;if(o)return r.get(to(n,o));let i=r.get(n);if(i)return i;for(let s of r.values())if(s.id===n)return s}hasModel(t,n,o){return this.getModel(t,n,o)!==void 0}getDefaultModelForAuthType(t){if(t==="matilda-oauth")return this.getModel(t,q);let n=this.modelsByAuthType.get(t);if(!(!n||n.size===0))return Array.from(n.values())[0]}resolveModelConfig(t,n){this.validateModelConfig(t,n);let o={...t.generationConfig??{}};return(o.modalities===void 0||ii(t.id))&&(o.modalities=Te(t.id)),{...t,authType:n,name:t.name||t.id,baseUrl:t.baseUrl||this.getDefaultBaseUrl(n),generationConfig:o,capabilities:t.capabilities||{}}}validateModelConfig(t,n){if(!t.id)throw new Error(`Model config in authType '${n}' missing required field: id`)}reloadModels(t){for(let n of this.modelsByAuthType.keys())n!=="matilda-oauth"&&this.modelsByAuthType.delete(n);if(t)for(let[n,o]of Object.entries(t)){let r=eo(n);if(!r){Dt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(P).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}};var no=class e{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;requireCachedMatildaCredentialsOnce=!1;hasManualCredentials=!1;onModelChange;authTypeWasExplicitlyProvided;runtimeModelSnapshots=new Map;activeRuntimeModelSnapshotId;static deepClone(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(o=>e.deepClone(o));let n={};for(let o of Object.keys(t))n[o]=e.deepClone(t[o]);return n}constructor(t={}){this.modelRegistry=new nt(t.modelProvidersConfig),this.onModelChange=t.onModelChange,this._generationConfig={...t.generationConfig||{}},this.generationConfigSources=t.generationConfigSources||{},this.authTypeWasExplicitlyProvided=t.initialAuthType!==void 0,this.currentAuthType=t.initialAuthType}createStateSnapshotForRollback(){return{currentAuthType:this.currentAuthType,generationConfig:e.deepClone(this._generationConfig),generationConfigSources:e.deepClone(this.generationConfigSources),strictModelProviderSelection:this.strictModelProviderSelection,requireCachedMatildaCredentialsOnce:this.requireCachedMatildaCredentialsOnce,hasManualCredentials:this.hasManualCredentials,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(t){this.currentAuthType=t.currentAuthType,this._generationConfig=t.generationConfig,this.generationConfigSources=t.generationConfigSources,this.strictModelProviderSelection=t.strictModelProviderSelection,this.requireCachedMatildaCredentialsOnce=t.requireCachedMatildaCredentialsOnce,this.hasManualCredentials=t.hasManualCredentials,this.activeRuntimeModelSnapshotId=t.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||q}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModelsForAuthType(this.currentAuthType):[]}getAvailableModelsForAuthType(t){return this.modelRegistry.getModelsForAuthType(t)}getAllConfiguredModels(t){let n=t&&t.length>0?t:Object.values(P),o=new Set,r=[];for(let l of n)o.has(l)||(o.add(l),r.push(l));let i=[];r.includes("matilda-oauth")&&i.push("matilda-oauth");for(let l of r)l!=="matilda-oauth"&&i.push(l);let s=this.getRuntimeModelOption(),a=[];for(let l of i)s&&s.authType===l&&a.push(s),a.push(...this.modelRegistry.getModelsForAuthType(l));return a}hasModel(t,n){return this.modelRegistry.hasModel(t,n)}getResolvedModel(t,n){return this.modelRegistry.getModel(t,n)}isManagedMatildaResolvedModel(t){return t?.id===St&&t?.envKey===un&&t?.baseUrl===pn&&t?.generationConfig?.openAIRequestProfile==="matilda-code"}isManagedMatildaModel(t){let n=t.trim();return!n||!this.currentAuthType?!1:this.isManagedMatildaResolvedModel(this.modelRegistry.getModel(this.currentAuthType,n))}getPublicModelId(t){return this.isManagedMatildaModel(t)?St:t}getModelDisplayName(t){return this.isManagedMatildaModel(t)?cn:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,t)?.name??t:t}async setModel(t,n){if(this.currentAuthType==="matilda-oauth"&&t===q){this.strictModelProviderSelection=!1,this._generationConfig.model=t,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.onModelChange&&await this.onModelChange("matilda-oauth",!1);return}if(this.currentAuthType&&this.modelRegistry.hasModel(this.currentAuthType,t)){await this.switchModel(this.currentAuthType,t);return}let o=this.createStateSnapshotForRollback();try{this.strictModelProviderSelection=!1,this._generationConfig.model=t,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.applyRawModelDerivedDefaults(t),this.onModelChange&&this.currentAuthType&&await this.onModelChange(this.currentAuthType,!0)}catch(r){throw this.rollbackToStateSnapshot(o),r}}applyRawModelDerivedDefaults(t){this.shouldUpdateModelDerivedDefault("modalities")&&(this._generationConfig.modalities=Te(t),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=pe(t,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"})}shouldUpdateModelDerivedDefault(t){let n=this.generationConfigSources[t];return n===void 0||n.kind==="computed"||n.kind==="default"||n.kind==="modelProviders"||n.kind==="programmatic"||n.kind==="unknown"}async switchModel(t,n,o){let r=this.extractRuntimeModelSnapshotId(n);if(r){await this.switchToRuntimeModel(r);return}let i=this.createStateSnapshotForRollback();t==="matilda-oauth"&&o?.requireCachedCredentials&&(this.requireCachedMatildaCredentialsOnce=!0);try{let s=t!==this.currentAuthType;this.currentAuthType=t;let a=this.modelRegistry.getModel(t,n,o?.baseUrl);if(!a)throw new Error(`Model '${n}' not found for authType '${t}'`);let l=i.generationConfig.model||"",c=!s&&l?this.modelRegistry.getModel(t,l,i.generationConfig.baseUrl)??this.modelRegistry.getModel(t,l):void 0,d=t!=="matilda-oauth"&&!s&&!!i.generationConfig.apiKey&&!!a.envKey&&c?.envKey===a.envKey&&c.baseUrl===a.baseUrl,p=d?i.generationConfig.apiKey:void 0,u=d?i.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(a),!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,u&&(this.generationConfigSources.apiKey=e.deepClone(u))),this.activeRuntimeModelSnapshotId=void 0;let h=s?!0:this.checkRequiresRefresh(l);this.onModelChange&&await this.onModelChange(t,h)}catch(s){throw this.rollbackToStateSnapshot(i),s}}buildRuntimeModelSnapshotId(t,n){return`${Qe}${t}|${n}`}extractRuntimeModelSnapshotId(t){if(t.startsWith(Qe))return this.runtimeModelSnapshots.has(t)?t:void 0;if(this.runtimeModelSnapshots.has(t))return t}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}mergeSettingsGenerationConfig(t){if(t)for(let n of Ze)!(n in this._generationConfig)&&n in t&&(this._generationConfig[n]=t[n],this.generationConfigSources[n]={kind:"settings",detail:`model.generationConfig.${n}`})}updateCredentials(t,n){(t.apiKey||t.baseUrl||t.model)&&(this.hasManualCredentials=!0,this.clearProviderSourcedConfig()),t.apiKey&&(this._generationConfig.apiKey=t.apiKey,this.generationConfigSources.apiKey={kind:"programmatic",detail:"updateCredentials"}),t.baseUrl&&(this._generationConfig.baseUrl=t.baseUrl,this.generationConfigSources.baseUrl={kind:"programmatic",detail:"updateCredentials"}),t.model&&(this._generationConfig.model=t.model,this.generationConfigSources.model={kind:"programmatic",detail:"updateCredentials"}),this.strictModelProviderSelection=!1,this._generationConfig.apiKeyEnvKey=void 0,n&&this.mergeSettingsGenerationConfig(n),this.syncRuntimeModelSnapshotWithCredentials()}syncRuntimeModelSnapshotWithCredentials(){let t=this.currentAuthType,{model:n,apiKey:o,baseUrl:r}=this._generationConfig;if(!(!n||!t||!o||!r)&&!this.modelRegistry.hasModel(t,n,r))if(this.activeRuntimeModelSnapshotId&&this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)){let i=this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);i.apiKey=o,i.baseUrl=r,i.modelId=n;let s=this.buildRuntimeModelSnapshotId(i.authType,i.modelId);s!==i.id&&(this.runtimeModelSnapshots.delete(i.id),i.id=s,this.runtimeModelSnapshots.set(s,i),this.activeRuntimeModelSnapshotId=s),i.createdAt=Date.now()}else this.detectAndCaptureRuntimeModel()}clearProviderSourcedConfig(){for(let t of et)this.generationConfigSources[t]?.kind==="modelProviders"&&(delete this._generationConfig[t],delete this.generationConfigSources[t])}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=!1}consumeRequireCachedCredentialsFlag(){let t=this.requireCachedMatildaCredentialsOnce;return this.requireCachedMatildaCredentialsOnce=!1,t}applyResolvedModelDefaults(t){if(this.strictModelProviderSelection=!0,this.hasManualCredentials=!1,this._generationConfig.model=t.id,this.generationConfigSources.model={kind:"modelProviders",authType:t.authType,modelId:t.id,detail:"model.id"},this.currentAuthType==="matilda-oauth"?(this._generationConfig.apiKey="MATILDA_OAUTH_DYNAMIC_TOKEN",this.generationConfigSources.apiKey={kind:"computed",detail:"Matilda OAuth placeholder token"},this._generationConfig.apiKeyEnvKey=void 0,delete this.generationConfigSources.apiKeyEnvKey):(this._generationConfig.apiKey=void 0,this._generationConfig.apiKeyEnvKey=void 0),t.envKey!==void 0){let o=si.env[t.envKey];o&&(this._generationConfig.apiKey=o,this.generationConfigSources.apiKey={kind:"env",envKey:t.envKey,via:{kind:"modelProviders",authType:t.authType,modelId:t.id,detail:"envKey"}}),this._generationConfig.apiKeyEnvKey=t.envKey,this.generationConfigSources.apiKeyEnvKey={kind:"modelProviders",authType:t.authType,modelId:t.id,detail:"envKey"}}this._generationConfig.baseUrl=t.baseUrl,this.generationConfigSources.baseUrl={kind:"modelProviders",authType:t.authType,modelId:t.id,detail:"baseUrl"};let n=t.generationConfig;for(let o of Ze)this._generationConfig[o]=n[o],this.generationConfigSources[o]={kind:"modelProviders",authType:t.authType,modelId:t.id,detail:`generationConfig.${o}`};n.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=pe(t.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=Te(t.id),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"})}checkRequiresRefresh(t){let n=this.currentAuthType;if(!n)return!0;if(n==="matilda-oauth")return!1;let o=this.modelRegistry.getModel(n,this._generationConfig.model||"",this._generationConfig.baseUrl||void 0),r=this.modelRegistry.getModel(n,t);return!r||!o||r.envKey!==o.envKey||r.baseUrl!==o.baseUrl}syncAfterAuthRefresh(t,n){this.strictModelProviderSelection=!1;let o=this.currentAuthType;this.currentAuthType=t;let r=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,i=n?this.modelRegistry.getModel(t,n,r)??this.modelRegistry.getModel(t,n):void 0;if(i){let h=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==i.envKey||this._generationConfig.baseUrl!==i.baseUrl),m=o===t&&this._generationConfig.model===n&&!h,g=m?this._generationConfig.apiKey:void 0,C=m&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,T=this.generationConfigSources.baseUrl,y=m&&!!this._generationConfig.baseUrl&&(T?.kind==="cli"||T?.kind==="env"||T?.kind==="settings"),E=y?this._generationConfig.baseUrl:void 0,R=y&&T?{...T}:void 0;this.applyResolvedModelDefaults(i),m&&!this._generationConfig.apiKey&&g&&(this._generationConfig.apiKey=g,C&&(this.generationConfigSources.apiKey=C)),E&&(this._generationConfig.baseUrl=E,R&&(this.generationConfigSources.baseUrl=R)),this.strictModelProviderSelection=!0,this.activeRuntimeModelSnapshotId=void 0;return}let s=this.generationConfigSources.apiKey,a=this.generationConfigSources.baseUrl,l=this._generationConfig.apiKey&&s?.kind!=="modelProviders"||this._generationConfig.baseUrl&&a?.kind!=="modelProviders";if(!(o!==t)&&(n===void 0||!this.modelRegistry.hasModel(t,n))&&(this.hasManualCredentials||l)){n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (preserved credentials)"}));return}let p=this.modelRegistry.getDefaultModelForAuthType(t);if(p){this.applyResolvedModelDefaults(p),this.activeRuntimeModelSnapshotId=void 0;return}n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (no default model)"}))}setOnModelChange(t){this.onModelChange=t}detectAndCaptureRuntimeModel(){let{model:t,apiKey:n,baseUrl:o,apiKeyEnvKey:r,...i}=this._generationConfig,s=this.currentAuthType;if(!t||!s)return;if(this.modelRegistry.hasModel(s,t,o)){this.clearRuntimeModelSnapshotForAuthType(s);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(s,t),c={id:l,authType:s,modelId:t,apiKey:n,baseUrl:o,apiKeyEnvKey:r,generationConfig:i,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(l,c),this.activeRuntimeModelSnapshotId=l,this.cleanupOldRuntimeModelSnapshots(),l}getActiveRuntimeModelSnapshot(){if(this.activeRuntimeModelSnapshotId)return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId)}getActiveRuntimeModelSnapshotId(){return this.activeRuntimeModelSnapshotId}async switchToRuntimeModel(t){let n=this.runtimeModelSnapshots.get(t);if(!n)throw new Error(`Runtime model snapshot '${t}' not found`);let o=this.createStateSnapshotForRollback();try{let r=n.authType!==this.currentAuthType;this.currentAuthType=n.authType,this.activeRuntimeModelSnapshotId=t,this.strictModelProviderSelection=!1,this.hasManualCredentials=!0,this._generationConfig.model=n.modelId,this.generationConfigSources.model={kind:"programmatic",detail:"runtimeModelSwitch"},n.apiKey&&(this._generationConfig.apiKey=n.apiKey,this.generationConfigSources.apiKey=n.sources.apiKey||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.baseUrl&&(this._generationConfig.baseUrl=n.baseUrl,this.generationConfigSources.baseUrl=n.sources.baseUrl||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.apiKeyEnvKey&&(this._generationConfig.apiKeyEnvKey=n.apiKeyEnvKey),n.generationConfig&&Object.assign(this._generationConfig,n.generationConfig);let i=r;this.onModelChange&&await this.onModelChange(n.authType,i)}catch(r){throw this.rollbackToStateSnapshot(o),r}}getRuntimeModelOption(){let t=this.getActiveRuntimeModelSnapshot();if(t)return{id:t.modelId,label:t.modelId,authType:t.authType,isVision:!1,contextWindowSize:t.generationConfig?.contextWindowSize,isRuntimeModel:!0,runtimeSnapshotId:t.id}}clearRuntimeModelSnapshotForAuthType(t){for(let[n,o]of this.runtimeModelSnapshots.entries())o.authType===t&&(this.runtimeModelSnapshots.delete(n),this.activeRuntimeModelSnapshotId===n&&(this.activeRuntimeModelSnapshotId=void 0))}cleanupOldRuntimeModelSnapshots(){let t=new Map;for(let n of this.runtimeModelSnapshots.values()){let o=t.get(n.authType);(!o||n.createdAt>o.createdAt)&&t.set(n.authType,n)}this.runtimeModelSnapshots.clear();for(let n of t.values())this.runtimeModelSnapshots.set(n.id,n);this.activeRuntimeModelSnapshotId&&!this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)&&(this.activeRuntimeModelSnapshotId=void 0)}reloadModelProvidersConfig(t){this.modelRegistry.reloadModels(t)}};f();import{readFileSync as Ri}from"node:fs";import{join as bi}from"node:path";f();f();import{randomBytes as ai,createHash as li}from"node:crypto";function oo(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}function Lt(){let e=ai(32).toString("base64url"),t=li("sha256").update(e).digest("base64url");return{codeVerifier:e,codeChallenge:t}}function ye(e,t){return{accessToken:e.access_token,refreshToken:e.refresh_token??t?.refreshToken,expiresAt:Date.now()+(e.expires_in??3600)*1e3,idToken:e.id_token??t?.idToken}}var di=15e3;async function Nt(e){let t=e.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",t);if(n.protocol!=="https:"&&!oo(n.hostname))throw new Error(`Refusing OAuth discovery over insecure transport: ${n.origin}`);let o=await fetch(n,{headers:{accept:"application/json"},signal:AbortSignal.timeout(di)});if(!o.ok)throw new Error(`OAuth discovery failed (${o.status}) for ${n.origin}`);let r=await o.json();if(!r.issuer||!r.authorization_endpoint||!r.token_endpoint)throw new Error(`OAuth discovery document missing required fields for ${n.origin}`);return{issuer:r.issuer,authorization_endpoint:r.authorization_endpoint,token_endpoint:r.token_endpoint,device_authorization_endpoint:r.device_authorization_endpoint}}f();import{promises as ot,openSync as ui,closeSync as ci,unlinkSync as ro,statSync as pi}from"node:fs";import{dirname as fi}from"node:path";var gi=2e4,mi=3e4,hi=50;function Ut(e,t={}){let n=async()=>{try{let i=await ot.readFile(e,"utf8"),s=JSON.parse(i);return s&&typeof s=="object"?s:{}}catch(i){if(i.code==="ENOENT")return{};throw i}},o=async i=>{await ot.mkdir(fi(e),{recursive:!0}),await ot.writeFile(e,JSON.stringify(i,null,2),{mode:384}),await ot.chmod(e,384).catch(()=>{})};return{store:{async get(i){return(await n())[i]??null},async set(i,s){let a=await n();a[i]=s,await o(a)},async remove(i){let s=await n();i in s&&(delete s[i],await o(s))}},lock:Ci(`${e}.lock`,t.lockTimeoutMs??gi)}}function Ci(e,t){let n=Promise.resolve();return o=>{let r=n.then(async()=>{await Ti(e,t);try{return await o()}finally{yi(e)}});return n=r.then(()=>{},()=>{}),r}}async function Ti(e,t){let n=Date.now()+t;for(;;)try{ci(ui(e,"wx"));return}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-pi(e).mtimeMs>mi){ro(e);continue}}catch{continue}if(Date.now()>n)throw Object.assign(new Error(`Timed out acquiring credential lock at ${e}`),{code:"ETIMEDOUT"});await Ai(hi)}}function yi(e){try{ro(e)}catch{}}function Ai(e){return new Promise(t=>setTimeout(t,e))}f();var ne=class extends Error{code="invalid_grant";constructor(t="Refresh token is no longer valid \u2014 sign in again."){super(t),this.name="InvalidGrantError"}};function Ft(e){let t=e.storageKey??"default",n=e.fetchImpl??fetch,o=e.expirySkewMs??6e4,r=e.refreshTimeoutMs??15e3,i=null,s=async()=>{let c=await e.store.get(t);if(!c)return null;try{let d=JSON.parse(c);return d.accessToken?d:null}catch{return null}},a=c=>c.expiresAt-Date.now()>o,l=c=>e.lock(async()=>{let d=await s()??c;if(d.accessToken!==c.accessToken&&a(d))return d.accessToken;if(!d.refreshToken)throw new ne("No refresh token available \u2014 sign in again.");let p;try{let h=await n(e.tokenEndpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:d.refreshToken}),signal:AbortSignal.timeout(r)});if(!h.ok){let m=await h.text().catch(()=>"");throw h.status>=400&&h.status<500&&Ei(m)==="invalid_grant"?(await e.store.remove(t),new ne):Object.assign(new Error(`Token refresh failed (${h.status})`),{status:h.status})}p=await h.json()}catch(h){throw h?.name==="TimeoutError"?Object.assign(new Error(`Token refresh timed out after ${r} ms`),{code:"ETIMEDOUT",cause:h}):h}let u=ye(p,d);return await e.store.set(t,JSON.stringify(u)),u.accessToken});return{async getAccessToken(c){let d=await s();if(!d)throw new ne("Not signed in.");return!c?.forceRefresh&&a(d)?d.accessToken:(i||(i=l(d).finally(()=>{i=null})),i)}}}function Ei(e){try{return JSON.parse(e).error}catch{return}}f();import{createServer as Si}from"node:http";import{randomBytes as Mi}from"node:crypto";async function Gt(e){if(e.transport.kind!=="loopback")throw new Error(`Unsupported login transport: ${e.transport.kind}`);if(e.signal?.aborted)throw new Error("Login aborted");let t=m=>e.onEvent?.(m),{codeVerifier:n,codeChallenge:o}=Lt(),r=Mi(16).toString("hex"),i=e.timeoutMs??5*60*1e3,s=e.transport.successRedirect;t({type:"state",status:"idle"});let a,l,c=new Promise((m,g)=>{a=m,l=g});c.catch(()=>{});let d=Si((m,g)=>{let C=new URL(m.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){g.writeHead(404).end();return}let T=C.searchParams.get("error"),y=C.searchParams.get("state"),E=C.searchParams.get("code");if(T){let R=C.searchParams.get("error_description"),H=R?`OAuth error: ${T} (${R})`:`OAuth error: ${T}`;g.writeHead(400,{"content-type":"text/plain; charset=utf-8"}).end(`Sign-in failed: ${T}
9
+ `,()=>l(new Error(H)));return}if(y!==r){g.writeHead(400).end("State mismatch"),l(new Error("OAuth state mismatch"));return}if(!E){g.writeHead(400).end("Missing authorization code");return}_i(g,s,()=>a(E))}),p=await new Promise((m,g)=>{d.once("error",g),d.listen(e.transport.port??0,"127.0.0.1",()=>{m(d.address().port)})}),u=setTimeout(()=>l(new Error("Login timed out \u2014 the browser never reached the local callback. The hosted success page is not a completed sign-in.")),i),h=()=>l(new Error("Login aborted"));e.signal?.addEventListener("abort",h,{once:!0}),e.signal?.aborted&&h();try{e.signal?.throwIfAborted();let m=`http://127.0.0.1:${p}/callback`,g=new URL(e.metadata.authorization_endpoint);g.searchParams.set("client_id",e.clientId),g.searchParams.set("response_type","code"),g.searchParams.set("redirect_uri",m),g.searchParams.set("code_challenge",o),g.searchParams.set("code_challenge_method","S256"),g.searchParams.set("state",r),g.searchParams.set("prompt","select_account"),g.searchParams.set("scope",e.scope??"openid offline_access");let C=g.toString();t({type:"authorize_url",url:C}),t({type:"state",status:"awaiting_user"}),e.openBrowser&&await e.openBrowser(C);let T=await c;await io(d),t({type:"state",status:"exchanging"});let y=await fetch(e.metadata.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:T,code_verifier:n,redirect_uri:m}),signal:e.signal});if(!y.ok){let R=await y.text().catch(()=>"");throw new Error(`Token exchange failed (${y.status}): ${R}`)}let E=ye(await y.json());return t({type:"state",status:"authenticated"}),E}catch(m){throw t({type:"state",status:"error"}),e.signal?.aborted?new Error("Login aborted"):m}finally{clearTimeout(u),e.signal?.removeEventListener("abort",h),await io(d)}}function io(e){return e.listening?new Promise(t=>{e.close(()=>t()),e.closeAllConnections()}):Promise.resolve()}function _i(e,t,n){e.writeHead(302,{location:t}).end(n)}var Ae="matilda-code",ao="matilda-desktop",vi="openid profile email offline_access",Ee="MATILDA_API_KEY",xi="matilda";function Se(e){return e.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function lo(){return bi(ve.getGlobalMatildaDir(),"matilda-auth.json")}function rt(){return Ut(lo())}function ki(e){return e==="desktop"}function Me(e){return e?.clientId?e.clientId:ki(e?.channel)?ao:Ae}function re(e){return`matilda:${e}`}function it(e){return`${re(e)}:refresh-rejected`}function _e(e){return e===Ae?[re(e),xi]:[re(e)]}function Ii(){try{let e=Ri(lo(),"utf8");return JSON.parse(e)}catch{return{}}}function Kt(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t?.accessToken=="string"&&typeof t?.baseUrl=="string"?t:null}catch{return null}}function wi(e,t){return Se(e)===Se(t)}function Oi(e){if(!e)return{};try{let t=e.split(".")[1],n=Buffer.from(t.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(n);return{sub:o.sub,email:o.email,name:o.name}}catch{return{}}}function Pi(e,t){let n=Oi(e.idToken);return{accessToken:e.accessToken,accessTokenExpiresAt:e.expiresAt,refreshToken:e.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:t}}var so=new Map;async function uo(e){let t=so.get(e);if(t)return t;try{let n=await Nt(e);return so.set(e,n),n}catch{return{issuer:e,authorization_endpoint:`${e}/api/auth/oauth/authorize`,token_endpoint:`${e}/api/auth/oauth/token`,device_authorization_endpoint:`${e}/api/auth/oauth/device/code`}}}function Y(e){try{let t=Ii(),n=Me(e);for(let o of _e(n)){let r=Kt(t[o]);if(r)return r}return null}catch{return null}}function co(e){let t=Y(e);return!t||e?.baseUrl&&!wi(t.baseUrl,e.baseUrl)?null:t}function Dd(e){return co(e)!==null}async function Di(e){let t=Me(e),n=rt().store;for(let o of _e(t))await n.remove(o);await n.set(it(t),"1"),delete process.env[Ee]}function Li(e){return e instanceof Error?e.code==="invalid_grant"||e.name==="InvalidGrantError"?!0:e.message==="Token refresh failed (401)":!1}function oe(e){$t({authStage:e.authStage,authOutcome:e.authOutcome,occurrenceCount:e.occurrenceCount},{baseUrl:e.baseUrl,token:e.token}).catch(()=>{})}async function Ni(e,t){let n=Me(t),o=rt().store;await o.set(re(n),JSON.stringify(e)),await o.remove(it(n));for(let r of _e(n))r!==re(n)&&await o.remove(r);process.env[Ee]=e.accessToken}async function Ui(e){let t=Me(e),n=rt().store;for(let o of _e(t))await n.remove(o);await n.remove(it(t)),delete process.env[Ee]}function Ld(e){let t=Y(e);return t?{authenticated:!0,userId:t.userId,email:t.email,displayName:t.displayName,baseUrl:t.baseUrl,accessTokenExpiresAt:t.accessTokenExpiresAt}:{authenticated:!1}}async function Nd(e){let t={channel:e?.channel,clientId:e?.clientId},n=Y(t);if(n?.accessToken){let o=Se(n.baseUrl);await fetch(`${o}/api/auth/logout`,{method:"POST",headers:{authorization:`Bearer ${n.accessToken}`,"content-type":"application/json"},body:JSON.stringify(n.refreshToken?{refreshToken:n.refreshToken}:{}),signal:e?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}await Ui(t)}async function Ht(e){let t=Me(e),n=re(t),o=co({baseUrl:e?.baseUrl,channel:e?.channel,clientId:t});if(!o)return e?.fallbackAccessToken??process.env[Ee]??"";let r=Se(o.baseUrl),i=await uo(r),{store:s,lock:a}=rt(),l=Fi(s,a,i.token_endpoint,o.baseUrl,t,n,e?.signal),c=t===Ae&&(!!e?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=3e5),d;try{d=await l.getAccessToken({forceRefresh:e?.forceRefresh})}catch(p){throw c&&oe({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"}),t===ao&&Li(p)&&await Di({channel:e?.channel,clientId:t}),p}return c&&oe({baseUrl:o.baseUrl,token:d,authStage:"refresh",authOutcome:"succeeded"}),process.env[Ee]=d,d}async function Ud(e){await Ht(e);let t=Y(e);if(!t)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return t}function Fi(e,t,n,o,r,i,s){let a=_e(r);return Ft({tokenEndpoint:n,clientId:r,store:{get:async d=>{let p=d===i?a:[d],u=null;for(let m of p)if(u=Kt(await e.get(m)),u)break;if(!u?.accessToken)return null;let h={accessToken:u.accessToken,refreshToken:u.refreshToken,expiresAt:u.accessTokenExpiresAt};return JSON.stringify(h)},set:async(d,p)=>{let u=JSON.parse(p),h=d===i?a:[d],m={};for(let C of h){let T=Kt(await e.get(C));if(T){m=T;break}}let g={...m,accessToken:u.accessToken,accessTokenExpiresAt:u.expiresAt,refreshToken:u.refreshToken??m.refreshToken??"",baseUrl:m.baseUrl??o};await e.set(i,JSON.stringify(g)),await e.remove(it(r));for(let C of a)C!==i&&await e.remove(C)},remove:async d=>{let p=d===i?a:[d];for(let u of p)await e.remove(u)}},storageKey:i,lock:t,fetchImpl:(d,p)=>{let u=[p?.signal,s].filter(h=>h instanceof AbortSignal);return fetch(d,{...p,signal:u.length>1?AbortSignal.any(u):u[0]})},expirySkewMs:3e5})}function Gi(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&nn()}async function Fd(e){let t=Se(e.baseUrl),n=await uo(t),o="",r=0,i=0,s={},a=p=>{s[p]=(s[p]??0)+1},c=await(p=>(r+=1,Gt({metadata:n,clientId:Ae,scope:p,transport:{kind:"loopback",successRedirect:`${t}/api/auth/oauth/success?client_id=${encodeURIComponent(Ae)}`},signal:e.signal,onEvent:u=>{u.type==="authorize_url"&&(o=u.url,e.onAuthorizeUrl?.(u.url)),u.type==="state"&&u.status==="exchanging"&&(i+=1)},openBrowser:async u=>{if(e.openBrowser===!1||!Gi()){a("skipped");return}try{let{default:h}=await import("./open-QQ7FWG4A.js");(await h(u)).once("error",()=>{}),a("succeeded")}catch{a("failed")}}})))(vi),d=Pi(c,e.baseUrl);await Ni(d),oe({baseUrl:e.baseUrl,token:d.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:r});for(let[p,u]of Object.entries(s))oe({baseUrl:e.baseUrl,token:d.accessToken,authStage:"browser_opened",authOutcome:p,occurrenceCount:u});return i>0&&oe({baseUrl:e.baseUrl,token:d.accessToken,authStage:"callback_received",authOutcome:"succeeded",occurrenceCount:i}),oe({baseUrl:e.baseUrl,token:d.accessToken,authStage:"token_persisted",authOutcome:"succeeded"}),{...d,authorizeUrl:o}}f();f();function ie(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="object"&&"message"in e.error}function st(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}function $d(e){let t=n=>n.includes("Quota exceeded for quota metric 'Gemini")&&n.includes("Pro Requests'");if(typeof e=="string")return t(e);if(st(e))return t(e.message);if(ie(e))return t(e.error.message);if(e&&typeof e=="object"&&"response"in e){let n=e;if(n.response&&n.response.data){if(typeof n.response.data=="string")return t(n.response.data);if(typeof n.response.data=="object"&&n.response.data!==null&&"error"in n.response.data){let o=n.response.data;return t(o.error?.message||"")}}}return!1}function Hd(e){return typeof e=="string"?e.includes("Quota exceeded for quota metric"):st(e)?e.message.includes("Quota exceeded for quota metric"):ie(e)?e.error.message.includes("Quota exceeded for quota metric"):!1}function po(e){if(typeof e!="object"||e===null)return!1;let{status:t,code:n,message:o}=e;return t===429&&n==="insufficient_quota"&&typeof o=="string"&&o.toLowerCase().includes("free allocated quota exceeded")}f();f();function fo(e){let t=Math.max(1,e.attempt),n=Math.min(e.maxDelayMs,2147483647),o=Math.min(t-1,31),r=Math.min(e.initialDelayMs*Math.pow(2,o),n),s=(e.retryAfterMode??"ignore")==="ignore"?null:Ki(e.error);if(s!==null&&s>0){let d=Math.min(e.retryAfterMaxDelayMs??e.maxDelayMs,2147483647),p=Math.min(s,d);return Math.max(r,p)}let a=e.jitterRatio??0;if(a<=0)return r;let l=e.random??Math.random,c=r*a*(l()*2-1);return Math.min(Math.max(0,r+c),n)}function Ki(e){let t=go(e,"retry-after")??$i(e,"retry-after");if(t===null)return null;let n=t.trim();if(/^\d+(\.\d+)?$/.test(n)){let i=Number(n);if(Number.isFinite(i)&&i>=0)return Math.min(i*1e3,2147483647)}let o=Date.parse(n);if(!Number.isFinite(o))return null;let r=o-Date.now();return r>0?Math.min(r,2147483647):0}function go(e,t){if(!Hi(e))return null;let{headers:n}=e;if(typeof n.get=="function"){let r=n.get(t);return typeof r=="string"?r:null}if(typeof n!="object"||n===null)return null;let o=t.toLowerCase();for(let[r,i]of Object.entries(n))if(r.toLowerCase()===o)return typeof i=="string"?i:null;return null}function $i(e,t){return ji(e)?go(e.response,t):null}function Hi(e){return typeof e=="object"&&e!==null&&"headers"in e&&e.headers!=null}function ji(e){return typeof e=="object"&&e!==null&&"response"in e&&typeof e.response=="object"&&e.response!==null&&"headers"in e.response&&e.response.headers!=null}var Vi=new Set([429,503,1302,1305]);function jt(e,t){if(Vt(e))return!1;let n=qi(e);return n===null?!1:!!(Vi.has(n)||t&&t.includes(n))}function Vt(e){return Bi(e)==="insufficient_quota"}function Bi(e){let t=ho(e)?.code;if(t!==void 0)return t;let n=typeof e=="object"&&e!==null&&"code"in e?e.code:void 0;return typeof n=="string"||typeof n=="number"?n:void 0}function mo(e){let t=U(e),n=ho(e),o=Co(e),r=o?.includes("event:error")||o?.includes("HTTP_STATUS/")?"sse":t!==void 0?"http":"unknown";return{...t!==void 0?{statusCode:t}:{},...n?.code!==void 0?{providerCode:String(n.code)}:{},...n?.message!==void 0?{providerMessage:n.message}:{},...n?.requestId!==void 0?{requestId:n.requestId}:{},transport:r}}function Jd(e,t){return fo({attempt:e,initialDelayMs:t.initialDelayMs,maxDelayMs:t.maxDelayMs,retryAfterMode:"minimum",retryAfterMaxDelayMs:t.maxDelayMs,error:t.error})}function qi(e){if(ie(e)){let n=Number(e.error.code);if(Number.isFinite(n)&&n>0)return n}let t=e instanceof Error?e.message:typeof e=="string"?e:null;if(t){let n=t.indexOf("{");if(n!==-1)try{let o=JSON.parse(t.substring(n));if(ie(o)){let r=Number(o.error.code);if(Number.isFinite(r)&&r>0)return r}}catch{}}if(st(e)&&typeof e.status=="number")return e.status;if(e instanceof Error&&"status"in e){let n=e.status;if(typeof n=="number")return n}return U(e)??null}function ho(e){for(let t of zi(e)){if(typeof t!="object"||t===null)continue;let n=t,o=t.error,i=(typeof o=="object"&&o!==null?o:void 0)??n,s=typeof i.code=="string"||typeof i.code=="number"?i.code:void 0,a=typeof i.message=="string"?i.message:void 0,l=typeof i.request_id=="string"?i.request_id:typeof i.requestId=="string"?i.requestId:typeof n.request_id=="string"?n.request_id:typeof n.requestId=="string"?n.requestId:void 0;if(s!==void 0||a!==void 0||l!==void 0)return{code:s,message:a,requestId:l}}return ie(e)?{code:e.error.code,message:e.error.message}:null}function zi(e){let t=Co(e);if(!t)return[];let n=[];for(let i of t.split(/\r?\n/)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(!s||s==="[DONE]"))try{n.push(JSON.parse(s))}catch{}}if(n.length>0)return n;let o=t.indexOf("{"),r=t.lastIndexOf("}");if(o!==-1&&r>o)try{n.push(JSON.parse(t.slice(o,r+1)))}catch{}return n}function Co(e){return e instanceof Error?e.message:typeof e=="string"?e:null}function Wi(e,t={}){if(Yi(e))return{kind:"abort",diagnosis:"fail-fast",reason:"aborted"};let n=mo(e),o=n.statusCode,r=ts(e),i=n.providerCode??r.providerCode,s=n.providerMessage??r.providerMessage,a=n.requestId??r.requestId,l={...o!==void 0?{statusCode:o}:{},...i!==void 0?{providerCode:i}:{},...s!==void 0?{providerMessage:s}:{},...a!==void 0?{requestId:a}:{}};if(t.authType==="matilda-oauth"&&po(e))return{kind:"provider-business",diagnosis:"fail-fast",reason:"matilda-oauth-free-tier-quota",...l};if(es(i))return{kind:"provider-business",diagnosis:"fail-fast",reason:"allocated-quota-exceeded",...l};if(Vt(e))return{kind:"provider-business",diagnosis:"fail-fast",reason:"insufficient-quota",...l};if(jt(e,t.extraRetryErrorCodes))return{kind:n.transport==="sse"?"sse-provider":o!==void 0?"http":"provider",diagnosis:"retryable",reason:"rate-limit",...l};let c=Xi(e);if(c!==void 0&&(o===void 0||o>=500))return{kind:"transport",diagnosis:"retryable",reason:"transport-error",transportCode:c,...o!==void 0?{statusCode:o}:{}};if(o!==void 0){let d=n.transport==="sse"?"sse-provider":"http";return o===529?{kind:d,diagnosis:"retryable",reason:"capacity-overload",...l}:o===401||o===403?{kind:d,diagnosis:"fail-fast",reason:"auth-error",...l}:o>=400&&o<500?{kind:d,diagnosis:"fail-fast",reason:"client-error",...l}:o>=500&&o<600?{kind:d,diagnosis:"retryable",reason:"server-error",...l}:{kind:d,diagnosis:"unknown",reason:"http-status",...l}}return i==="upstream_unavailable"||i==="upstream_timeout"||i==="incomplete_stream"?{kind:"sse-provider",diagnosis:"retryable",reason:"server-error",...l}:{kind:"unknown",diagnosis:"unknown",reason:"unclassified",...l}}function ou(e){let t=e.statusCode??Number(e.providerCode);return e.kind!=="transport"&&e.diagnosis!=="fail-fast"&&(t>=500&&t<600||e.kind==="sse-provider"&&e.reason==="server-error"&&e.diagnosis==="retryable")}function To(e,t){return jt(e,t)||Wi(e,{extraRetryErrorCodes:t}).diagnosis==="retryable"}function Yi(e){return Qt(e)?!0:e instanceof Error&&e.name==="CanceledError"}var Ji=5;function Xi(e){let t=e;for(let n=0;n<=Ji;n++){if(typeof t!="object"||t===null)return;let o=t.code;if(typeof o=="string"&&Qi(o))return o;t=t instanceof Error?t.cause:void 0}}function Qi(e){return Zi.has(e)}var Zi=new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET","ConnectionClosed","ConnectionRefused","ConnectionReset","ConnectionTimedOut","FailedToOpenSocket","HostUnreachable","NetworkUnreachable"]);function es(e){return e==="Throttling.AllocationQuota"}function ts(e){if(typeof e!="object"||e===null)return{};let t=e,n=typeof t.code=="string"||typeof t.code=="number"?String(t.code):void 0,o=typeof t.code=="number"&&t.code>=100&&t.code<600,r=e instanceof Error&&n?.startsWith("ERR_")||o?void 0:n,i=typeof t.request_id=="string"?t.request_id:typeof t.requestId=="string"?t.requestId:void 0,s=typeof t.message=="string"&&(!(e instanceof Error)||r!==void 0||i!==void 0)?t.message:void 0;return{...r!==void 0?{providerCode:r}:{},...s!==void 0?{providerMessage:s}:{},...i!==void 0?{requestId:i}:{}}}var P=(i=>(i.USE_OPENAI="openai",i.MATILDA_OAUTH="matilda-oauth",i.USE_GEMINI="gemini",i.USE_VERTEX_AI="vertex-ai",i.USE_ANTHROPIC="anthropic",i))(P||{}),ns="MATILDA_AGENT_SDK",at="MATILDA_API_KEY";function os(e,t){if(e.apiKey||e.apiKeyEnvKey!==at)return;let n=Y({channel:t});n?.accessToken&&(e.apiKey=n.accessToken,process.env[at]=n.accessToken)}async function rs(e,t){if(e.apiKeyEnvKey!==at)return;let n=Y({channel:t});if(!n?.accessToken)return;let o;try{o=await Ht({baseUrl:e.baseUrl,fallbackAccessToken:n.accessToken,channel:t})}catch(r){if(!To(r))throw r;o=n.accessToken}o&&(e.apiKey=o,process.env[at]=o)}function is(e){return e.matildaAgentSdk===!0||process.env[ns]==="1"}function Bt(e,t,n){e[t]=n}function ss(e,t){return e?.[t]}function as(e,t,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:t,proxy:e?.getProxy()};Bt(i,"authType",{kind:"computed",detail:"provided by caller"}),e?.getProxy()&&Bt(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=d=>ss(o,d)??{kind:"unknown"};for(let d of et)n&&d in n&&!i[d]&&Bt(i,d,l(d));os(a,e.getChannel());let c=Ao(a,s);if(!c.valid)throw new Error(c.errors.map(d=>d.message).join(`
10
+ `));return{config:a,sources:i}}function Ao(e,t=!1){let n=[];if(e.authType==="matilda-oauth")return{valid:!0,errors:[]};if(!e.apiKey)if(t)n.push(new qe(e.authType,e.model,e.apiKeyEnvKey));else{let o=e.apiKeyEnvKey||Jn(e.authType);n.push(new We({authType:e.authType,model:e.model,baseUrl:e.baseUrl,envKey:o}))}if(!e.model)if(t)n.push(new ze(e.authType));else{let o=Xn(e.authType);n.push(new Ye({authType:e.authType,envKey:o}))}return e.authType==="anthropic"&&!e.baseUrl&&(t?n.push(new Je({authType:e.authType,model:e.model})):e.authType==="anthropic"&&n.push(new Xe)),{valid:n.length===0,errors:n}}function pu(e,t,n){return as(e,t,n).config}function yo(e){let t=e;for(;t instanceof Error;){if("code"in t&&t.code==="ERR_MODULE_NOT_FOUND")return t;t=t.cause}}async function fu(e,t,n){Pt(e,t.getOrganizationId?.(),t.getCodeCreditLimitMinor?.()),Yn(e.customHeaders),await rs(e,t.getChannel());let o=Ao(e,!1);if(!o.valid)throw new Error(o.errors.map(s=>s.message).join(`
11
+ `));let r=e.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai")if(is(e)){let{createMatildaAgentContentGenerator:s}=await import("./matildaAgentContentGenerator-QQHPCFJ5.js");i=s(e,t)}else{let{createOpenAIContentGenerator:s}=await import("./openaiContentGenerator-NDVJL6QL.js");i=s(e,t)}else if(r==="matilda-oauth"){let{getMatildaOAuthClient:s}=await import("./matildaOAuth2-7COTQQR2.js"),{MatildaContentGenerator:a}=await import("./matildaContentGenerator-W7Z33ONU.js");try{let l=await s(t,n?{requireCachedCredentials:!0}:void 0);i=new a(l,e,t)}catch(l){throw yo(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(r==="anthropic"){let{createAnthropicContentGenerator:s}=await import("./anthropicContentGenerator-LLDIKDMQ.js");i=s(e,t)}else if(r==="gemini"||r==="vertex-ai"){let{createGeminiContentGenerator:s}=await import("./geminiContentGenerator-FIZFLPU3.js");i=s(e,t)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=yo(s);throw a?new Error(`Matilda was updated in the background and needs to be restarted.
12
+ Please exit and restart Matilda to use the '${r}' provider.`,{cause:a}):s}return new Ce(i,t,e)}var ls=["x-matilda-client-name","x-matilda-client-version","x-matilda-client-operating-system","x-matilda-client-architecture","x-matilda-client-distribution-channel","x-matilda-client-release-channel"],ds=new Set([...ls,...Xt]),us=new Set(["VSCode","ACP","SDK","CI"]),se="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",cs="[A-Za-z][0-9A-Za-z-]{0,23}",Eo="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",ps=new RegExp(`^${se}(?:-${cs}(?:\\.${Eo})+)?$`),fs=63,gs=new RegExp(`^${se}$`),ms=new RegExp(`^${se}-preview\\.(?:0|[1-9]\\d{0,11})$`),hs=new RegExp(`^${se}-canary\\.(?:0|[1-9]\\d{0,11})$`),Cs=new RegExp(`^${se}-nightly\\.(?:0|[1-9]\\d{0,11})\\.[0-9A-Fa-f]{7,12}$`),Ts=new RegExp(`^${se}-(preview|canary|nightly|development|internal)(?:\\.${Eo})+$`);function ys(e){return e==="desktop"?"desktop":e===void 0||us.has(e)?"code_cli":"unknown"}function As(e){if(e==="android")return"android";if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux")return"linux"}function Es(e){if(e==="x64")return"x64";if(e==="arm64")return"arm64"}function Ss(e){if(e===void 0)return"npm";if(e==="desktop")return"direct-download";if(e==="VSCode")return"vscode-marketplace"}function Ms(e,t){if(t==="desktop")return"matilda-desktop";if(e==="VSCode")return"matilda-vscode";if(t==="code_cli")return"matilda-code"}function _s(e){if(typeof e=="string"&&!(e.length>fs||!ps.test(e)))return e}function Rs(e){if(e!==void 0)return gs.test(e)?"stable":ms.test(e)?"preview":hs.test(e)?"canary":Cs.test(e)?"nightly":Ts.exec(e)?.[1]}function So(e,t=process.platform,n=process.arch){let o=e.getChannel?.(),r=ys(o),i=_s(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:e.getCliVersion?.()),s=Rs(i),a=As(t),l=Es(n),c=Ss(o),d=Ms(o,r);return{...d?{"x-matilda-client-name":d}:{},...i?{"x-matilda-client-version":i}:{},...a?{"x-matilda-client-operating-system":a}:{},...l?{"x-matilda-client-architecture":l}:{},...c?{"x-matilda-client-distribution-channel":c}:{},...s?{"x-matilda-client-release-channel":s}:{}}}function yu(e){let t=e.toLowerCase();return ds.has(t)||t.startsWith("x-matilda-reported-")}function bs(e){let t=e??an;try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let o=n.hostname.toLowerCase();return o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="core-api.matilda"}catch{return!1}}function Au(e,t=e.apiKey){return e.authType==="matilda-oauth"?!0:e.authType==="openai"&&!!t&&bs(e.baseUrl)}var vs=3e3,Re=1,xs=24*60*60*1e3,Mo=20,_o=999,ks=new Set(["UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_HAS_EXPIRED","ERR_TLS_CERT_ALTNAME_INVALID"]),Is=new Set(["ENOTFOUND","EAI_AGAIN"]),ws=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),Os=new Set(["ABORT_ERR","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT"]),Ps=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]);function Ds(e){return`${new URL(e).origin}/api/client-events`}function Ls(e){let t={eventType:e.eventType,platform:"cli"};return e.eventType==="network_error"&&(t.transportReason=e.transportReason,t.transportStage=e.transportStage,t.responseReceived=e.responseReceived,t.occurrenceCount=e.occurrenceCount),e.eventType==="auth_funnel"&&(t.authStage=e.authStage,t.authOutcome=e.authOutcome,t.occurrenceCount=e.occurrenceCount),e.eventType==="network_error"&&(t.reportedSurface=e.reportedSurface,t.reportedOs=e.reportedOs,t.reportedArchitecture=e.reportedArchitecture,t.reportedProcess=e.reportedProcess,t.reportedReleaseChannel=e.reportedReleaseChannel,e.reportedVersion&&(t.reportedVersion=e.reportedVersion)),t}async function qt(e,t){let{baseUrl:n,token:o}=t;if(!n||!o)return!1;let r=t.fetchImpl??fetch,i=new AbortController,s=setTimeout(()=>i.abort(),t.timeoutMs??vs);try{let a=await r(Ds(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(Ls(e)),signal:i.signal});return a.ok?!0:(xe.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`),!1)}catch{return!1}finally{clearTimeout(s)}}async function $t(e,t){let n=typeof e.occurrenceCount=="number"&&Number.isFinite(e.occurrenceCount)?Math.max(1,Math.min(Math.floor(e.occurrenceCount),_o)):1;return qt({eventType:"auth_funnel",authStage:e.authStage,authOutcome:e.authOutcome,occurrenceCount:n},t)}function Ro(){try{let e=$.readFileSync(xo(),"utf8"),t=JSON.parse(e);return t.schemaVersion!==Re||!Array.isArray(t.failures)?void 0:{schemaVersion:Re,failures:t.failures.filter(Ns)}}catch{return}}function Ns(e){if(!e||typeof e!="object")return!1;let t=e;return t.eventType==="network_error"&&typeof t.transportReason=="string"&&typeof t.transportStage=="string"&&typeof t.responseReceived=="boolean"&&typeof t.occurrenceCount=="number"&&typeof t.reportedSurface=="string"&&typeof t.reportedOs=="string"&&typeof t.reportedArchitecture=="string"&&typeof t.reportedProcess=="string"&&typeof t.reportedReleaseChannel=="string"&&typeof t.firstObservedAtMs=="number"&&typeof t.lastObservedAtMs=="number"}function bo(e){let t=xo();if(e.failures.length===0){try{$.rmSync(t,{force:!0})}catch{}return}try{$.mkdirSync(lt.dirname(t),{recursive:!0}),$.writeFileSync(t,`${JSON.stringify(e)}
13
+ `,"utf8")}catch{}}function vo(e,t){return e.filter(n=>t-n.lastObservedAtMs<=xs).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-Mo)}function Us(e){let t=So(e);return{reportedSurface:t["x-matilda-client-name"]==="matilda-desktop"?"desktop":t["x-matilda-client-name"]==="matilda-code"||t["x-matilda-client-name"]==="matilda-vscode"?"code_cli":"unknown",reportedOs:t["x-matilda-client-operating-system"]??"unknown",reportedArchitecture:t["x-matilda-client-architecture"]??"unknown",reportedProcess:t["x-matilda-client-name"]??"unknown",reportedVersion:t["x-matilda-client-version"],reportedReleaseChannel:t["x-matilda-client-release-channel"]??"unknown"}}function Fs(e){if(!e||typeof e!="object")return;let t=e.code;if(typeof t=="string")return t;if(!(e instanceof Error)||!e.cause||typeof e.cause!="object")return;let n=e.cause.code;return typeof n=="string"?n:void 0}function Gs(e){if(!(!e||typeof e!="object"))for(let t of["status","statusCode"]){let n=e[t];if(typeof n=="number")return n}}function Ks(e,t){let n=Fs(e);if(n&&ks.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&Is.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&ws.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&Os.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&Ps.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=Gs(e),r=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();if(r.includes("self signed")||r.includes("certificate")||r.includes("tls"))return{reason:"tls",stage:"tls",responseReceived:!1};if(o===407||n==="proxy_auth_required")return{reason:"proxy",stage:"connect",responseReceived:!0};if(t&&r.includes("proxy")&&(r.includes("407")||r.includes("connect")||r.includes("fetch failed")))return{reason:"proxy",stage:"connect",responseReceived:!1};if(r.includes("timed out")||r.includes("timeout")||r.includes("deadline exceeded"))return{reason:"timeout",stage:"request",responseReceived:!1};if(r.includes("fetch failed"))return{reason:"unknown",stage:"unknown",responseReceived:!1}}function $s(e,t){return e.findIndex(n=>n.transportReason===t.transportReason&&n.transportStage===t.transportStage&&n.responseReceived===t.responseReceived&&n.reportedSurface===t.reportedSurface&&n.reportedOs===t.reportedOs&&n.reportedArchitecture===t.reportedArchitecture&&n.reportedProcess===t.reportedProcess&&n.reportedVersion===t.reportedVersion&&n.reportedReleaseChannel===t.reportedReleaseChannel)}function bu(e,t){let n=Us(t.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=Ks(e,t.proxyConfigured);if(!o)return!1;let r=Date.now(),i={eventType:"network_error",transportReason:o.reason,transportStage:o.stage,responseReceived:o.responseReceived,occurrenceCount:1,...n,firstObservedAtMs:r,lastObservedAtMs:r},s=Ro()??{schemaVersion:Re,failures:[]},a=vo(s.failures,r),l=$s(a,i);if(l>=0){let c=a[l];a[l]={...c,occurrenceCount:Math.min(c.occurrenceCount+1,_o),lastObservedAtMs:r}}else a.push(i);return bo({schemaVersion:Re,failures:a.slice(-Mo)}),!0}async function vu(e){let t=Ro();if(!t)return;let n=vo(t.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await qt({eventType:i.eventType,transportReason:i.transportReason,transportStage:i.transportStage,responseReceived:i.responseReceived,occurrenceCount:i.occurrenceCount,reportedSurface:i.reportedSurface,reportedOs:i.reportedOs,reportedArchitecture:i.reportedArchitecture,reportedProcess:i.reportedProcess,reportedVersion:i.reportedVersion,reportedReleaseChannel:i.reportedReleaseChannel},e)){o.push(...n.slice(r));break}}bo({schemaVersion:Re,failures:o})}function xo(){return lt.join(ve.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var Io=(n=>(n.GCP="gcp",n.LOCAL="local",n))(Io||{}),Dp="local",Lp="http://localhost:4317";f();X();var js=new Set(["service.version","service.instance.id","session.id"]);function J(e,t){xe.warn(e),t?.push(e)}function wo(e,t){if(!e)return{};let n={};for(let o of e.split(",")){let r=o.trim();if(!r)continue;let i=r.indexOf("=");if(i<0){J(`Skipping malformed OTEL_RESOURCE_ATTRIBUTES entry: "${r}" (hint: percent-encode literal commas as %2C)`,t);continue}let s=r.slice(0,i).trim();if(!s)continue;let a=r.slice(i+1).trim(),l;try{l=decodeURIComponent(s)}catch{J(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,t),l=s}let c;try{c=decodeURIComponent(a)}catch{J(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${l}", using raw value`,t),c=a}n[l]=c}return n}function zt(e,t,n){for(let o of js)o in e&&(J(`${t} cannot override reserved key "${o}"; ignoring`,n),delete e[o]);return e}function Oo(e,t){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))return J("settings.telemetry.resourceAttributes must be an object; ignoring",t),{};let n={};for(let[o,r]of Object.entries(e)){let i=o.trim();if(!i){J("settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",t);continue}typeof r=="string"?n[i]=r:J(`settings.telemetry.resourceAttributes value for "${i}" must be a string (got ${typeof r}); ignoring`,t)}return n}function be(e){if(e!==void 0)return e==="true"||e==="1"}function ko(e){if(e!==void 0){if(e==="local"||e==="local")return"local";if(e==="gcp"||e==="gcp")return"gcp"}}async function Hs(e){let t=e.argv??{},n=e.env??{},o=e.settings??{},r=t.telemetry??be(n.MATILDA_TELEMETRY_ENABLED)??o.enabled,i=t.telemetryTarget??n.MATILDA_TELEMETRY_TARGET??o.target,s=ko(i);if(i!==void 0&&s===void 0)throw new dt(`Invalid telemetry target: ${String(i)}. Valid values are: local, gcp`);let a=t.telemetryOtlpEndpoint??n.MATILDA_TELEMETRY_OTLP_ENDPOINT??n.OTEL_EXPORTER_OTLP_ENDPOINT??o.otlpEndpoint,l=t.telemetryOtlpProtocol??n.MATILDA_TELEMETRY_OTLP_PROTOCOL??o.otlpProtocol,c=["grpc","http"].find(N=>N===l);if(l!==void 0&&c===void 0)throw new dt(`Invalid telemetry OTLP protocol: ${String(l)}. Valid values are: grpc, http`);let d=t.telemetryLogPrompts??be(n.MATILDA_TELEMETRY_LOG_PROMPTS)??o.logPrompts,p=be(n.MATILDA_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES)??o.includeSensitiveSpanAttributes??!1,u=t.telemetryOutfile??n.MATILDA_TELEMETRY_OUTFILE??o.outfile,h=n.MATILDA_TELEMETRY_OTLP_TRACES_ENDPOINT??n.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT??o.otlpTracesEndpoint,m=n.MATILDA_TELEMETRY_OTLP_LOGS_ENDPOINT??n.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT??o.otlpLogsEndpoint,g=n.MATILDA_TELEMETRY_OTLP_METRICS_ENDPOINT??n.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT??o.otlpMetricsEndpoint,C=[],T=zt(wo(n.OTEL_RESOURCE_ATTRIBUTES,C),"OTEL_RESOURCE_ATTRIBUTES",C),y=zt(Oo(o.resourceAttributes,C),"settings.telemetry.resourceAttributes",C),E={...T,...y},R=n.OTEL_SERVICE_NAME?.trim();R&&(E["service.name"]=R);let H=Object.keys(E).length?E:void 0,j=be(n.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??o.metrics?.includeSessionId??!1;return{enabled:r,target:s,otlpEndpoint:a,otlpProtocol:c,otlpTracesEndpoint:h,otlpLogsEndpoint:m,otlpMetricsEndpoint:g,logPrompts:d,includeSensitiveSpanAttributes:p,outfile:u,resourceAttributes:H,metrics:{includeSessionId:j},resourceAttributeWarnings:C.length?C:void 0}}export{_t as a,Z as b,Le as c,Fo as d,Go as e,Sn as f,Ke as g,Bn as h,cr as i,he as j,va as k,be as l,ko as m,Hs as n,te as o,Be as p,_r as q,It as r,Rr as s,wn as t,br as u,vr as v,On as w,xr as x,Pn as y,Dn as z,Ln as A,kr as B,Ir as C,Vr as D,Br as E,qr as F,zr as G,Wr as H,Yr as I,Jr as J,Xr as K,Qr as L,So as M,yu as N,Au as O,qt as P,$t as Q,bu as R,vu as S,Io as T,Dp as U,Lp as V,hl as W,Pt as X,Yn as Y,Cl as Z,Te as _,Qe as $,Rl as aa,Ze as ba,Il as ca,wl as da,tt as ea,Ol as fa,to as ga,nt as ha,no as ia,lo as ja,Y as ka,Dd as la,Li as ma,Ni as na,Ui as oa,Ld as pa,Nd as qa,Ht as ra,Ud as sa,Gi as ta,Fd as ua,ie as va,st as wa,$d as xa,Hd as ya,po as za,fo as Aa,Ki as Ba,jt as Ca,Vt as Da,Bi as Ea,mo as Fa,Jd as Ga,Wi as Ha,ou as Ia,To as Ja,P as Ka,as as La,Ao as Ma,pu as Na,fu as Oa};
14
+ /**
15
+ * @license
16
+ * Copyright 2026 Matilda Team
17
+ * SPDX-License-Identifier: Apache-2.0
18
+ */
19
+ /**
20
+ * @license
21
+ * Copyright 2025 Matilda
22
+ * SPDX-License-Identifier: Apache-2.0
23
+ */
24
+ /**
25
+ * @license
26
+ * Copyright 2025 Google LLC
27
+ * SPDX-License-Identifier: Apache-2.0
28
+ */
29
+ /**
30
+ * @license
31
+ * Copyright 2025 Matilda Team
32
+ * SPDX-License-Identifier: Apache-2.0
33
+ */
34
+ /**
35
+ * @license
36
+ * Copyright 2026 Maincode
37
+ * SPDX-License-Identifier: Apache-2.0
38
+ *
39
+ * Low-level OAuth primitives for core-auth's unified `/api/auth/oauth/*` flow
40
+ * (ADR-029): PKCE pair generation, RFC 8414 discovery, the RFC 8628 device
41
+ * grant, and refresh. Vendored (as source) from matilda-core's
42
+ * `packages/client-sdk/src/auth.ts` and extended to carry the `id_token`
43
+ * (display identity) that the higher-level flows need. Node built-ins only —
44
+ * no third-party runtime dependencies.
45
+ */
46
+ /**
47
+ * @license
48
+ * Copyright 2026 Maincode
49
+ * SPDX-License-Identifier: Apache-2.0
50
+ *
51
+ * File-backed token store + cross-process lock. The store persists a JSON map
52
+ * (`{ [key]: value }`) at 0600 so callers can key several credentials in one
53
+ * file; the lock is an O_EXCL lockfile that serialises refreshes across
54
+ * processes (the guarantee a plaintext read/modify/write can't give).
55
+ */
56
+ /**
57
+ * @license
58
+ * Copyright 2026 Maincode
59
+ * SPDX-License-Identifier: Apache-2.0
60
+ *
61
+ * Hardened access-token manager: returns a valid access token, refreshing via
62
+ * core-auth's token endpoint when expired or forced. Single-flight within the
63
+ * process, serialised across processes by the store's lock, carries a prior
64
+ * refresh token forward when the response omits one, and evicts on a terminal
65
+ * `invalid_grant` so a dead session doesn't wedge the caller in a refresh loop.
66
+ */
67
+ /**
68
+ * @license
69
+ * Copyright 2026 Maincode
70
+ * SPDX-License-Identifier: Apache-2.0
71
+ *
72
+ * Browser login orchestration: PKCE + a loopback capture server, driven off
73
+ * discovery metadata. Unlike a bare loopback helper, this emits lifecycle
74
+ * events for a UI, honours an AbortSignal, and — instead of serving its own
75
+ * HTML — 302-redirects the browser to an app-owned branded landing
76
+ * (`successRedirect`). Returns a TokenSet including the `id_token`.
77
+ */
78
+ /**
79
+ * @license
80
+ * Copyright 2026 Maincode
81
+ * SPDX-License-Identifier: Apache-2.0
82
+ *
83
+ * Node auth surface for `@maincode-ai/matilda-client-sdk/auth/node`.
84
+ * Re-exports the OAuth primitives plus the higher-level login flow, file token
85
+ * store, and hardened token manager that the CLI (`packages/core`) and the
86
+ * Electron desktop app consume.
87
+ */
88
+ /**
89
+ * @license
90
+ * Copyright 2026 Maincode
91
+ * SPDX-License-Identifier: Apache-2.0
92
+ *
93
+ * Matilda account auth for the CLI, backed by the shared client SDK.
94
+ *
95
+ * The OAuth dance (PKCE, loopback capture, code exchange, refresh, cross-process
96
+ * token locking) is owned by `@maincode-ai/matilda-client-sdk/auth/node` — the
97
+ * auth team's tested implementation of ADR-029's unified `/api/auth/oauth/*`
98
+ * flow. This module keeps ONLY the CLI-specific concerns: which endpoint, the
99
+ * on-disk credential shape the rest of the CLI already reads, and surfacing the
100
+ * authorize URL to the Ink UI. No PKCE crypto, no loopback server, no token
101
+ * exchange lives here anymore (replaced the 391-line hand-rolled beta that hit
102
+ * the divergent `/api/auth/cli/*` endpoints and stored tokens in plaintext).
103
+ */
104
+ /**
105
+ * @license
106
+ * Copyright 2026 Google LLC
107
+ * SPDX-License-Identifier: Apache-2.0
108
+ */
109
+ /**
110
+ * @license
111
+ * Copyright 2026 Matilda
112
+ * SPDX-License-Identifier: Apache-2.0
113
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as Ka}from"./chunk-LJR4RZZ2.js";import{b as D}from"./chunk-GZPNIYVZ.js";import{a as Q,d as B,f as Ja}from"./chunk-OWGSC52X.js";var Ya=B((OS,Wa)=>{D();function xe(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Wa.exports=xe;xe.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};xe.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};xe.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},n),this._options.unref&&this._timer.unref(),!0};xe.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};xe.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};xe.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};xe.prototype.start=xe.prototype.try;xe.prototype.errors=function(){return this._errors};xe.prototype.attempts=function(){return this._attempts};xe.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,n=0,i=0;i<this._errors.length;i++){var o=this._errors[i],s=o.message,l=(t[s]||0)+1;t[s]=l,l>=n&&(e=o,n=l)}return e}});var za=B(vt=>{D();var dp=Ya();vt.operation=function(t){var e=vt.timeouts(t);return new dp(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};vt.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in t)e[n]=t[n];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],o=0;o<e.retries;o++)i.push(this.createTimeout(o,e));return t&&t.forever&&!i.length&&i.push(this.createTimeout(o,e)),i.sort(function(s,l){return s-l}),i};vt.createTimeout=function(t,e){var n=e.randomize?Math.random()+1:1,i=Math.round(n*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return i=Math.min(i,e.maxTimeout),i};vt.wrap=function(t,e,n){if(e instanceof Array&&(n=e,e=null),!n){n=[];for(var i in t)typeof t[i]=="function"&&n.push(i)}for(var o=0;o<n.length;o++){var s=n[o],l=t[s];t[s]=function(c){var d=vt.operation(e),f=Array.prototype.slice.call(arguments,1),p=f.pop();f.push(function(h){d.retry(h)||(h&&(arguments[0]=d.mainError()),p.apply(this,arguments))}),d.attempt(function(){c.apply(t,f)})}.bind(t,l),t[s].options=e}}});var Qa=B((VS,Xa)=>{D();Xa.exports=za()});var ja=B((JS,kn)=>{"use strict";D();var fp=Qa(),pp=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],xn=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},hp=(t,e,n)=>{let i=n.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=i,t},mp=t=>pp.includes(t),Za=(t,e)=>new Promise((n,i)=>{e={onFailedAttempt:()=>{},retries:10,...e};let o=fp.operation(e);o.attempt(async s=>{try{n(await t(s))}catch(l){if(!(l instanceof Error)){i(new TypeError(`Non-error was thrown: "${l}". You should only throw errors.`));return}if(l instanceof xn)o.stop(),i(l.originalError);else if(l instanceof TypeError&&!mp(l.message))o.stop(),i(l);else{hp(l,s,e);try{await e.onFailedAttempt(l)}catch(u){i(u);return}o.retry(l)||i(o.mainError())}}})});kn.exports=Za;kn.exports.default=Za;kn.exports.AbortError=xn});var Po=B((WS,al)=>{"use strict";D();var Un=Object.prototype.hasOwnProperty,sl=Object.prototype.toString,el=Object.defineProperty,tl=Object.getOwnPropertyDescriptor,nl=function(e){return typeof Array.isArray=="function"?Array.isArray(e):sl.call(e)==="[object Array]"},il=function(e){if(!e||sl.call(e)!=="[object Object]")return!1;var n=Un.call(e,"constructor"),i=e.constructor&&e.constructor.prototype&&Un.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!i)return!1;var o;for(o in e);return typeof o>"u"||Un.call(e,o)},ol=function(e,n){el&&n.name==="__proto__"?el(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},rl=function(e,n){if(n==="__proto__")if(Un.call(e,n)){if(tl)return tl(e,n).value}else return;return e[n]};al.exports=function t(){var e,n,i,o,s,l,u=arguments[0],c=1,d=arguments.length,f=!1;for(typeof u=="boolean"&&(f=u,u=arguments[1]||{},c=2),(u==null||typeof u!="object"&&typeof u!="function")&&(u={});c<d;++c)if(e=arguments[c],e!=null)for(n in e)i=rl(u,n),o=rl(e,n),u!==o&&(f&&o&&(il(o)||(s=nl(o)))?(s?(s=!1,l=i&&nl(i)?i:[]):l=i&&il(i)?i:{},ol(u,{name:n,newValue:t(f,l,o)})):typeof o<"u"&&ol(u,{name:n,newValue:o}));return u}});var ll=B((zS,gp)=>{gp.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}});var cl=B((XS,ul)=>{"use strict";D();var yp=ll();ul.exports={pkg:yp}});var Do=B(ke=>{"use strict";D();var fl=ke&&ke.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ke,"__esModule",{value:!0});ke.GaxiosError=ke.GAXIOS_ERROR_SYMBOL=void 0;ke.defaultErrorRedactor=pl;var dl=fl(Po()),Ep=fl(cl()),Ro=Ep.default.pkg;ke.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Ro.name}-gaxios-error`);var No=class t extends Error{config;response;code;status;error;[ke.GAXIOS_ERROR_SYMBOL]=Ro.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&ke.GAXIOS_ERROR_SYMBOL in e&&e[ke.GAXIOS_ERROR_SYMBOL]===Ro.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,i,o){if(super(e,{cause:o}),this.config=n,this.response=i,this.error=o instanceof Error?o:void 0,this.config=(0,dl.default)(!0,{},n),this.response&&(this.response.config=(0,dl.default)(!0,{},this.response.config)),this.response){try{this.response.data=_p(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let i=n;if(typeof e.data=="string"&&(i=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){i="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:i;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let l=[];for(let u of e.data.error.errors)typeof u=="object"&&"message"in u&&typeof u.message=="string"&&l.push(u.message);return Object.assign({message:l.join(`
3
+ import{a as Ka}from"./chunk-AOOZREGV.js";import{b as D}from"./chunk-GZPNIYVZ.js";import{a as Q,d as B,f as Ja}from"./chunk-OWGSC52X.js";var Ya=B((OS,Wa)=>{D();function xe(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Wa.exports=xe;xe.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};xe.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};xe.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},n),this._options.unref&&this._timer.unref(),!0};xe.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};xe.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};xe.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};xe.prototype.start=xe.prototype.try;xe.prototype.errors=function(){return this._errors};xe.prototype.attempts=function(){return this._attempts};xe.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,n=0,i=0;i<this._errors.length;i++){var o=this._errors[i],s=o.message,l=(t[s]||0)+1;t[s]=l,l>=n&&(e=o,n=l)}return e}});var za=B(vt=>{D();var dp=Ya();vt.operation=function(t){var e=vt.timeouts(t);return new dp(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};vt.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in t)e[n]=t[n];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],o=0;o<e.retries;o++)i.push(this.createTimeout(o,e));return t&&t.forever&&!i.length&&i.push(this.createTimeout(o,e)),i.sort(function(s,l){return s-l}),i};vt.createTimeout=function(t,e){var n=e.randomize?Math.random()+1:1,i=Math.round(n*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return i=Math.min(i,e.maxTimeout),i};vt.wrap=function(t,e,n){if(e instanceof Array&&(n=e,e=null),!n){n=[];for(var i in t)typeof t[i]=="function"&&n.push(i)}for(var o=0;o<n.length;o++){var s=n[o],l=t[s];t[s]=function(c){var d=vt.operation(e),f=Array.prototype.slice.call(arguments,1),p=f.pop();f.push(function(h){d.retry(h)||(h&&(arguments[0]=d.mainError()),p.apply(this,arguments))}),d.attempt(function(){c.apply(t,f)})}.bind(t,l),t[s].options=e}}});var Qa=B((VS,Xa)=>{D();Xa.exports=za()});var ja=B((JS,kn)=>{"use strict";D();var fp=Qa(),pp=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],xn=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},hp=(t,e,n)=>{let i=n.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=i,t},mp=t=>pp.includes(t),Za=(t,e)=>new Promise((n,i)=>{e={onFailedAttempt:()=>{},retries:10,...e};let o=fp.operation(e);o.attempt(async s=>{try{n(await t(s))}catch(l){if(!(l instanceof Error)){i(new TypeError(`Non-error was thrown: "${l}". You should only throw errors.`));return}if(l instanceof xn)o.stop(),i(l.originalError);else if(l instanceof TypeError&&!mp(l.message))o.stop(),i(l);else{hp(l,s,e);try{await e.onFailedAttempt(l)}catch(u){i(u);return}o.retry(l)||i(o.mainError())}}})});kn.exports=Za;kn.exports.default=Za;kn.exports.AbortError=xn});var Po=B((WS,al)=>{"use strict";D();var Un=Object.prototype.hasOwnProperty,sl=Object.prototype.toString,el=Object.defineProperty,tl=Object.getOwnPropertyDescriptor,nl=function(e){return typeof Array.isArray=="function"?Array.isArray(e):sl.call(e)==="[object Array]"},il=function(e){if(!e||sl.call(e)!=="[object Object]")return!1;var n=Un.call(e,"constructor"),i=e.constructor&&e.constructor.prototype&&Un.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!i)return!1;var o;for(o in e);return typeof o>"u"||Un.call(e,o)},ol=function(e,n){el&&n.name==="__proto__"?el(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},rl=function(e,n){if(n==="__proto__")if(Un.call(e,n)){if(tl)return tl(e,n).value}else return;return e[n]};al.exports=function t(){var e,n,i,o,s,l,u=arguments[0],c=1,d=arguments.length,f=!1;for(typeof u=="boolean"&&(f=u,u=arguments[1]||{},c=2),(u==null||typeof u!="object"&&typeof u!="function")&&(u={});c<d;++c)if(e=arguments[c],e!=null)for(n in e)i=rl(u,n),o=rl(e,n),u!==o&&(f&&o&&(il(o)||(s=nl(o)))?(s?(s=!1,l=i&&nl(i)?i:[]):l=i&&il(i)?i:{},ol(u,{name:n,newValue:t(f,l,o)})):typeof o<"u"&&ol(u,{name:n,newValue:o}));return u}});var ll=B((zS,gp)=>{gp.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}});var cl=B((XS,ul)=>{"use strict";D();var yp=ll();ul.exports={pkg:yp}});var Do=B(ke=>{"use strict";D();var fl=ke&&ke.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ke,"__esModule",{value:!0});ke.GaxiosError=ke.GAXIOS_ERROR_SYMBOL=void 0;ke.defaultErrorRedactor=pl;var dl=fl(Po()),Ep=fl(cl()),Ro=Ep.default.pkg;ke.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Ro.name}-gaxios-error`);var No=class t extends Error{config;response;code;status;error;[ke.GAXIOS_ERROR_SYMBOL]=Ro.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&ke.GAXIOS_ERROR_SYMBOL in e&&e[ke.GAXIOS_ERROR_SYMBOL]===Ro.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,i,o){if(super(e,{cause:o}),this.config=n,this.response=i,this.error=o instanceof Error?o:void 0,this.config=(0,dl.default)(!0,{},n),this.response&&(this.response.config=(0,dl.default)(!0,{},this.response.config)),this.response){try{this.response.data=_p(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let i=n;if(typeof e.data=="string"&&(i=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){i="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:i;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let l=[];for(let u of e.data.error.errors)typeof u=="object"&&"message"in u&&typeof u.message=="string"&&l.push(u.message);return Object.assign({message:l.join(`
4
4
  `)||i,code:s,status:o},e.data.error)}return Object.assign({message:i,code:s,status:o},e.data.error)}}return{message:i,code:e.status,status:e.statusText}}};ke.GaxiosError=No;function _p(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function pl(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((l,u)=>{(/^authentication$/i.test(u)||/^authorization$/i.test(u)||/secret/i.test(u))&&s.set(u,e)})}function i(s,l){if(typeof s=="object"&&s!==null&&typeof s[l]=="string"){let u=s[l];(/grant_type=/i.test(u)||/assertion=/i.test(u)||/secret/i.test(u))&&(s[l]=e)}}function o(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((l,u)=>{(["grant_type","assertion"].includes(u)||/secret/.test(u))&&s.set(u,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.client_secret=e)))}return t.config&&(n(t.config.headers),i(t.config,"data"),o(t.config.data),i(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(pl({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(i(t.response,"data"),o(t.response.data))),t}});var ml=B(Mo=>{"use strict";D();Object.defineProperty(Mo,"__esModule",{value:!0});Mo.getRetryConfig=Tp;async function Tp(t){let e=hl(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||Ap)(t))return{shouldRetry:!1,config:t.config};let o=vp(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,o):new Promise(l=>{setTimeout(l,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function Ap(t){let e=hl(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let n=!1;for(let[i,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=i&&s<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function hl(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function vp(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,i=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,i,t.maxRetryDelay)}});var ko=B(Gn=>{"use strict";D();Object.defineProperty(Gn,"__esModule",{value:!0});Gn.GaxiosInterceptorManager=void 0;var xo=class extends Set{};Gn.GaxiosInterceptorManager=xo});var El=B(xt=>{"use strict";D();var Cp=xt&&xt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Mt;Object.defineProperty(xt,"__esModule",{value:!0});xt.Gaxios=void 0;var Sp=Cp(Po()),Ip=Q("https"),Ct=Do(),wp=ml(),gl=Q("stream"),yl=ko(),Pp=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),Rp=204,Ln=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new yl.GaxiosInterceptorManager,response:new yl.GaxiosInterceptorManager}}fetch(...e){let n=e[0],i=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&Mt.mergeHeaders(s,n.headers),i&&Mt.mergeHeaders(s,new Headers(i.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...i,...n,headers:s,url:o}):this.request({...i,headers:s,url:o})}async request(e={}){let n=await this.#i(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await Mt.#l(),i={...e};delete i.data;let o=await n(e.url,i),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let o=[];for await(let s of n.data)o.push(s);n.data=o.toString()}let i=Ct.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new Ct.GaxiosError(i?.message,e,n,i)}return n}catch(n){let i;n instanceof Ct.GaxiosError?i=n:n instanceof Error?i=new Ct.GaxiosError(n.message,e,void 0,n):i=new Ct.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,wp.getRetryConfig)(i);if(o&&s)return i.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=i.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(i),i}}async getResponseData(e,n){if(n.status===Rp)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new Ct.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":{let i=await n.text();try{return JSON.parse(i)}catch{return i}}case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let i=new URL(e),o=[...n],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let l of s)o.push(l.trim());for(let l of o)if(l instanceof RegExp){if(l.test(i.toString()))return!1}else if(l instanceof URL){if(l.origin===i.origin)return!1}else if(l.startsWith("*.")||l.startsWith(".")){let u=l.replace(/^\*\./,".");if(i.hostname.endsWith(u))return!1}else if(l===i.origin||l===i.hostname||l===i.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let i of this.interceptors.request.values())i&&(n=n.then(i.resolved,i.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let i of this.interceptors.response.values())i&&(n=n.then(i.resolved,i.rejected));return n}async#i(e){let n=new Headers(this.defaults.headers);Mt.mergeHeaders(n,e.headers);let i=(0,Sp.default)(!0,{},this.defaults,e);if(!i.url)throw new Error("URL is required.");if(i.baseURL&&(i.url=new URL(i.url,i.baseURL)),i.url=new URL(i.url),i.params)if(i.paramsSerializer){let l=i.paramsSerializer(i.params);l.startsWith("?")&&(l=l.slice(1));let u=i.url.toString().includes("?")?"&":"?";i.url=i.url+u+l}else{let l=i.url instanceof URL?i.url:new URL(i.url);for(let[u,c]of new URLSearchParams(i.params))l.searchParams.append(u,c);i.url=l}typeof e.maxContentLength=="number"&&(i.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(i.follow=e.maxRedirects);let o=typeof i.data=="string"||i.data instanceof ArrayBuffer||i.data instanceof Blob||globalThis.File&&i.data instanceof File||i.data instanceof FormData||i.data instanceof gl.Readable||i.data instanceof ReadableStream||i.data instanceof String||i.data instanceof URLSearchParams||ArrayBuffer.isView(i.data)||["Blob","File","FormData"].includes(i.data?.constructor?.name||"");if(i.multipart?.length){let l=await Pp();n.set("content-type",`multipart/related; boundary=${l}`),i.body=gl.Readable.from(this.getMultipartRequest(i.multipart,l))}else o?i.body=i.data:typeof i.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?i.body=i.paramsSerializer?i.paramsSerializer(i.data):new URLSearchParams(i.data):(n.has("content-type")||n.set("content-type","application/json"),i.body=JSON.stringify(i.data)):i.data&&(i.body=i.data);i.validateStatus=i.validateStatus||this.validateStatus,i.responseType=i.responseType||"unknown",!n.has("accept")&&i.responseType==="json"&&n.set("accept","application/json");let s=i.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!i.agent)if(s&&this.#e(i.url,i.noProxy)){let l=await Mt.#a();this.agentCache.has(s)?i.agent=this.agentCache.get(s):(i.agent=new l(s,{cert:i.cert,key:i.key}),this.agentCache.set(s,i.agent))}else i.cert&&i.key&&(this.agentCache.has(i.key)?i.agent=this.agentCache.get(i.key):(i.agent=new Ip.Agent({cert:i.cert,key:i.key}),this.agentCache.set(i.key,i.agent)));return typeof i.errorRedactor!="function"&&i.errorRedactor!==!1&&(i.errorRedactor=Ct.defaultErrorRedactor),i.body&&!("duplex"in i)&&(i.duplex="half"),this.#o(i),Object.assign(i,{headers:n,url:i.url instanceof URL?i.url:new URL(i.url)})}#o(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let i=await e.text();try{i=JSON.parse(i)}catch{}return i}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let i=`--${n}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
5
5
  Content-Type: ${s}\r
6
6
  \r
@@ -18,7 +18,7 @@ import{ba as cu}from"./chunk-27Q5KW3A.js";import{b as f}from"./chunk-GZPNIYVZ.js
18
18
  `)}formatDetailed(e,r=Date.now()){let n=this.getSummary(r),s=n.totalToolCalls>0?n.successRate??n.successfulToolCalls/n.totalToolCalls*100:0,o=[];o.push(`\u{1F4CB} Task Completed: ${e}`),o.push(`\u23F1\uFE0F Duration: ${this.fmtDuration(n.totalDurationMs)} | \u{1F501} Rounds: ${n.rounds}`);let a="Poor execution";s>=95?a="Excellent execution":s>=85?a="Good execution":s>=70&&(a="Fair execution"),o.push(`\u2705 Quality: ${a} (${s.toFixed(1)}% tool success)`);let i=n.totalDurationMs,c="Long execution - consider breaking down tasks";if(i<1e4?c="Fast completion - under 10 seconds":i<6e4?c="Good speed - under a minute":i<3e5&&(c="Moderate duration - a few minutes"),o.push(`\u{1F680} Speed: ${c}`),o.push(`\u{1F527} Tools: ${n.totalToolCalls} calls, ${s.toFixed(1)}% success (${n.successfulToolCalls} ok, ${n.failedToolCalls} failed)`),typeof n.totalTokens=="number"){let u=[`in ${n.inputTokens??0}`,`out ${n.outputTokens??0}`];o.push(`\u{1F522} Tokens: ${n.totalTokens.toLocaleString()} (${u.join(", ")})`)}if(n.toolUsage&&n.toolUsage.length){let u=[...n.toolUsage].sort((l,y)=>y.count-l.count).slice(0,5);o.push(`
19
19
  Top tools:`);for(let l of u){let y=typeof l.averageDurationMs=="number"?`, avg ${this.fmtDuration(Math.round(l.averageDurationMs))}`:"";o.push(` - ${l.name}: ${l.count} calls (${l.success} ok, ${l.failure} fail${y}${l.lastError?`, last error: ${l.lastError}`:""})`)}}let d=this.generatePerformanceTips(n);if(d.length){o.push(`
20
20
  \u{1F4A1} Performance Insights:`);for(let u of d.slice(0,3))o.push(` - ${u}`)}return o.join(`
21
- `)}fmtDuration(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;if(e<36e5){let s=Math.floor(e/6e4),o=Math.floor(e%6e4/1e3);return`${s}m ${o}s`}let r=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4);return`${r}h ${n}m`}generatePerformanceTips(e){let r=[],n=e.totalToolCalls;if((e.totalToolCalls>0?e.successRate??e.successfulToolCalls/e.totalToolCalls*100:0)<80&&r.push("Low tool success rate - review inputs and error messages"),e.totalDurationMs>6e4&&r.push("Long execution time - consider breaking down complex tasks"),typeof e.totalTokens=="number"&&e.totalTokens>1e5&&r.push("High token usage - consider optimizing prompts or narrowing scope"),typeof e.totalTokens=="number"&&n>0){let c=e.totalTokens/n;c>5e3&&r.push(`High token usage per tool call (~${Math.round(c)} tokens/call)`)}let o=c=>/web|fetch|search/i.test(c);(e.toolUsage||[]).some(c=>o(c.name)&&c.lastError&&/timeout|network/i.test(c.lastError))&&r.push("Network operations had failures - consider increasing timeout or checking connectivity");let i=(e.toolUsage||[]).filter(c=>(c.averageDurationMs??0)>1e4).sort((c,d)=>(d.averageDurationMs??0)-(c.averageDurationMs??0));return i.length&&r.push(`Consider optimizing ${i[0].name} operations (avg ${this.fmtDuration(Math.round(i[0].averageDurationMs))})`),r}};f();var Jm=class{constructor(e){this.params=e}toolLocations(){return[]}getDefaultPermission(){return Promise.resolve("allow")}getConfirmationDetails(e){let r={type:"info",title:`Confirm ${this.constructor.name.replace(/Invocation$/,"")}`,prompt:this.getDescription(),onConfirm:async(n,s)=>{}};return Promise.resolve(r)}},au=class{constructor(e,r,n,s,o,a=!0,i=!1,c=!1,d=!1,u){this.name=e;this.displayName=r;this.description=n;this.kind=s;this.parameterSchema=o;this.isOutputMarkdown=a;this.canUpdateOutput=i;this.shouldDefer=c;this.alwaysLoad=d;this.searchHint=u}get schema(){return{name:this.name,description:this.description,parametersJsonSchema:this.parameterSchema}}get maxOutputChars(){}get truncateKeep(){return"both"}toAutoClassifierInput(e){return""}validateToolParams(e){return null}async buildAndExecute(e,r,n,s){return this.build(e).execute(r,n,s)}silentBuild(e){try{return this.build(e)}catch(r){return r instanceof Error?r:new Error(String(r))}}async validateBuildAndExecute(e,r){let n=this.silentBuild(e);if(n instanceof Error){let s=n.message;return{llmContent:`Error: Invalid parameters provided. Reason: ${s}`,returnDisplay:s,error:{message:s,type:"invalid_tool_params"}}}try{return await n.execute(r)}catch(s){let o=s instanceof Error?s.message:String(s);return{llmContent:`Error: Tool call execution failed. Reason: ${o}`,returnDisplay:o,error:{message:o,type:"execution_failed"}}}}},Bm=class extends au{build(e){let r=this.validateToolParams(e);if(r)throw new Error(r);return this.createInvocation(e)}validateToolParams(e){let r=to.validate(this.schema.parametersJsonSchema,e);return r||this.validateToolParamValues(e)}validateToolParamValues(e){return null}};function VN(t){return typeof t=="object"&&t!==null&&"name"in t&&"build"in t&&typeof t.build=="function"}function xN(t){function e(n){if(!n.startsWith("#/"))return null;let s=n.substring(2).split("/"),o=t;for(let a of s){if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,a))return null;o=o[a]}return o}function r(n,s,o){if(typeof n!="object"||n===null)return!1;if(Array.isArray(n)){for(let a of n)if(r(a,s,o))return!0;return!1}if("$ref"in n&&typeof n.$ref=="string"){let a=n.$ref;if(a==="#/"||o.has(a))return!0;if(s.has(a))return!1;let i=e(a);if(i){s.add(a),o.add(a);let c=r(i,s,o);return o.delete(a),c}}for(let a in n)if(Object.prototype.hasOwnProperty.call(n,a)&&r(n[a],s,o))return!0;return!1}return r(t,new Set,new Set)}var JP=(d=>(d.ProceedOnce="proceed_once",d.ProceedAlways="proceed_always",d.ProceedAlwaysServer="proceed_always_server",d.ProceedAlwaysTool="proceed_always_tool",d.ProceedAlwaysProject="proceed_always_project",d.ProceedAlwaysUser="proceed_always_user",d.ModifyWithEditor="modify_with_editor",d.RestorePrevious="restore_previous",d.Cancel="cancel",d))(JP||{}),BP=(u=>(u.Read="read",u.Edit="edit",u.Delete="delete",u.Move="move",u.Search="search",u.Execute="execute",u.Think="think",u.Fetch="fetch",u.Agent="agent",u.Other="other",u))(BP||{}),zN=["edit","delete","move","execute"],LN=new Set(["read","search","fetch"]);f();var iu={EDIT:"edit",WRITE_FILE:"write_file",READ_FILE:"read_file",GREP:"grep_search",GLOB:"glob",SHELL:"run_shell_command",TODO_WRITE:"todo_write",MEMORY:"save_memory",AGENT:"agent",SKILL:"skill",EXIT_PLAN_MODE:"exit_plan_mode",ENTER_PLAN_MODE:"enter_plan_mode",GET_GOAL:"get_goal",UPDATE_GOAL:"update_goal",WEB_FETCH:"web_fetch",WEB_SEARCH:"web_search",SYMBOL_SEARCH:"symbol_search",LS:"list_directory",LSP:"lsp",ASK_USER_QUESTION:"ask_user_question",CRON_CREATE:"cron_create",CRON_LIST:"cron_list",CRON_DELETE:"cron_delete",TASK_STOP:"task_stop",TASK_DETACH:"task_detach",TASK_CREATE:"task_create",TASK_UPDATE:"task_update",TASK_LIST:"task_list",TEAM_CREATE:"team_create",TEAM_DELETE:"team_delete",SEND_MESSAGE:"send_message",STRUCTURED_OUTPUT:"structured_output",MONITOR:"monitor",NOTEBOOK_EDIT:"notebook_edit",TOOL_SEARCH:"tool_search",ENTER_WORKTREE:"enter_worktree",EXIT_WORKTREE:"exit_worktree",WORKFLOW:"workflow"},no={EDIT:"Edit",WRITE_FILE:"WriteFile",READ_FILE:"ReadFile",GREP:"Grep",GLOB:"Glob",SHELL:"Shell",TODO_WRITE:"TodoWrite",MEMORY:"SaveMemory",AGENT:"Agent",SKILL:"Skill",EXIT_PLAN_MODE:"ExitPlanMode",ENTER_PLAN_MODE:"EnterPlanMode",GET_GOAL:"Goal",UPDATE_GOAL:"UpdateGoal",WEB_FETCH:"WebFetch",WEB_SEARCH:"WebSearch",SYMBOL_SEARCH:"SymbolSearch",LS:"ListFiles",LSP:"Lsp",ASK_USER_QUESTION:"AskUserQuestion",CRON_CREATE:"CronCreate",CRON_LIST:"CronList",CRON_DELETE:"CronDelete",TASK_STOP:"TaskStop",TASK_DETACH:"TaskDetach",TASK_CREATE:"TaskCreate",TASK_UPDATE:"TaskUpdate",TASK_LIST:"TaskList",TEAM_CREATE:"TeamCreate",TEAM_DELETE:"TeamDelete",SEND_MESSAGE:"SendMessage",STRUCTURED_OUTPUT:"StructuredOutput",MONITOR:"Monitor",NOTEBOOK_EDIT:"NotebookEdit",TOOL_SEARCH:"ToolSearch",ENTER_WORKTREE:"EnterWorktree",EXIT_WORKTREE:"ExitWorktree",WORKFLOW:"Workflow"},Xm={search_file_content:iu.GREP,replace:iu.EDIT,task:iu.AGENT};function KN(t){return Object.prototype.hasOwnProperty.call(Xm,t)?Xm[t]??t:t}var GN={SearchFiles:no.GREP,FindFiles:no.GLOB,ReadFolder:no.LS,Task:no.AGENT};export{uu as a,Kr as b,Yo as c,Dm as d,to as e,Wm as f,Jm as g,au as h,Bm as i,VN as j,xN as k,JP as l,BP as m,zN as n,LN as o,iu as p,no as q,Xm as r,KN as s,GN as t};
21
+ `)}fmtDuration(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;if(e<36e5){let s=Math.floor(e/6e4),o=Math.floor(e%6e4/1e3);return`${s}m ${o}s`}let r=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4);return`${r}h ${n}m`}generatePerformanceTips(e){let r=[],n=e.totalToolCalls;if((e.totalToolCalls>0?e.successRate??e.successfulToolCalls/e.totalToolCalls*100:0)<80&&r.push("Low tool success rate - review inputs and error messages"),e.totalDurationMs>6e4&&r.push("Long execution time - consider breaking down complex tasks"),typeof e.totalTokens=="number"&&e.totalTokens>1e5&&r.push("High token usage - consider optimizing prompts or narrowing scope"),typeof e.totalTokens=="number"&&n>0){let c=e.totalTokens/n;c>5e3&&r.push(`High token usage per tool call (~${Math.round(c)} tokens/call)`)}let o=c=>/web|fetch|search/i.test(c);(e.toolUsage||[]).some(c=>o(c.name)&&c.lastError&&/timeout|network/i.test(c.lastError))&&r.push("Network operations had failures - consider increasing timeout or checking connectivity");let i=(e.toolUsage||[]).filter(c=>(c.averageDurationMs??0)>1e4).sort((c,d)=>(d.averageDurationMs??0)-(c.averageDurationMs??0));return i.length&&r.push(`Consider optimizing ${i[0].name} operations (avg ${this.fmtDuration(Math.round(i[0].averageDurationMs))})`),r}};f();var Jm=class{constructor(e){this.params=e}toolLocations(){return[]}getDefaultPermission(){return Promise.resolve("allow")}getConfirmationDetails(e){let r={type:"info",title:`Confirm ${this.constructor.name.replace(/Invocation$/,"")}`,prompt:this.getDescription(),onConfirm:async(n,s)=>{}};return Promise.resolve(r)}},au=class{constructor(e,r,n,s,o,a=!0,i=!1,c=!1,d=!1,u){this.name=e;this.displayName=r;this.description=n;this.kind=s;this.parameterSchema=o;this.isOutputMarkdown=a;this.canUpdateOutput=i;this.shouldDefer=c;this.alwaysLoad=d;this.searchHint=u}get schema(){return{name:this.name,description:this.description,parametersJsonSchema:this.parameterSchema}}get maxOutputChars(){}get truncateKeep(){return"both"}get boundsOwnOutput(){return!1}toAutoClassifierInput(e){return""}validateToolParams(e){return null}async buildAndExecute(e,r,n,s){return this.build(e).execute(r,n,s)}silentBuild(e){try{return this.build(e)}catch(r){return r instanceof Error?r:new Error(String(r))}}async validateBuildAndExecute(e,r){let n=this.silentBuild(e);if(n instanceof Error){let s=n.message;return{llmContent:`Error: Invalid parameters provided. Reason: ${s}`,returnDisplay:s,error:{message:s,type:"invalid_tool_params"}}}try{return await n.execute(r)}catch(s){let o=s instanceof Error?s.message:String(s);return{llmContent:`Error: Tool call execution failed. Reason: ${o}`,returnDisplay:o,error:{message:o,type:"execution_failed"}}}}},Bm=class extends au{build(e){let r=this.validateToolParams(e);if(r)throw new Error(r);return this.createInvocation(e)}validateToolParams(e){let r=to.validate(this.schema.parametersJsonSchema,e);return r||this.validateToolParamValues(e)}validateToolParamValues(e){return null}};function VN(t){return typeof t=="object"&&t!==null&&"name"in t&&"build"in t&&typeof t.build=="function"}function xN(t){function e(n){if(!n.startsWith("#/"))return null;let s=n.substring(2).split("/"),o=t;for(let a of s){if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,a))return null;o=o[a]}return o}function r(n,s,o){if(typeof n!="object"||n===null)return!1;if(Array.isArray(n)){for(let a of n)if(r(a,s,o))return!0;return!1}if("$ref"in n&&typeof n.$ref=="string"){let a=n.$ref;if(a==="#/"||o.has(a))return!0;if(s.has(a))return!1;let i=e(a);if(i){s.add(a),o.add(a);let c=r(i,s,o);return o.delete(a),c}}for(let a in n)if(Object.prototype.hasOwnProperty.call(n,a)&&r(n[a],s,o))return!0;return!1}return r(t,new Set,new Set)}var JP=(d=>(d.ProceedOnce="proceed_once",d.ProceedAlways="proceed_always",d.ProceedAlwaysServer="proceed_always_server",d.ProceedAlwaysTool="proceed_always_tool",d.ProceedAlwaysProject="proceed_always_project",d.ProceedAlwaysUser="proceed_always_user",d.ModifyWithEditor="modify_with_editor",d.RestorePrevious="restore_previous",d.Cancel="cancel",d))(JP||{}),BP=(u=>(u.Read="read",u.Edit="edit",u.Delete="delete",u.Move="move",u.Search="search",u.Execute="execute",u.Think="think",u.Fetch="fetch",u.Agent="agent",u.Other="other",u))(BP||{}),zN=["edit","delete","move","execute"],LN=new Set(["read","search","fetch"]);f();var iu={EDIT:"edit",WRITE_FILE:"write_file",READ_FILE:"read_file",GREP:"grep_search",GLOB:"glob",SHELL:"run_shell_command",TODO_WRITE:"todo_write",MEMORY:"save_memory",AGENT:"agent",SKILL:"skill",EXIT_PLAN_MODE:"exit_plan_mode",ENTER_PLAN_MODE:"enter_plan_mode",GET_GOAL:"get_goal",UPDATE_GOAL:"update_goal",WEB_FETCH:"web_fetch",WEB_SEARCH:"web_search",SYMBOL_SEARCH:"symbol_search",LS:"list_directory",LSP:"lsp",ASK_USER_QUESTION:"ask_user_question",CRON_CREATE:"cron_create",CRON_LIST:"cron_list",CRON_DELETE:"cron_delete",TASK_STOP:"task_stop",TASK_DETACH:"task_detach",TASK_CREATE:"task_create",TASK_UPDATE:"task_update",TASK_LIST:"task_list",TEAM_CREATE:"team_create",TEAM_DELETE:"team_delete",SEND_MESSAGE:"send_message",STRUCTURED_OUTPUT:"structured_output",MONITOR:"monitor",NOTEBOOK_EDIT:"notebook_edit",TOOL_SEARCH:"tool_search",ENTER_WORKTREE:"enter_worktree",EXIT_WORKTREE:"exit_worktree",WORKFLOW:"workflow"},no={EDIT:"Edit",WRITE_FILE:"WriteFile",READ_FILE:"ReadFile",GREP:"Grep",GLOB:"Glob",SHELL:"Shell",TODO_WRITE:"TodoWrite",MEMORY:"SaveMemory",AGENT:"Agent",SKILL:"Skill",EXIT_PLAN_MODE:"ExitPlanMode",ENTER_PLAN_MODE:"EnterPlanMode",GET_GOAL:"Goal",UPDATE_GOAL:"UpdateGoal",WEB_FETCH:"WebFetch",WEB_SEARCH:"WebSearch",SYMBOL_SEARCH:"SymbolSearch",LS:"ListFiles",LSP:"Lsp",ASK_USER_QUESTION:"AskUserQuestion",CRON_CREATE:"CronCreate",CRON_LIST:"CronList",CRON_DELETE:"CronDelete",TASK_STOP:"TaskStop",TASK_DETACH:"TaskDetach",TASK_CREATE:"TaskCreate",TASK_UPDATE:"TaskUpdate",TASK_LIST:"TaskList",TEAM_CREATE:"TeamCreate",TEAM_DELETE:"TeamDelete",SEND_MESSAGE:"SendMessage",STRUCTURED_OUTPUT:"StructuredOutput",MONITOR:"Monitor",NOTEBOOK_EDIT:"NotebookEdit",TOOL_SEARCH:"ToolSearch",ENTER_WORKTREE:"EnterWorktree",EXIT_WORKTREE:"ExitWorktree",WORKFLOW:"Workflow"},Xm={search_file_content:iu.GREP,replace:iu.EDIT,task:iu.AGENT};function KN(t){return Object.prototype.hasOwnProperty.call(Xm,t)?Xm[t]??t:t}var GN={SearchFiles:no.GREP,FindFiles:no.GLOB,ReadFolder:no.LS,Task:no.AGENT};export{uu as a,Kr as b,Yo as c,Dm as d,to as e,Wm as f,Jm as g,au as h,Bm as i,VN as j,xN as k,JP as l,BP as m,zN as n,LN as o,iu as p,no as q,Xm as r,KN as s,GN as t};
22
22
  /**
23
23
  * @license
24
24
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{b as o}from"./chunk-GZPNIYVZ.js";o();function l(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var c=/<[^<>]*>/g;function r(t){return t!==void 0&&/\s/.test(t)}function a(t){let e=t.codePointAt(0);return e===void 0?!1:e===173||e===1564||e===12644||e===65279||e===65440||e>=0&&e<=31||e>=127&&e<=159||e>=4447&&e<=4448||e>=6068&&e<=6069||e>=6155&&e<=6159||e>=8203&&e<=8207||e>=8234&&e<=8238||e>=8288&&e<=8303||e>=65024&&e<=65039||e>=65520&&e<=65528||e>=113824&&e<=113827||e>=119155&&e<=119162||e>=917504&&e<=921599}function x(t){let e="";for(let i of t)a(i)||(e+=i);return e.toLowerCase()}function d(t){let e=x(t),i=e.length;if(i<2||e[0]!=="<"||e[i-1]!==">")return;let n=1;for(;n<i&&r(e[n]);)n++;let s=!1;for(e[n]==="/"&&(s=!0,n++);n<i&&r(e[n]);)n++;let f="system-reminder";if(e.slice(n,n+f.length)===f){if(n+=f.length,n<i-1&&r(e[n])){for(;n<i&&r(e[n]);)n++;for(;n<i&&e[n]!==">";)n++}for(;n<i&&r(e[n]);)n++;for(e[n]==="/"&&n++;n<i&&r(e[n]);)n++;if(!(n!==i-1||e[n]!==">"))return s?"closing":"other"}}function g(t){let e=d(t);return e==="closing"?"<\\/system-reminder>":e==="other"?l(t):t}function u(t){return t.replace(c,g)}export{l as a,u as b};
3
+ import{b as o}from"./chunk-GZPNIYVZ.js";o();function x(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var c=/<[^<>]*>/g;function r(t){return t!==void 0&&/\s/.test(t)}function d(t){let e=t.codePointAt(0);return e===void 0?!1:e===173||e===1564||e===12644||e===65279||e===65440||e>=0&&e<=31||e>=127&&e<=159||e>=4447&&e<=4448||e>=6068&&e<=6069||e>=6155&&e<=6159||e>=8203&&e<=8207||e>=8234&&e<=8238||e>=8288&&e<=8303||e>=65024&&e<=65039||e>=65520&&e<=65528||e>=113824&&e<=113827||e>=119155&&e<=119162||e>=917504&&e<=921599}function l(t){let e="";for(let i of t)d(i)||(e+=i);return e.toLowerCase()}function u(t){let e=l(t),i=e.length;if(i<2||e[0]!=="<"||e[i-1]!==">")return;let n=1;for(;n<i&&r(e[n]);)n++;let s=!1;for(e[n]==="/"&&(s=!0,n++);n<i&&r(e[n]);)n++;let f="system-reminder";if(e.slice(n,n+f.length)===f){if(n+=f.length,n<i-1&&r(e[n])){for(;n<i&&r(e[n]);)n++;for(;n<i&&e[n]!==">";)n++}for(;n<i&&r(e[n]);)n++;for(e[n]==="/"&&n++;n<i&&r(e[n]);)n++;if(!(n!==i-1||e[n]!==">"))return s?"closing":"other"}}function m(t){let e=u(t);return e==="closing"?"<\\/system-reminder>":e==="other"?x(t):t}function a(t){return t.replace(c,m)}function p(t){return Array.isArray(t)?t.map(g):g(t)}function g(t){return typeof t=="string"?a(t):t.text===void 0?t:{...t,text:a(t.text)}}export{x as a,a as b,p as c};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Matilda
@@ -0,0 +1,9 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{e as g}from"./chunk-ZX34M2GF.js";import{b as h}from"./chunk-7ZODGQO6.js";import{b as M}from"./chunk-TISQNFB5.js";import{c as w}from"./chunk-LUNDTQ3G.js";import{b as c,ba as b}from"./chunk-27Q5KW3A.js";import{b as p}from"./chunk-GZPNIYVZ.js";import{f as E}from"./chunk-OWGSC52X.js";p();var m=null;function D(e){m=e}function _(){return m}function P(){m=null}function S(e,r,o){return m?(m.enqueueApproval({teammateName:e,teammateColor:r,details:o}),!0):!1}function $(e,r,o,t){return{...e,title:`[${r}] ${e.title}`,onConfirm:async(i,s)=>{await o(i,s)}}}p();var C=E(h(),1);import*as a from"node:fs/promises";import*as u from"node:path";var y=b("AGENTS_TEAM_MAILBOX"),N={retries:{retries:10,minTimeout:5,maxTimeout:100,factor:2,randomize:!0},stale:5e3,onCompromised:e=>{y.debug("mailbox lock compromised:",e?.message??e)}},d=new Map;function O(e){let r=d.get(e);return r||(r=new M,d.set(e,r)),r}function I(e){let r=g(e),o=0;for(let t of d.keys())u.dirname(t)===r&&(d.delete(t),o++);return o}async function T(e,r){return O(e).runExclusive(async()=>{let o=await C.default.lock(e,N);try{return await r()}finally{await o()}})}function x(e,r){return u.join(g(e),`${r}.json`)}async function X(e,r){let o=x(e,r);try{let t=await a.readFile(o,"utf-8");return JSON.parse(t)}catch(t){if(c(t)&&t.code==="ENOENT")return[];throw t}}var L=5*60*1e3;async function A(e,r,o){let t=x(e,r);await v(t),await T(t,async()=>{let i=await k(t),s=Date.now()-L,l=i.filter(f=>{if(!f.read)return!0;let n=Date.parse(f.timestamp);return Number.isNaN(n)||n>=s});l.push(o),await w(t,l)})}async function z(e,r,o){let t=x(e,r);return await v(t),T(t,async()=>{let i=await k(t),s=n=>!n.read&&(o===void 0||n.type===o),l=i.filter(s);if(l.length===0)return[];let f=i.map(n=>s(n)?{...n,read:!0}:n);return await w(t,f),l})}async function G(e,r){let o=x(e,r);try{await a.unlink(o)}catch(t){if(!c(t)||t.code!=="ENOENT")throw t}}async function K(e){let r=g(e);await a.rm(r,{recursive:!0,force:!0}),I(e)}async function Q(e,r,o){await A(e,r,{from:o.from,text:o.text,timestamp:new Date().toISOString(),read:!1,type:o.type,color:o.color,summary:o.summary})}async function v(e){await a.mkdir(u.dirname(e),{recursive:!0});try{await a.writeFile(e,`[]
4
+ `,{flag:"wx"})}catch(r){if(!c(r)||r.code!=="EEXIST")throw r}}async function k(e){try{let r=await a.readFile(e,"utf-8");return JSON.parse(r)}catch(r){if(c(r)&&r.code==="ENOENT")return[];let o=r instanceof Error?r.message:String(r);y.warn(`Quarantining corrupt inbox at ${e}: ${o}`);try{await a.rename(e,`${e}.corrupt-${Date.now()}`)}catch(t){let i=t instanceof Error?t.message:String(t);throw y.warn(`Failed to quarantine ${e}: ${i}`),r instanceof Error?r:new Error(`Failed to read inbox at ${e}: ${o}`)}return[]}}export{D as a,_ as b,P as c,S as d,$ as e,I as f,x as g,X as h,A as i,z as j,G as k,K as l,Q as m};
5
+ /**
6
+ * @license
7
+ * Copyright 2025 Matilda
8
+ * SPDX-License-Identifier: Apache-2.0
9
+ */
@@ -0,0 +1,14 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{l as f,m as h,n as T,o as w,p as x,q as s}from"./chunk-QKYGQLWC.js";import{c as g}from"./chunk-LUNDTQ3G.js";import{Q as c,b as p}from"./chunk-27Q5KW3A.js";import{b as o}from"./chunk-GZPNIYVZ.js";o();function y(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}o();import*as n from"node:fs/promises";import*as a from"node:path";function M(){return a.join(c.getGlobalMatildaDir(),h)}function d(e){return a.join(M(),e)}function l(e){return a.join(d(e),w)}function I(e){return a.join(d(e),x)}function E(e){return a.join(c.getGlobalMatildaDir(),T,e)}function m(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function j(e,t){return`${m(e)}@${m(t)}`}function R(e,t){let r=m(e);if(!r)throw new Error(`Teammate name "${e}" sanitizes to an empty string. Choose a name with at least one alphanumeric character.`);if(r===f)throw new Error(`"${f}" is reserved for the team leader. Choose a different teammate name.`);let i=new Set(t.map(u=>u.name));if(i.has(r)){let u=[...i].join(", ")||"<none>";throw new Error(`A teammate named "${r}" already exists in this team (existing: ${u}). Choose a different name.`)}return r}function C(e){let t=new Set(e.map(r=>r.color).filter(r=>r!==void 0));for(let r of s)if(!t.has(r))return r;return s[e.length%s.length]}function O(e){return e.map(t=>{let{color:r,...i}=t;return i})}function $(e,t,r){return e.map(i=>i.agentId===t?{...i,isActive:r}:i)}function k(e,t){return e.find(r=>r.agentId===t)}function z(e,t){let r=m(t);return e.find(i=>i.name===r)}function L(e){let t=e.trimStart();if(/^shutdown_approved\b/i.test(t))return"shutdown_approved";if(/^shutdown_rejected\b/i.test(t))return"shutdown_rejected"}async function P(e){let t=l(e);try{let r=await n.readFile(t,"utf-8");return JSON.parse(r)}catch(r){if(p(r)&&r.code==="ENOENT")return;throw r}}async function J(e,t){let r=l(e);await n.mkdir(a.dirname(r),{recursive:!0}),await g(r,t)}async function B(e,t){let r=l(e);await n.mkdir(a.dirname(r),{recursive:!0}),await n.writeFile(r,JSON.stringify(t,null,2)+`
4
+ `,{encoding:"utf-8",flag:"wx"})}async function G(e){let t;try{t=await P(e)}catch{return!1}return t?typeof t.leadPid!="number"||t.leadPid<=0||t.leadPid!==process.pid&&y(t.leadPid)?!1:(await b(e),!0):(await b(e),!0)}async function b(e){let t=d(e),r=E(e);await Promise.allSettled([n.rm(t,{recursive:!0,force:!0}),n.rm(r,{recursive:!0,force:!0})])}async function q(){let e=M();try{return(await n.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}export{y as a,M as b,d as c,l as d,I as e,E as f,m as g,j as h,R as i,C as j,O as k,$ as l,k as m,z as n,L as o,P as p,J as q,B as r,G as s,b as t,q as u};
5
+ /**
6
+ * @license
7
+ * Copyright 2026 Matilda
8
+ * SPDX-License-Identifier: Apache-2.0
9
+ */
10
+ /**
11
+ * @license
12
+ * Copyright 2025 Matilda
13
+ * SPDX-License-Identifier: Apache-2.0
14
+ */