@maincode-ai/matilda-code 0.21.11 → 0.21.12

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 (123) hide show
  1. package/bundled/mainy/docs/configuration/settings.md +16 -5
  2. package/bundled/mainy/docs/configuration/trusted-folders.md +12 -6
  3. package/chunks/agent-WM63A6NK.js +3 -0
  4. package/chunks/agent-headless-QIUBDKPW.js +3 -0
  5. package/chunks/{anthropicContentGenerator-IYZILRDW.js → anthropicContentGenerator-VKFTAIU3.js} +1 -1
  6. package/chunks/{askUserQuestion-XWHJY3DM.js → askUserQuestion-2QI4NSFJ.js} +1 -1
  7. package/chunks/{ca-EUJBUYX5.js → ca-I2HEEIL7.js} +1 -1
  8. package/chunks/{chunk-MH2P4YXC.js → chunk-27Q5KW3A.js} +2 -2
  9. package/chunks/{chunk-NYEWHSBL.js → chunk-2HTPVSGT.js} +1 -1
  10. package/chunks/{chunk-2HQMJ2IU.js → chunk-2MOGYHWM.js} +1 -1
  11. package/chunks/{chunk-WRQLIPXW.js → chunk-3IRGBRSP.js} +10 -10
  12. package/chunks/{chunk-NIQK6NX3.js → chunk-5C2RJ5RR.js} +1 -1
  13. package/chunks/{chunk-T4P4KEDW.js → chunk-6E766NPX.js} +1 -1
  14. package/chunks/{chunk-QH7736R5.js → chunk-6EQMZNIY.js} +1 -1
  15. package/chunks/{chunk-4FVBPNTZ.js → chunk-6T2GIM76.js} +1 -1
  16. package/chunks/{chunk-25NCTG5H.js → chunk-6Z2MV7ZY.js} +55 -53
  17. package/chunks/chunk-BVOCFLC4.js +56 -0
  18. package/chunks/chunk-CSJTA7NE.js +101 -0
  19. package/chunks/{chunk-SNLH42QJ.js → chunk-CZGZ3KK7.js} +1 -1
  20. package/chunks/{chunk-JXUDKX6D.js → chunk-DE3HKC2W.js} +1 -1
  21. package/chunks/{chunk-4CSSDBOS.js → chunk-DOOFGSRV.js} +10 -10
  22. package/chunks/{chunk-RK2AKQAX.js → chunk-FPO57O66.js} +6 -6
  23. package/chunks/{chunk-ODZOYHIC.js → chunk-GOJCMVJJ.js} +1 -1
  24. package/chunks/{chunk-FFFZ2QMG.js → chunk-GTVCJCHR.js} +1 -1
  25. package/chunks/{chunk-SUH3UUWZ.js → chunk-JCE3JAVC.js} +1 -1
  26. package/chunks/chunk-JRECUFB3.js +2630 -0
  27. package/chunks/chunk-KHHJYBR5.js +9 -0
  28. package/chunks/{chunk-GO2GA2GY.js → chunk-LUNDTQ3G.js} +1 -1
  29. package/chunks/{chunk-5427BPR2.js → chunk-MCQUPLRE.js} +1 -1
  30. package/chunks/{chunk-QN6WSWMM.js → chunk-MO2HXJG5.js} +1 -1
  31. package/chunks/{chunk-ELH4YHJR.js → chunk-PGXQZVLX.js} +1 -1
  32. package/chunks/{chunk-Q55AVE2N.js → chunk-QVCGLQCI.js} +11 -11
  33. package/chunks/{chunk-W5CGKUM4.js → chunk-S3CWEVTS.js} +1 -1
  34. package/chunks/{chunk-YMIF2DMT.js → chunk-VTGICC67.js} +1 -1
  35. package/chunks/chunk-WC2VTVCE.js +27 -0
  36. package/chunks/{chunk-SPW5DXX4.js → chunk-WV3IUPZS.js} +1 -1
  37. package/chunks/{chunk-4YVN5HXG.js → chunk-YJAKOETP.js} +2 -2
  38. package/chunks/{chunk-WHG6N5X2.js → chunk-YRQP3SLC.js} +1 -1
  39. package/chunks/{chunk-GUFIMKF5.js → chunk-YV3PUOBU.js} +1 -1
  40. package/chunks/{computer-use-SXP25RZQ.js → computer-use-WKDNUTLD.js} +1 -1
  41. package/chunks/contextCommand-DAB3HOHY.js +3 -0
  42. package/chunks/{cron-create-2UI4AT4Q.js → cron-create-F2LXM2OA.js} +1 -1
  43. package/chunks/{cron-delete-ZB6BOTFF.js → cron-delete-DE6Q2S2L.js} +1 -1
  44. package/chunks/{cron-list-YYAXNHB6.js → cron-list-IAQEJVV7.js} +1 -1
  45. package/chunks/{de-DNEPG7S7.js → de-AQXFJYZI.js} +1 -1
  46. package/chunks/edit-QQNJZ55P.js +43 -0
  47. package/chunks/{en-NOD6KQNM.js → en-EJLDYIBM.js} +1 -1
  48. package/chunks/{enter-worktree-X47BSJLE.js → enter-worktree-5X5SAMBJ.js} +1 -1
  49. package/chunks/{enterPlanMode-F22ZNTYJ.js → enterPlanMode-HP35SPLN.js} +1 -1
  50. package/chunks/{exit-worktree-XY5UMDHX.js → exit-worktree-SRKZBEYF.js} +1 -1
  51. package/chunks/exitPlanMode-WSPTGGVN.js +120 -0
  52. package/chunks/{fr-2OE5WLJ4.js → fr-6TDHK7F2.js} +1 -1
  53. package/chunks/{geminiContentGenerator-EQEGOXOV.js → geminiContentGenerator-RJ73DQAP.js} +1 -1
  54. package/chunks/{glob-KSBEWI3E.js → glob-QQ6LGKDX.js} +1 -1
  55. package/chunks/{goal-tools-6QTC3UI7.js → goal-tools-C6BSBHCF.js} +1 -1
  56. package/chunks/{grep-6TTPZ524.js → grep-MVCOBUYW.js} +1 -1
  57. package/chunks/{ja-3B6V5KS7.js → ja-GGNJR7AR.js} +1 -1
  58. package/chunks/{keychain-token-storage-54BNK6VH.js → keychain-token-storage-KQK6MNOJ.js} +1 -1
  59. package/chunks/{ls-YWZU3FYL.js → ls-JYJXFSXN.js} +1 -1
  60. package/chunks/{lsp-4CJDKEEC.js → lsp-DYDK6XCS.js} +1 -1
  61. package/chunks/{matildaAgentContentGenerator-OV4U6DJD.js → matildaAgentContentGenerator-YUYS4336.js} +1 -1
  62. package/chunks/{matildaContentGenerator-ETIAWE22.js → matildaContentGenerator-O4Z2QPCP.js} +1 -1
  63. package/chunks/{matildaOAuth2-WOY7ZS43.js → matildaOAuth2-7COTQQR2.js} +1 -1
  64. package/chunks/mcp-client-RXVQU5VI.js +3 -0
  65. package/chunks/monitor-77KXDXPR.js +32 -0
  66. package/chunks/{notebook-edit-TL7CI5EA.js → notebook-edit-TKJD2EQZ.js} +1 -1
  67. package/chunks/{openaiContentGenerator-MGASUFQL.js → openaiContentGenerator-2EALAM3U.js} +1 -1
  68. package/chunks/{pt-KP2JCPUY.js → pt-D6L2QTDM.js} +1 -1
  69. package/chunks/read-file-3KUAH6ND.js +3 -0
  70. package/chunks/ripGrep-U2PLKXMY.js +3 -0
  71. package/chunks/{ru-K7IQQKHC.js → ru-BNJCHDYO.js} +1 -1
  72. package/chunks/{scheduler-TKWPD4LP.js → scheduler-J7VU2V5Y.js} +1 -1
  73. package/chunks/{send-message-OO2HAKCC.js → send-message-P3SMWNEE.js} +1 -1
  74. package/chunks/{serve-ZQX2WBLF.js → serve-FXH6EBQ6.js} +36 -36
  75. package/chunks/shell-PXR2AXDD.js +3 -0
  76. package/chunks/{skill-KDM3UUML.js → skill-HZPFEAPF.js} +1 -1
  77. package/chunks/src-RFAEPLY7.js +3 -0
  78. package/chunks/{symbol-search-ALYOX5JN.js → symbol-search-EAIZPWN7.js} +1 -1
  79. package/chunks/{syntheticOutput-UASKABJH.js → syntheticOutput-432LXITX.js} +1 -1
  80. package/chunks/task-create-Z3QRCMX4.js +3 -0
  81. package/chunks/{task-detach-I67ZE5MX.js → task-detach-XMSJ3HBM.js} +1 -1
  82. package/chunks/{task-list-5BGX4G5N.js → task-list-GXAJW3JP.js} +1 -1
  83. package/chunks/{task-stop-ERI5X4AO.js → task-stop-NTS62FLG.js} +1 -1
  84. package/chunks/{task-update-CD3W556L.js → task-update-AR26UFYZ.js} +1 -1
  85. package/chunks/{team-create-F4KQRGMB.js → team-create-PYXFVIR5.js} +1 -1
  86. package/chunks/{team-delete-5U3GBFKJ.js → team-delete-OMYVUAQU.js} +1 -1
  87. package/chunks/todoWrite-5NZ7CHTC.js +3 -0
  88. package/chunks/{tool-search-JFCD5W5M.js → tool-search-RKZDSRYS.js} +1 -1
  89. package/chunks/tree-sitter-bash-2SWKO5B7.js +3 -0
  90. package/chunks/{web-fetch-REWGIRWQ.js → web-fetch-VW3SVDQ6.js} +13 -13
  91. package/chunks/{web-search-OX2DPEVN.js → web-search-XQUIZARL.js} +1 -1
  92. package/chunks/{workflow-SEFYGBED.js → workflow-YXNXDRWZ.js} +2 -2
  93. package/chunks/{write-file-UAGVBZMC.js → write-file-XDDLTGSG.js} +1 -1
  94. package/cli.js +459 -449
  95. package/locales/ca.js +1 -0
  96. package/locales/de.js +1 -0
  97. package/locales/en.js +1 -0
  98. package/locales/fr.js +1 -0
  99. package/locales/ja.js +1 -0
  100. package/locales/pt.js +1 -0
  101. package/locales/ru.js +1 -0
  102. package/package.json +2 -2
  103. package/sandbox-macos-restrictive-closed.sb +3 -0
  104. package/sandbox-macos-restrictive-open.sb +3 -0
  105. package/sandbox-macos-restrictive-proxied.sb +3 -0
  106. package/chunks/agent-ZFZ4HJQC.js +0 -3
  107. package/chunks/agent-headless-KH2BKLP7.js +0 -3
  108. package/chunks/chunk-GHBKFIHC.js +0 -35
  109. package/chunks/chunk-HWOQNYAO.js +0 -27
  110. package/chunks/chunk-NVM7W7TG.js +0 -101
  111. package/chunks/chunk-QFNFLE2I.js +0 -2625
  112. package/chunks/chunk-XCFLI3OC.js +0 -9
  113. package/chunks/contextCommand-3GN5CAOK.js +0 -3
  114. package/chunks/edit-KX6V4PH3.js +0 -39
  115. package/chunks/exitPlanMode-G3QLIWJ4.js +0 -90
  116. package/chunks/monitor-F4K5HOZX.js +0 -32
  117. package/chunks/read-file-6EAPS2KG.js +0 -3
  118. package/chunks/ripGrep-K6SFFUIE.js +0 -3
  119. package/chunks/shell-AZRK5GIO.js +0 -3
  120. package/chunks/src-SGI6VLOS.js +0 -3
  121. package/chunks/task-create-EBJD55TB.js +0 -3
  122. package/chunks/todoWrite-YGG6AZ3A.js +0 -3
  123. package/chunks/tree-sitter-bash-XNCMPQBK.js +0 -3
@@ -1,16 +1,16 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as sn,b as St,c as an,d as ln}from"./chunk-DC7LAFZZ.js";import{a as q,d as on}from"./chunk-4F4DA5UI.js";import{b as Xt,d as Qt,g as Et,j as Zt,k as en,s as rn,v as pe}from"./chunk-SUH3UUWZ.js";import{b as A,e as V}from"./chunk-4J6DC24J.js";import{a as tn,d as nn}from"./chunk-SDTWBD62.js";import{Bb as ue,Mb as mt,Nc as Tt,Oc as yt,Pa as Io,Pb as ht,Qc as At,Ra as Oo,Rb as Ct,Sa as Q,Wa as ke,Xa as Ie,Ya as Oe,a as M,ab as gt,eb as we,f as F,fb as B,na as ft,tb as Pe,ub as De}from"./chunk-25NCTG5H.js";import{b as dn}from"./chunk-3YLXGE6T.js";import{Q as ve,U as Jt,W as pt,ba as O,c as zt,d as Wt,e as U,f as de,k as dt}from"./chunk-MH2P4YXC.js";import{b as ct,c as b,f as ut,g as ce,h as _,i as xe,k as Yt,l as x,n as X}from"./chunk-FWDMPRKU.js";import{b as f}from"./chunk-GZPNIYVZ.js";import{f as ko}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 wo(e){return e.total&&e.total>0?Math.max(e.total,(e.prompt||0)+Le(e)):(e.prompt||0)+Le(e)}function Po(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 Do=/[A-Za-z\u00C0-\u024F]/g;function Lo(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&&Lo(t)}function No(e){let t=e.match(Do)?.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||!No(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>"],Uo=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>Uo?!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 cn(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)`),cn(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`),cn(r))}};function un(e){return new _t().parse(e,!0)}var P=O("CONVERTER"),Tn="(attached media from previous tool call)";function yn(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,u=Math.max(0,t.estimatedReasoningTokens??0),d=Math.max(0,t.estimatedContentTokens??0),p=l>0?l:u,c=o;p>0&&(o>=p?c=o:c=o+p),(d>0||u>0)&&(c=Math.max(c,d+(l>0?0:u),d+p)),r>n&&(n>0||o>0||p>0)&&(c=Math.max(c,r-n)),p===0&&u>0&&(p=u),p>c&&(p=c);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||c>0)||g>0&&m>0&&g<m+c)&&(g=m+c),{promptTokenCount:m,candidatesTokenCount:c,totalTokenCount:g,cachedContentTokenCount:s,thoughtsTokenCount:p,...h?{usageIsIncomplete:!0}:{}}}var Fo=64,pn=1024;function fn(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)?(P.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${t.emittedText.length}b, chunk=${e.length}b)`),""):(P.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>=pn&&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,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${e.length}b)`),i}}return e===t.emittedText?e.length>=Fo?(t.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${e.length}b)`),""):(t.emittedLength+=e.length,e):(t.emittedText.length<pn&&(t.emittedText+=e),t.emittedLength+=e.length,e)}function An(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 Go(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=An(i.parameters)),s&&(s=Qt(s,t)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function Ko(e,t,n={cleanOrphanToolCalls:!0}){let o=[];return jo(e,o),Ho(e.contents,o,t),o=Cn(o),n.cleanOrphanToolCalls&&(o=Zo(o),o=Cn(o)),o}function $o(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},u=r.join("");u&&(l.reasoning_content=u),s.length>0&&(l.tool_calls=s);let d=Qo(n?.finishReason),p=e.usageMetadata,c={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(c.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:c}}function jo(e,t){if(!e.config?.systemInstruction)return;let n=Sn(e.config.systemInstruction);n&&t.push({role:"system",content:n})}function Ho(e,t,n){if(Array.isArray(e))for(let o of e)gn(o,t,n);else e&&gn(e,t,n)}function gn(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,u=new Set,d=new Set,p=[];for(let c of o){if(typeof c=="string"){i.push({type:"text",text:c});continue}"text"in c&&"thought"in c&&c.thought&&r==="assistant"&&c.text&&s.push(c.text),"text"in c&&c.text&&!("thought"in c&&c.thought)&&i.push({type:"text",text:c.text});let h=En(c,n);if(h&&r==="user"&&i.push(h),"functionCall"in c&&c.functionCall&&r==="assistant"){let m=c.functionCall.id;if(m){if(u.has(m)){P.debug(`Dropping duplicate functionCall id=${m} while converting content`);continue}u.add(m)}a.push({id:m||`call_${l}`,type:"function",function:{name:c.functionCall.name||"",arguments:JSON.stringify(c.functionCall.args||{})}}),l+=1}if(c.functionResponse&&r==="user"){let m=c.functionResponse.id;if(m){if(d.has(m))continue;d.add(m)}let g=Bo(c.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:Tn},...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 Vo(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 Bo(e,t){let n=Vo(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=En(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 En(e,t){let{modalities:n}=t;if(e.inlineData?.mimeType&&e.inlineData?.data){let o=e.inlineData.mimeType,r=mn(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=mn(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){P.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 mn(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 Sn(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>Sn(t)).filter(Boolean).join(`
3
+ import{a as an,b as St,c as ln,d as dn}from"./chunk-DC7LAFZZ.js";import{a as q,d as rn}from"./chunk-4F4DA5UI.js";import{b as Xt}from"./chunk-3YLXGE6T.js";import{b as Qt,d as Zt,g as Et,j as en,k as tn,s as sn,v as pe}from"./chunk-JCE3JAVC.js";import{b as A,e as V}from"./chunk-4J6DC24J.js";import{a as nn,d as on}from"./chunk-SDTWBD62.js";import{Cb as ue,Nb as mt,Nc as Tt,Oc as yt,Qa as wo,Qb as ht,Qc as At,Sa as Po,Sb as Ct,Ta as Q,Xa as ke,Ya as Ie,Za as Oe,a as M,bb as gt,f as F,fb as we,gb as B,oa as ft,ub as Pe,vb as De}from"./chunk-6Z2MV7ZY.js";import{Q as ve,U as Jt,W as pt,ba as w,c as zt,d as Wt,e as U,f as de,k as dt}from"./chunk-27Q5KW3A.js";import{b as ct,c as b,f as ut,g as ce,h as _,i as xe,k as Yt,l as k,n as X}from"./chunk-FWDMPRKU.js";import{b as f}from"./chunk-GZPNIYVZ.js";import{f as Oo}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 Do(e){return e.total&&e.total>0?Math.max(e.total,(e.prompt||0)+Le(e)):(e.prompt||0)+Le(e)}function Lo(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 No=/[A-Za-z\u00C0-\u024F]/g;function Uo(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&&Uo(t)}function Fo(e){let t=e.match(No)?.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||!Fo(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=w("TAGGED_THINKING_PARSER"),ge=["<think>","<thinking>"],me=["</think>","</thinking>"],Go=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>Go?!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 cn(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)`),cn(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`),cn(r))}};function un(e){return new _t().parse(e,!0)}var P=w("CONVERTER"),Tn="(attached media from previous tool call)";function yn(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,u=Math.max(0,t.estimatedReasoningTokens??0),d=Math.max(0,t.estimatedContentTokens??0),p=l>0?l:u,c=o;p>0&&(o>=p?c=o:c=o+p),(d>0||u>0)&&(c=Math.max(c,d+(l>0?0:u),d+p)),r>n&&(n>0||o>0||p>0)&&(c=Math.max(c,r-n)),p===0&&u>0&&(p=u),p>c&&(p=c);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||c>0)||g>0&&m>0&&g<m+c)&&(g=m+c),{promptTokenCount:m,candidatesTokenCount:c,totalTokenCount:g,cachedContentTokenCount:s,thoughtsTokenCount:p,...h?{usageIsIncomplete:!0}:{}}}var Ko=64,pn=1024;function fn(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)?(P.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${t.emittedText.length}b, chunk=${e.length}b)`),""):(P.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>=pn&&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,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${e.length}b)`),i}}return e===t.emittedText?e.length>=Ko?(t.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${e.length}b)`),""):(t.emittedLength+=e.length,e):(t.emittedText.length<pn&&(t.emittedText+=e),t.emittedLength+=e.length,e)}function An(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 $o(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=An(i.parameters)),s&&(s=Zt(s,t)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function jo(e,t,n={cleanOrphanToolCalls:!0}){let o=[];return Vo(e,o),Bo(e.contents,o,t),o=Cn(o),n.cleanOrphanToolCalls&&(o=tr(o),o=Cn(o)),o}function Ho(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},u=r.join("");u&&(l.reasoning_content=u),s.length>0&&(l.tool_calls=s);let d=er(n?.finishReason),p=e.usageMetadata,c={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(c.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:c}}function Vo(e,t){if(!e.config?.systemInstruction)return;let n=Sn(e.config.systemInstruction);n&&t.push({role:"system",content:n})}function Bo(e,t,n){if(Array.isArray(e))for(let o of e)gn(o,t,n);else e&&gn(e,t,n)}function gn(e,t,n){if(typeof e=="string"){t.push({role:"user",content:e});return}if(!Yo(e))return;let o=e.parts||[],r=e.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,u=new Set,d=new Set,p=[];for(let c of o){if(typeof c=="string"){i.push({type:"text",text:c});continue}"text"in c&&"thought"in c&&c.thought&&r==="assistant"&&c.text&&s.push(c.text),"text"in c&&c.text&&!("thought"in c&&c.thought)&&i.push({type:"text",text:c.text});let h=En(c,n);if(h&&r==="user"&&i.push(h),"functionCall"in c&&c.functionCall&&r==="assistant"){let m=c.functionCall.id;if(m){if(u.has(m)){P.debug(`Dropping duplicate functionCall id=${m} while converting content`);continue}u.add(m)}a.push({id:m||`call_${l}`,type:"function",function:{name:c.functionCall.name||"",arguments:JSON.stringify(c.functionCall.args||{})}}),l+=1}if(c.functionResponse&&r==="user"){let m=c.functionResponse.id;if(m){if(d.has(m))continue;d.add(m)}let g=zo(c.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:Tn},...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 qo(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 zo(e,t){let n=qo(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=En(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 En(e,t){let{modalities:n}=t;if(e.inlineData?.mimeType&&e.inlineData?.data){let o=e.inlineData.mimeType,r=mn(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=Wo(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=mn(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){P.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 mn(e){return e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":e.startsWith("video/")?"video":"file"}function Wo(e){return e.includes("wav")?"wav":e.includes("mp3")||e.includes("mpeg")?"mp3":null}function Yo(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&Array.isArray(e.parts)}function Sn(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>Sn(t)).filter(Boolean).join(`
6
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 un(e);if(!e)return[];let o=Ne(Rt(e));return o?[{text:o}]:[]}function Wo(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=Xt(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:Mn(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=yn(e.usage,{estimatedReasoningTokens:Z(i.length),estimatedContentTokens:Z(s.length)})}return o}function Yo(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 u=n.delta?.reasoning_content??n.delta?.reasoning;if(u){let d=fn(u,t.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});d&&i.push({text:d,thought:!0})}}if(typeof n.delta?.content=="string"){let u=fn(n.delta.content,t.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(u||n.finish_reason)&&i.push(...Ge(u,t,!!n.finish_reason))}else n.finish_reason&&i.push(...Ge("",t,!0));if(n.delta?.tool_calls)for(let u of n.delta.tool_calls){let d=u.index??0;u.function?.arguments?r.addChunk(d,u.function.arguments,u.id,u.function.name):r.addChunk(d,"",u.id,u.function?.name)}let s=!1;if(n.finish_reason){s=r.hasIncompleteToolCalls();let u=r.getCompletedToolCalls();for(let d of u)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=Mn(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=yn(e.usage,Xo(t))),o}function Jo(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 Xo(e){return{estimatedReasoningTokens:Z(e.reasoningDeltaState?.emittedLength??0),estimatedContentTokens:Z(e.textDeltaState?.emittedLength??0)}}function Mn(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 Qo(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 hn(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===Tn}function Zo(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 u=[],d=new Set;for(let C of l.tool_calls){let T=C.id;!T||s.has(T)||d.has(T)||(d.add(T),u.push(C))}let p=new Set,c=[],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),c.push(C),m=!0):m=!1;continue}if(hn(T)){m&&h.push(C);continue}if(!(T.role==="assistant"&&!bt(T)))break}let g=u.filter(C=>p.has(C.id));for(let C of g)s.add(C.id);n.set(a,g),o.set(a,c),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 u=l.reasoning_content,d=n.get(a)??[];if(d.length>0){let p={...l};p.tool_calls=d,t.push(p);for(let c of o.get(a)??[]){let h=e[c];h&&(t.push(h),i.add(c))}for(let c of r.get(a)??[]){let h=e[c];h&&(t.push(h),i.add(c))}}else if(typeof l.content=="string"&&l.content.trim()||u){let p={...l};delete p.tool_calls,t.push(p)}else P.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?P.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):hn(l)?P.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):t.push(l)}return t}function Cn(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),u;if(l){let p=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[],c=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[];u=[...p,...c]}else u=[typeof s=="string"?s:"",typeof a=="string"?a:""].filter(Boolean).join("")||null;let d=[...r,...i];o.content=u||null,d.length>0&&(o.tool_calls=d);continue}}t.push(n)}return t}var Ke={convertGeminiToolParametersToOpenAI:An,convertGeminiToolsToOpenAI:Go,convertGeminiRequestToOpenAI:Ko,convertGeminiResponseToOpenAI:$o,convertOpenAIResponseToGemini:Wo,convertOpenAIChunkToGemini:Yo,flushOpenAIStreamToGemini:Jo};f();import*as I from"node:path";import{promises as He}from"node:fs";f();f();import er from"crypto";var je=new Uint8Array(256),$e=je.length;function vt(){return $e>je.length-16&&(er.randomFillSync(je),$e=0),je.slice($e,$e+=16)}f();var S=[];for(let e=0;e<256;++e)S.push((e+256).toString(16).slice(1));function _n(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 tr from"crypto";var xt={randomUUID:tr.randomUUID};function nr(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 _n(o)}var kt=nr;import*as G from"os";var Ve=O("OPENAI_LOGGER"),or="########",rr=/^[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 ir(e,t){let n=t||process.cwd();if(!e)return I.join(n,"logs","openai");let o=e;return e==="~"||e.startsWith("~/")?o=I.join(G.homedir(),e.slice(1)):I.isAbsolute(e)||(o=I.resolve(n,e)),I.normalize(o)}function Rn(e){return e&&e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function sr(e){let t=e.split("#");if(t.length!==3)return;let[,n,o]=t;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function ar(e){if(e)return Q(e)?Rn(e):Rn(sr(e))}function lr(e){if(!e)return;let t=e.indexOf(or);if(t>0)return e.slice(0,t);if(rr.test(e))return e;let n=e.split("#");if(n.length>=3&&n[0])return n[0]}function dr(e){let t=e?.trim(),n=lr(t);return!t&&!n?null:{...t?{promptId:t}:{},...n?{sessionId:n}:{}}}var he=class{logDir;initialized=!1;constructor(t,n){this.logDir=ir(t,n)}async initialize(){if(!this.initialized)try{await He.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=ar(r),l=a?`openai-${i}-${s}-${a}.json`:`openai-${i}-${s}.json`,u=I.join(this.logDir,l),d={timestamp:new Date().toISOString(),request:t,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:dr(r),system:{hostname:G.hostname(),platform:G.platform(),release:G.release(),nodeVersion:process.version}};try{return await He.writeFile(u,JSON.stringify(d,null,2),"utf-8"),u}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 He.readdir(this.logDir)).filter(r=>r.startsWith("openai-")&&r.endsWith(".json")).map(r=>I.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 He.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}`)}}},Aa=new he;f();f();X();Oo();f();X();var bn=ko(Io(),1);import{createHash as cr}from"node:crypto";var te="matilda.telemetry.traceparent",Be="matilda.telemetry.tracestate",ur="matilda-code.daemon.request",vn="matilda-code.daemon.bridge",pr="matilda-code.daemon.error";function fr(e){return e instanceof Error?e.message:String(e)}function gr(e){return e instanceof Error?e.name||"Error":typeof e}var mr="0".repeat(32),hr="0".repeat(16);function Cr(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 Tr(e){return cr("sha256").update(e).digest("hex").slice(0,16)}async function It(e,t,n,o={}){if(!ue())return await n(void 0);let r=o.autoOkOnSuccess??!0;return await x.getTracer(M).startActiveSpan(e,{kind:ut.INTERNAL,attributes:t},async s=>{try{let a=await n(s);return r&&s.setStatus({code:ce.OK}),a}catch(a){throw kn(s,a),a}finally{s.end()}})}async function yr(e,t){return await It(ur,{"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 xn(e,t,n){return await It(vn,{"matilda-code.daemon.operation":e,...t},async()=>await n())}function Ar(e,t){try{e?.setAttribute("http.response.status_code",t)}catch{}}function Er(e,t){try{x.getSpan(_.active())?.setAttribute(e,t)}catch{}}function kn(e,t,n={}){let o=e??x.getSpan(_.active());if(o)try{let r=gt(fr(t));o.recordException(t instanceof Error?t:new Error(r)),o.setAttributes({"error.type":gr(t),"error.message":r,...n}),o.setStatus({code:ce.ERROR,message:r})}catch{}}function Sr(e,t={},n){if(ue())try{bn.logs.getLogger(M).emit({body:e,timestamp:new Date,attributes:{"event.name":n?.eventName??pr,...t},...n?.severityNumber!=null?{severityNumber:n.severityNumber}:{}})}catch{}}function In(){return{context:_.active()}}async function On(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 wn(e){let t=e._meta,n=Cr(t);try{let o=Jt();o&&(n[te]=pt(o))}catch{}return!t&&!n[te]?e:{...e,_meta:n}}function Mr(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=Yt.extract(ct,r);if(x.getSpanContext(s))return s;let a=o.split("-"),l=a[1],u=a[2],d=a[3];if(!(a[0]!=="00"||!l?.match(/^[0-9a-f]{32}$/)||!u?.match(/^[0-9a-f]{16}$/)||!d?.match(/^[0-9a-f]{2}$/)||l===mr||u===hr))return x.setSpan(ct,x.wrapSpanContext({traceId:l,spanId:u,traceFlags:Number.parseInt(d,16),isRemote:!0}))}function _r(){return{captureContext:In,runWithContext:On,withSpan:xn,event(e,t){if(ue())try{let n=x.getSpan(_.active());if(n){n.addEvent(e,t);return}let o=x.getTracer(M).startSpan(vn,{kind:ut.INTERNAL,attributes:{"event.name":e,"matilda-code.daemon.operation":`event.${e}`,...t}});o.addEvent(e,t),o.setStatus({code:ce.OK}),o.end()}catch{}},injectPromptContext:wn}}f();X();var Rr=`${M}.daemon.http.request.count`,br=`${M}.daemon.http.request.duration`,vr=`${M}.daemon.session.active`,xr=`${M}.daemon.session.lifecycle`,kr=`${M}.daemon.channel.lifecycle`,Ir=`${M}.daemon.prompt.queue_wait`,Or=`${M}.daemon.prompt.duration`,wr=`${M}.daemon.bridge.error.count`,Pr=`${M}.daemon.cancel.count`,Dr=`${M}.daemon.sse.active`,Lr=`${M}.daemon.process.heap_used`,Nr=new Set(["SessionNotFoundError","WorkspaceMismatchError","InvalidClientIdError","SessionLimitExceededError","RestoreInProgressError","InvalidSessionScopeError","TrustGateError","WorkspaceInitConflictError","WorkspaceInitPathEscapeError","WorkspaceInitSymlinkError","WorkspaceInitRaceError","McpServerNotFoundError","McpServerRestartFailedError","PromptDeadlineExceededError","InvalidSessionMetadataError","SubscriberLimitExceededError","BridgeChannelClosedError","BridgeTimeoutError","PermissionForbiddenError"]),D=!1,Dn,Ln,Nn,Un,Fn,Gn,Kn,$n;function Ur(e){let t=e instanceof Error?e.name:typeof e;return Nr.has(t)?t:"unknown"}function Fr(){if(D)return;let e=ft();e&&(Dn=e.createCounter(Rr,{description:"Daemon HTTP request count by route and status class.",valueType:b.INT}),Ln=e.createHistogram(br,{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]}}),Nn=e.createCounter(xr,{description:"Daemon session lifecycle events (spawn, close, die).",valueType:b.INT}),Un=e.createCounter(kr,{description:"Daemon ACP channel lifecycle events (spawn, exit).",valueType:b.INT}),Fn=e.createHistogram(Ir,{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]}}),Gn=e.createHistogram(Or,{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]}}),Kn=e.createCounter(wr,{description:"Daemon bridge error count by normalized error type.",valueType:b.INT}),$n=e.createCounter(Pr,{description:"Daemon cancel request count.",valueType:b.INT}),D=!0)}var Pn=!1;function Gr(e){if(Pn)return;let t=ft();t&&(t.createObservableGauge(vr,{description:"Current number of active daemon sessions.",valueType:b.INT}).addCallback(n=>{try{n.observe(e.sessionCount())}catch{}}),t.createObservableGauge(Dr,{description:"Current number of active SSE connections.",valueType:b.INT}).addCallback(n=>{try{n.observe(e.sseCount())}catch{}}),t.createObservableGauge(Lr,{description:"Daemon process heap memory usage in bytes.",unit:"bytes",valueType:b.INT}).addCallback(n=>{try{n.observe(e.heapUsed())}catch{}}),Pn=!0)}function Kr(e,t,n){if(!D)return;let o=`${Math.floor(n/100)}xx`;Dn?.add(1,{route:t,status_class:o}),Ln?.record(e,{route:t})}function $r(e){D&&Nn?.add(1,{action:e})}function jr(e,t){D&&Un?.add(1,{action:e,...t!=null?{expected:t}:{}})}function Hr(e){D&&Fn?.record(e)}function Vr(e){D&&Gn?.record(e)}function Br(e){D&&Kn?.add(1,{error_type:Ur(e)})}function qr(){D&&$n?.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 jn=new zr;f();function Hn(e){let t=e.candidates?.[0]?.content?.parts;return!t||t.length===0?!1:t.some(Wr)}function Wr(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 Vn(){let e=tn.getStore();return{attempt:e?.attempt??1,requestSetupMs:e?.requestSetupMs,retryTotalDelayMs:e?.retryTotalDelayMs}}var W=O("LOGGING_CONTENT_GENERATOR"),Yr=4096,Bn="...[truncated]",Jr=Yr-Bn.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=Wt(o),a=de(o),l=o?.requestID||o?.request_id||t,u=U(o);ht(this.config,new yt({responseId:l,model:r,durationMs:n,promptId:i,authType:this.generatorAuthType,errorMessage:s,errorType:a,statusCode:u,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=Vn(),r=we(t.model,n);try{r.setAttribute("llm_request.stream",!1)}catch{}let i=x.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 u=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,c=a?void 0:this.extractResponseText(d);a||Oe(this.config,r,c),this.safelyLogApiResponse(d.responseId??"",p,this.getClientVisibleModelId(t.model,d.modelVersion),n,d.usageMetadata,c);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:u.usageMetadata?.promptTokenCount,outputTokens:u.usageMetadata?.candidatesTokenCount,cachedInputTokens:u.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-s,responseId:u.responseId||void 0,finishReason:u.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:u.usageMetadata?.thoughtsTokenCount,subagentName:F.getStore()||void 0,...o}),u}catch(u){let d=Date.now()-s,p=t.config?.abortSignal?.aborted??!1;throw B(r,{success:!1,durationMs:d,error:p?De:Pe,errorType:de(u),errorStatusCode:U(u),subagentName:F.getStore()||void 0,...o}),await _.with(i,async()=>{this.safelyLogApiError("",d,u,this.getClientVisibleModelId(t.model),n);try{await this.safelyLogOpenAIInteraction(await l.resolve(t),void 0,u,n)}catch(c){W.warn("Failed to log OpenAI interaction:",c)}}),u}}async generateContentStream(t,n){let o=Vn(),r=we(t.model,n);try{r.setAttribute("llm_request.stream",!0)}catch{}let i=x.setSpan(_.active(),r),s=Date.now(),a=Q(n),l=this.startCaptureSession(),u;try{Et.recordGenerateContentRequest(t,{stream:!0,source:"generateContentStream"}),a||(ke(this.config,r,t.config?.systemInstruction),Ie(this.config,r,t.config?.tools)),u=await _.with(i,async()=>(a||this.logApiRequest(this.toContents(t.contents),t.model,n),l.wrap(()=>this.wrapped.generateContentStream(t,n))))}catch(p){let c=Date.now()-s;_.with(i,()=>this.safelyLogApiError("",c,p,t.model,n));let h=t.config?.abortSignal?.aborted??!1;B(r,{success:!1,durationMs:c,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(u,s,n,t.model,d,r,i,t.config?.abortSignal,o))}startCaptureSession(){let t,n=!this.openaiLogger;return{wrap:o=>n?o():jn.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,u){let d=Q(o),p=!d||!!this.openaiLogger,c=[],h="",m="",g,C=!1,T,y=!1,E,R=F.getStore(),j,H=!1,N=v=>a?_.with(a,v):v(),xo=5*6e4,w,Vt=s?()=>{H||(w!==void 0&&clearTimeout(w),w=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,...u}),H=!0},xo),w.unref())}:void 0;Vt?.();try{for await(let k of t){!h&&k.responseId&&(h=k.responseId),!m&&k.modelVersion&&(m=k.modelVersion),p&&c.push(k),k.usageMetadata&&(g=k.usageMetadata);let qt=k.candidates?.[0];qt?.finishReason&&(T=qt.finishReason),k.functionCalls?.length&&(y=!0),j===void 0&&Hn(k)&&(j=Date.now()-n),Vt?.(),yield k}w!==void 0&&(clearTimeout(w),w=void 0);let v=Date.now()-n,ae=p?this.consolidateGeminiResponsesForLogging(c):void 0,Bt=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),H||(le?(N(()=>this.safelyLogApiError(h,v,le,this.getClientVisibleModelId(r,m),o)),await N(()=>this.safelyLogOpenAIInteraction(i,ae,le,o))):(N(()=>this.safelyLogApiResponse(h,v,this.getClientVisibleModelId(r,m),o,g,Bt)),!d&&s&&Oe(this.config,s,Bt),await N(()=>this.safelyLogOpenAIInteraction(i,ae,void 0,o))))}catch(v){if(C=!0,E=v,!H){let ae=Date.now()-n;N(()=>this.safelyLogApiError(h,ae,v,this.getClientVisibleModelId(r,m),o)),await N(()=>this.safelyLogOpenAIInteraction(i,void 0,v,o))}throw v}finally{if(w!==void 0&&clearTimeout(w),s&&!H){let v=l?.aborted??!1;B(s,{success:!C,inputTokens:g?.promptTokenCount,outputTokens:g?.candidatesTokenCount,cachedInputTokens:g?.cachedContentTokenCount,ttftMs:j,durationMs:Date.now()-n,error:C?v?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,...u})}}}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 u of t){u.usageMetadata&&(s=u.usageMetadata);let d=u.candidates?.[0];d?.finishReason&&(i=d.finishReason);let p=d?.content?.parts??[];for(let c of p){if(typeof c=="string"){o.push({text:c});continue}if("text"in c){c.text&&o.push({text:c.text,...c.thought?{thought:!0}:{},...c.thoughtSignature?{thoughtSignature:c.thoughtSignature}:{}});continue}if("functionCall"in c&&c.functionCall){let h=c.functionCall.id||c.functionCall.name||"tool_call",m=r.get(h),g={functionCall:c.functionCall};m!==void 0?o[m]=g:(r.set(h,o.length),o.push(g));continue}if("functionResponse"in c&&c.functionResponse){o.push({functionResponse:c.functionResponse});continue}o.push(c)}}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=Jr-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}${Bn}`: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();function qn(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 zn(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 Zr from"node:process";f();var Wn={image:!0,pdf:!0,audio:!0,video:!0},Xr=[[/^gemini-3/,Wn],[/^gemini-/,Wn],[/^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=rn(e);for(let[n,o]of Xr)if(n.test(t))return{...o};return{}}f();var Qe="$runtime|";function fl(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"],Yn=["model","apiKey","apiKeyEnvKey","baseUrl"],et=[...Yn,...Ze],Tl={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:[]}},yl={openai:on,"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}}],Al=tt.map(e=>e.id);var Ot=O("MODEL_REGISTRY");function Jn(e){if(Object.values(L).includes(e))return e}function Qr(e){return/^minimax-m3/i.test(e.trim().toLowerCase())}function Xn(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 Zt;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=Jn(n);if(!r){Ot.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(L).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}registerAuthTypeModels(t,n){let o=new Map;for(let r of n){let i=Xn(r.id,r.baseUrl);if(o.has(i)){Ot.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(Xn(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||Qr(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=Jn(n);if(!r){Ot.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(L).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}};var Qn=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(L),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===sn&&t?.baseUrl===ln&&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)?an: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||"",u=!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&&u?.envKey===a.envKey&&u.baseUrl===a.baseUrl,p=d?i.generationConfig.apiKey:void 0,c=d?i.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(a),!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,c&&(this.generationConfigSources.apiKey=e.deepClone(c))),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=Zr.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),u={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,u),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 Ti}from"node:fs";import{join as yi}from"node:path";f();f();import{randomBytes as ei,createHash as ti}from"node:crypto";function Zn(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}function wt(){let e=ei(32).toString("base64url"),t=ti("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 ni=15e3;async function Pt(e){let t=e.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",t);if(n.protocol!=="https:"&&!Zn(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(ni)});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 oi,closeSync as ri,unlinkSync as eo,statSync as ii}from"node:fs";import{dirname as si}from"node:path";var ai=2e4,li=3e4,di=50;function Dt(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(si(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??ai)}}function ci(e,t){let n=Promise.resolve();return o=>{let r=n.then(async()=>{await ui(e,t);try{return await o()}finally{pi(e)}});return n=r.then(()=>{},()=>{}),r}}async function ui(e,t){let n=Date.now()+t;for(;;)try{ri(oi(e,"wx"));return}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-ii(e).mtimeMs>li){eo(e);continue}}catch{continue}if(Date.now()>n)throw Object.assign(new Error(`Timed out acquiring credential lock at ${e}`),{code:"ETIMEDOUT"});await fi(di)}}function pi(e){try{eo(e)}catch{}}function fi(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 Lt(e){let t=e.storageKey??"default",n=e.fetchImpl??fetch,o=e.expirySkewMs??6e4,r=e.refreshTimeoutMs??15e3,i=null,s=async()=>{let u=await e.store.get(t);if(!u)return null;try{let d=JSON.parse(u);return d.accessToken?d:null}catch{return null}},a=u=>u.expiresAt-Date.now()>o,l=u=>e.lock(async()=>{let d=await s()??u;if(d.accessToken!==u.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&&gi(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 c=ye(p,d);return await e.store.set(t,JSON.stringify(c)),c.accessToken});return{async getAccessToken(u){let d=await s();if(!d)throw new ne("Not signed in.");return!u?.forceRefresh&&a(d)?d.accessToken:(i||(i=l(d).finally(()=>{i=null})),i)}}}function gi(e){try{return JSON.parse(e).error}catch{return}}f();import{createServer as mi}from"node:http";import{randomBytes as hi}from"node:crypto";async function Nt(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}=wt(),r=hi(16).toString("hex"),i=e.timeoutMs??5*60*1e3,s=e.transport.successRedirect;t({type:"state",status:"idle"});let a,l,u=new Promise((m,g)=>{a=m,l=g});u.catch(()=>{});let d=mi((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"),j=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(j)));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}Ci(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)})}),c=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 u;await to(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(c),e.signal?.removeEventListener("abort",h),await to(d)}}function to(e){return e.listening?new Promise(t=>{e.close(()=>t()),e.closeAllConnections()}):Promise.resolve()}function Ci(e,t,n){e.writeHead(302,{location:t}).end(n)}var Ae="matilda-code",oo="matilda-desktop",Ai="openid profile email offline_access",Ee="MATILDA_API_KEY",Ei="matilda";function Se(e){return e.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function ro(){return yi(ve.getGlobalMatildaDir(),"matilda-auth.json")}function rt(){return Dt(ro())}function Si(e){return e==="desktop"}function Me(e){return e?.clientId?e.clientId:Si(e?.channel)?oo:Ae}function re(e){return`matilda:${e}`}function it(e){return`${re(e)}:refresh-rejected`}function _e(e){return e===Ae?[re(e),Ei]:[re(e)]}function Mi(){try{let e=Ti(ro(),"utf8");return JSON.parse(e)}catch{return{}}}function Ut(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 _i(e,t){return Se(e)===Se(t)}function Ri(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 bi(e,t){let n=Ri(e.idToken);return{accessToken:e.accessToken,accessTokenExpiresAt:e.expiresAt,refreshToken:e.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:t}}var no=new Map;async function io(e){let t=no.get(e);if(t)return t;try{let n=await Pt(e);return no.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=Mi(),n=Me(e);for(let o of _e(n)){let r=Ut(t[o]);if(r)return r}return null}catch{return null}}function so(e){let t=Y(e);return!t||e?.baseUrl&&!_i(t.baseUrl,e.baseUrl)?null:t}function Sd(e){return so(e)!==null}async function vi(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 xi(e){return e instanceof Error?e.code==="invalid_grant"||e.name==="InvalidGrantError"?!0:e.message==="Token refresh failed (401)":!1}function oe(e){Ft({authStage:e.authStage,authOutcome:e.authOutcome,occurrenceCount:e.occurrenceCount},{baseUrl:e.baseUrl,token:e.token}).catch(()=>{})}async function ki(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 Ii(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 Md(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 _d(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 Ii(t)}async function Gt(e){let t=Me(e),n=re(t),o=so({baseUrl:e?.baseUrl,channel:e?.channel,clientId:t});if(!o)return e?.fallbackAccessToken??process.env[Ee]??"";let r=Se(o.baseUrl),i=await io(r),{store:s,lock:a}=rt(),l=Oi(s,a,i.token_endpoint,o.baseUrl,t,n,e?.signal),u=t===Ae&&(!!e?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=3e5),d;try{d=await l.getAccessToken({forceRefresh:e?.forceRefresh})}catch(p){throw u&&oe({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"}),t===oo&&xi(p)&&await vi({channel:e?.channel,clientId:t}),p}return u&&oe({baseUrl:o.baseUrl,token:d,authStage:"refresh",authOutcome:"succeeded"}),process.env[Ee]=d,d}async function Rd(e){await Gt(e);let t=Y(e);if(!t)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return t}function Oi(e,t,n,o,r,i,s){let a=_e(r);return Lt({tokenEndpoint:n,clientId:r,store:{get:async d=>{let p=d===i?a:[d],c=null;for(let m of p)if(c=Ut(await e.get(m)),c)break;if(!c?.accessToken)return null;let h={accessToken:c.accessToken,refreshToken:c.refreshToken,expiresAt:c.accessTokenExpiresAt};return JSON.stringify(h)},set:async(d,p)=>{let c=JSON.parse(p),h=d===i?a:[d],m={};for(let C of h){let T=Ut(await e.get(C));if(T){m=T;break}}let g={...m,accessToken:c.accessToken,accessTokenExpiresAt:c.expiresAt,refreshToken:c.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 c of p)await e.remove(c)}},storageKey:i,lock:t,fetchImpl:(d,p)=>{let c=[p?.signal,s].filter(h=>h instanceof AbortSignal);return fetch(d,{...p,signal:c.length>1?AbortSignal.any(c):c[0]})},expirySkewMs:3e5})}function wi(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&dn()}async function bd(e){let t=Se(e.baseUrl),n=await io(t),o="",r=0,i=0,s={},a=p=>{s[p]=(s[p]??0)+1},u=await(p=>(r+=1,Nt({metadata:n,clientId:Ae,scope:p,transport:{kind:"loopback",successRedirect:`${t}/api/auth/oauth/success?client_id=${encodeURIComponent(Ae)}`},signal:e.signal,onEvent:c=>{c.type==="authorize_url"&&(o=c.url,e.onAuthorizeUrl?.(c.url)),c.type==="state"&&c.status==="exchanging"&&(i+=1)},openBrowser:async c=>{if(e.openBrowser===!1||!wi()){a("skipped");return}try{let{default:h}=await import("./open-QQ7FWG4A.js");(await h(c)).once("error",()=>{}),a("succeeded")}catch{a("failed")}}})))(Ai),d=bi(u,e.baseUrl);await ki(d),oe({baseUrl:e.baseUrl,token:d.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:r});for(let[p,c]of Object.entries(s))oe({baseUrl:e.baseUrl,token:d.accessToken,authStage:"browser_opened",authOutcome:p,occurrenceCount:c});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 kd(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 Id(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 ao(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 lo(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:Pi(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,u=r*a*(l()*2-1);return Math.min(Math.max(0,r+u),n)}function Pi(e){let t=co(e,"retry-after")??Di(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 co(e,t){if(!Li(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 Di(e,t){return Ni(e)?co(e.response,t):null}function Li(e){return typeof e=="object"&&e!==null&&"headers"in e&&e.headers!=null}function Ni(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 Ui=new Set([429,503,1302,1305]);function Kt(e,t){let n=Fi(e);return n===null?!1:!!(Ui.has(n)||t&&t.includes(n))}function uo(e){let t=U(e),n=Gi(e),o=po(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 Fd(e,t){return lo({attempt:e,initialDelayMs:t.initialDelayMs,maxDelayMs:t.maxDelayMs,retryAfterMode:"minimum",retryAfterMaxDelayMs:t.maxDelayMs,error:t.error})}function Fi(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 Gi(e){for(let t of Ki(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 Ki(e){let t=po(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 po(e){return e instanceof Error?e.message:typeof e=="string"?e:null}function $i(e,t={}){if(ji(e))return{kind:"abort",diagnosis:"fail-fast",reason:"aborted"};let n=uo(e),o=n.statusCode,r=Wi(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"&&ao(e))return{kind:"provider-business",diagnosis:"fail-fast",reason:"matilda-oauth-free-tier-quota",...l};if(zi(i))return{kind:"provider-business",diagnosis:"fail-fast",reason:"allocated-quota-exceeded",...l};if(Kt(e,t.extraRetryErrorCodes))return{kind:n.transport==="sse"?"sse-provider":o!==void 0?"http":"provider",diagnosis:"retryable",reason:"rate-limit",...l};let u=Vi(e);if(u!==void 0&&(o===void 0||o>=500))return{kind:"transport",diagnosis:"retryable",reason:"transport-error",transportCode:u,...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{kind:"unknown",diagnosis:"unknown",reason:"unclassified",...l}}function fo(e,t){return Kt(e,t)||$i(e,{extraRetryErrorCodes:t}).diagnosis==="retryable"}function ji(e){return zt(e)?!0:e instanceof Error&&e.name==="CanceledError"}var Hi=5;function Vi(e){let t=e;for(let n=0;n<=Hi;n++){if(typeof t!="object"||t===null)return;let o=t.code;if(typeof o=="string"&&Bi(o))return o;t=t instanceof Error?t.cause:void 0}}function Bi(e){return qi.has(e)}var qi=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 zi(e){return e==="Throttling.AllocationQuota"}function Wi(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 L=(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))(L||{}),Yi="MATILDA_AGENT_SDK",at="MATILDA_API_KEY";function Ji(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 Xi(e,t){if(e.apiKeyEnvKey!==at)return;let n=Y({channel:t});if(!n?.accessToken)return;let o;try{o=await Gt({baseUrl:e.baseUrl,fallbackAccessToken:n.accessToken,channel:t})}catch(r){if(!fo(r))throw r;o=n.accessToken}o&&(e.apiKey=o,process.env[at]=o)}function Qi(e){return e.matildaAgentSdk===!0||process.env[Yi]==="1"}function $t(e,t,n){e[t]=n}function Zi(e,t){return e?.[t]}function es(e,t,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:t,proxy:e?.getProxy()};$t(i,"authType",{kind:"computed",detail:"provided by caller"}),e?.getProxy()&&$t(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=d=>Zi(o,d)??{kind:"unknown"};for(let d of et)n&&d in n&&!i[d]&&$t(i,d,l(d));Ji(a,e.getChannel());let u=mo(a,s);if(!u.valid)throw new Error(u.errors.map(d=>d.message).join(`
10
- `));return{config:a,sources:i}}function mo(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||qn(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=zn(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 Qd(e,t,n){return es(e,t,n).config}function go(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 Zd(e,t,n){await Xi(e,t.getChannel());let o=mo(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(Qi(e)){let{createMatildaAgentContentGenerator:s}=await import("./matildaAgentContentGenerator-OV4U6DJD.js");i=s(e,t)}else{let{createOpenAIContentGenerator:s}=await import("./openaiContentGenerator-MGASUFQL.js");i=s(e,t)}else if(r==="matilda-oauth"){let{getMatildaOAuthClient:s}=await import("./matildaOAuth2-WOY7ZS43.js"),{MatildaContentGenerator:a}=await import("./matildaContentGenerator-ETIAWE22.js");try{let l=await s(t,n?{requireCachedCredentials:!0}:void 0);i=new a(l,e,t)}catch(l){throw go(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(r==="anthropic"){let{createAnthropicContentGenerator:s}=await import("./anthropicContentGenerator-IYZILRDW.js");i=s(e,t)}else if(r==="gemini"||r==="vertex-ai"){let{createGeminiContentGenerator:s}=await import("./geminiContentGenerator-EQEGOXOV.js");i=s(e,t)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=go(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 ts=["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"],ns=new Set([...ts,...nn]),os=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})",rs="[A-Za-z][0-9A-Za-z-]{0,23}",ho="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",is=new RegExp(`^${se}(?:-${rs}(?:\\.${ho})+)?$`),ss=63,as=new RegExp(`^${se}$`),ls=new RegExp(`^${se}-preview\\.(?:0|[1-9]\\d{0,11})$`),ds=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}$`),us=new RegExp(`^${se}-(preview|canary|nightly|development|internal)(?:\\.${ho})+$`);function ps(e){return e==="desktop"?"desktop":e===void 0||os.has(e)?"code_cli":"unknown"}function fs(e){if(e==="android")return"android";if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux")return"linux"}function gs(e){if(e==="x64")return"x64";if(e==="arm64")return"arm64"}function ms(e){if(e===void 0)return"npm";if(e==="desktop")return"direct-download";if(e==="VSCode")return"vscode-marketplace"}function hs(e,t){if(t==="desktop")return"matilda-desktop";if(e==="VSCode")return"matilda-vscode";if(t==="code_cli")return"matilda-code"}function Cs(e){if(typeof e=="string"&&!(e.length>ss||!is.test(e)))return e}function Ts(e){if(e!==void 0)return as.test(e)?"stable":ls.test(e)?"preview":ds.test(e)?"canary":cs.test(e)?"nightly":us.exec(e)?.[1]}function Co(e,t=process.platform,n=process.arch){let o=e.getChannel?.(),r=ps(o),i=Cs(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:e.getCliVersion?.()),s=Ts(i),a=fs(t),l=gs(n),u=ms(o),d=hs(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}:{},...u?{"x-matilda-client-distribution-channel":u}:{},...s?{"x-matilda-client-release-channel":s}:{}}}function ic(e){let t=e.toLowerCase();return ns.has(t)||t.startsWith("x-matilda-reported-")}function ys(e){let t=e??en;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 sc(e,t=e.apiKey){return e.authType==="matilda-oauth"?!0:e.authType==="openai"&&!!t&&ys(e.baseUrl)}var As=3e3,Re=1,Es=24*60*60*1e3,To=20,yo=999,Ss=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"]),Ms=new Set(["ENOTFOUND","EAI_AGAIN"]),_s=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),Rs=new Set(["ABORT_ERR","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT"]),bs=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]);function vs(e){return`${new URL(e).origin}/api/client-events`}function xs(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 jt(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??As);try{let a=await r(vs(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(xs(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 Ft(e,t){let n=typeof e.occurrenceCount=="number"&&Number.isFinite(e.occurrenceCount)?Math.max(1,Math.min(Math.floor(e.occurrenceCount),yo)):1;return jt({eventType:"auth_funnel",authStage:e.authStage,authOutcome:e.authOutcome,occurrenceCount:n},t)}function Ao(){try{let e=$.readFileSync(Mo(),"utf8"),t=JSON.parse(e);return t.schemaVersion!==Re||!Array.isArray(t.failures)?void 0:{schemaVersion:Re,failures:t.failures.filter(ks)}}catch{return}}function ks(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 Eo(e){let t=Mo();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 So(e,t){return e.filter(n=>t-n.lastObservedAtMs<=Es).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-To)}function Is(e){let t=Co(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 Os(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 ws(e){if(!(!e||typeof e!="object"))for(let t of["status","statusCode"]){let n=e[t];if(typeof n=="number")return n}}function Ps(e,t){let n=Os(e);if(n&&Ss.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&Ms.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&_s.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&Rs.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&bs.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=ws(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 Ds(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 pc(e,t){let n=Is(t.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=Ps(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=Ao()??{schemaVersion:Re,failures:[]},a=So(s.failures,r),l=Ds(a,i);if(l>=0){let u=a[l];a[l]={...u,occurrenceCount:Math.min(u.occurrenceCount+1,yo),lastObservedAtMs:r}}else a.push(i);return Eo({schemaVersion:Re,failures:a.slice(-To)}),!0}async function fc(e){let t=Ao();if(!t)return;let n=So(t.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await jt({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}}Eo({schemaVersion:Re,failures:o})}function Mo(){return lt.join(ve.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var Ro=(n=>(n.GCP="gcp",n.LOCAL="local",n))(Ro||{}),Ap="local",Ep="http://localhost:4317";f();X();var Ns=new Set(["service.version","service.instance.id","session.id"]);function J(e,t){xe.warn(e),t?.push(e)}function bo(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 u;try{u=decodeURIComponent(a)}catch{J(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${l}", using raw value`,t),u=a}n[l]=u}return n}function Ht(e,t,n){for(let o of Ns)o in e&&(J(`${t} cannot override reserved key "${o}"; ignoring`,n),delete e[o]);return e}function vo(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 _o(e){if(e!==void 0){if(e==="local"||e==="local")return"local";if(e==="gcp"||e==="gcp")return"gcp"}}async function Ls(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=_o(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,u=["grpc","http"].find(N=>N===l);if(l!==void 0&&u===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,c=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=Ht(bo(n.OTEL_RESOURCE_ATTRIBUTES,C),"OTEL_RESOURCE_ATTRIBUTES",C),y=Ht(vo(o.resourceAttributes,C),"settings.telemetry.resourceAttributes",C),E={...T,...y},R=n.OTEL_SERVICE_NAME?.trim();R&&(E["service.name"]=R);let j=Object.keys(E).length?E:void 0,H=be(n.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??o.metrics?.includeSessionId??!1;return{enabled:r,target:s,otlpEndpoint:a,otlpProtocol:u,otlpTracesEndpoint:h,otlpLogsEndpoint:m,otlpMetricsEndpoint:g,logPrompts:d,includeSensitiveSpanAttributes:p,outfile:c,resourceAttributes:j,metrics:{includeSessionId:H},resourceAttributeWarnings:C.length?C:void 0}}export{_t as a,Z as b,Le as c,wo as d,Po as e,yn as f,Ke as g,jn as h,ir as i,he as j,Aa as k,be as l,_o as m,Ls as n,te as o,Be as p,Tr as q,It as r,yr as s,xn as t,Ar as u,Er as v,kn as w,Sr as x,In as y,On as z,wn as A,Mr as B,_r as C,Fr as D,Gr as E,Kr as F,$r as G,jr as H,Hr as I,Vr as J,Br as K,qr as L,Co as M,ic as N,sc as O,jt as P,Ft as Q,pc as R,fc as S,Ro as T,Ap as U,Ep as V,Te as W,Qe as X,fl as Y,Ze as Z,Tl as _,yl as $,tt as aa,Al as ba,Xn as ca,nt as da,Qn as ea,ro as fa,Y as ga,Sd as ha,xi as ia,ki as ja,Ii as ka,Md as la,_d as ma,Gt as na,Rd as oa,wi as pa,bd as qa,ie as ra,st as sa,kd as ta,Id as ua,ao as va,lo as wa,Pi as xa,Kt as ya,uo as za,Fd as Aa,$i as Ba,fo as Ca,L as Da,es as Ea,mo as Fa,Qd as Ga,Zd as Ha};
7
+ `)||""}function Ge(e,t,n=!0){if(t.taggedThinkingParser)return t.taggedThinkingParser.parse(e,n);if(t.responseParsingOptions?.taggedThinkingTags)return un(e);if(!e)return[];let o=Ne(Rt(e));return o?[{text:o}]:[]}function Jo(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=Qt(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:Mn(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=yn(e.usage,{estimatedReasoningTokens:Z(i.length),estimatedContentTokens:Z(s.length)})}return o}function Xo(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 u=n.delta?.reasoning_content??n.delta?.reasoning;if(u){let d=fn(u,t.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});d&&i.push({text:d,thought:!0})}}if(typeof n.delta?.content=="string"){let u=fn(n.delta.content,t.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(u||n.finish_reason)&&i.push(...Ge(u,t,!!n.finish_reason))}else n.finish_reason&&i.push(...Ge("",t,!0));if(n.delta?.tool_calls)for(let u of n.delta.tool_calls){let d=u.index??0;u.function?.arguments?r.addChunk(d,u.function.arguments,u.id,u.function.name):r.addChunk(d,"",u.id,u.function?.name)}let s=!1;if(n.finish_reason){s=r.hasIncompleteToolCalls();let u=r.getCompletedToolCalls();for(let d of u)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=Mn(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=yn(e.usage,Zo(t))),o}function Qo(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 Zo(e){return{estimatedReasoningTokens:Z(e.reasoningDeltaState?.emittedLength??0),estimatedContentTokens:Z(e.textDeltaState?.emittedLength??0)}}function Mn(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 er(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 hn(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===Tn}function tr(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 u=[],d=new Set;for(let C of l.tool_calls){let T=C.id;!T||s.has(T)||d.has(T)||(d.add(T),u.push(C))}let p=new Set,c=[],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),c.push(C),m=!0):m=!1;continue}if(hn(T)){m&&h.push(C);continue}if(!(T.role==="assistant"&&!bt(T)))break}let g=u.filter(C=>p.has(C.id));for(let C of g)s.add(C.id);n.set(a,g),o.set(a,c),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 u=l.reasoning_content,d=n.get(a)??[];if(d.length>0){let p={...l};p.tool_calls=d,t.push(p);for(let c of o.get(a)??[]){let h=e[c];h&&(t.push(h),i.add(c))}for(let c of r.get(a)??[]){let h=e[c];h&&(t.push(h),i.add(c))}}else if(typeof l.content=="string"&&l.content.trim()||u){let p={...l};delete p.tool_calls,t.push(p)}else P.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?P.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):hn(l)?P.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):t.push(l)}return t}function Cn(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),u;if(l){let p=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[],c=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[];u=[...p,...c]}else u=[typeof s=="string"?s:"",typeof a=="string"?a:""].filter(Boolean).join("")||null;let d=[...r,...i];o.content=u||null,d.length>0&&(o.tool_calls=d);continue}}t.push(n)}return t}var Ke={convertGeminiToolParametersToOpenAI:An,convertGeminiToolsToOpenAI:$o,convertGeminiRequestToOpenAI:jo,convertGeminiResponseToOpenAI:Ho,convertOpenAIResponseToGemini:Jo,convertOpenAIChunkToGemini:Xo,flushOpenAIStreamToGemini:Qo};f();import*as O from"node:path";import{promises as He}from"node:fs";f();f();import nr from"crypto";var je=new Uint8Array(256),$e=je.length;function vt(){return $e>je.length-16&&(nr.randomFillSync(je),$e=0),je.slice($e,$e+=16)}f();var S=[];for(let e=0;e<256;++e)S.push((e+256).toString(16).slice(1));function _n(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 or from"crypto";var xt={randomUUID:or.randomUUID};function rr(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 _n(o)}var kt=rr;import*as G from"os";var Ve=w("OPENAI_LOGGER"),ir="########",sr=/^[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 ar(e,t){let n=t||process.cwd();if(!e)return O.join(n,"logs","openai");let o=e;return e==="~"||e.startsWith("~/")?o=O.join(G.homedir(),e.slice(1)):O.isAbsolute(e)||(o=O.resolve(n,e)),O.normalize(o)}function Rn(e){return e&&e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function lr(e){let t=e.split("#");if(t.length!==3)return;let[,n,o]=t;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function dr(e){if(e)return Q(e)?Rn(e):Rn(lr(e))}function cr(e){if(!e)return;let t=e.indexOf(ir);if(t>0)return e.slice(0,t);if(sr.test(e))return e;let n=e.split("#");if(n.length>=3&&n[0])return n[0]}function ur(e){let t=e?.trim(),n=cr(t);return!t&&!n?null:{...t?{promptId:t}:{},...n?{sessionId:n}:{}}}var he=class{logDir;initialized=!1;constructor(t,n){this.logDir=ar(t,n)}async initialize(){if(!this.initialized)try{await He.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=dr(r),l=a?`openai-${i}-${s}-${a}.json`:`openai-${i}-${s}.json`,u=O.join(this.logDir,l),d={timestamp:new Date().toISOString(),request:t,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:ur(r),system:{hostname:G.hostname(),platform:G.platform(),release:G.release(),nodeVersion:process.version}};try{return await He.writeFile(u,JSON.stringify(d,null,2),"utf-8"),u}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 He.readdir(this.logDir)).filter(r=>r.startsWith("openai-")&&r.endsWith(".json")).map(r=>O.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 He.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}`)}}},Ea=new he;f();f();X();Po();f();X();var bn=Oo(wo(),1);import{createHash as pr}from"node:crypto";var te="matilda.telemetry.traceparent",Be="matilda.telemetry.tracestate",fr="matilda-code.daemon.request",vn="matilda-code.daemon.bridge",gr="matilda-code.daemon.error";function mr(e){return e instanceof Error?e.message:String(e)}function hr(e){return e instanceof Error?e.name||"Error":typeof e}var Cr="0".repeat(32),Tr="0".repeat(16);function yr(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 Ar(e){return pr("sha256").update(e).digest("hex").slice(0,16)}async function It(e,t,n,o={}){if(!ue())return await n(void 0);let r=o.autoOkOnSuccess??!0;return await k.getTracer(M).startActiveSpan(e,{kind:ut.INTERNAL,attributes:t},async s=>{try{let a=await n(s);return r&&s.setStatus({code:ce.OK}),a}catch(a){throw kn(s,a),a}finally{s.end()}})}async function Er(e,t){return await It(fr,{"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 xn(e,t,n){return await It(vn,{"matilda-code.daemon.operation":e,...t},async()=>await n())}function Sr(e,t){try{e?.setAttribute("http.response.status_code",t)}catch{}}function Mr(e,t){try{k.getSpan(_.active())?.setAttribute(e,t)}catch{}}function kn(e,t,n={}){let o=e??k.getSpan(_.active());if(o)try{let r=gt(mr(t));o.recordException(t instanceof Error?t:new Error(r)),o.setAttributes({"error.type":hr(t),"error.message":r,...n}),o.setStatus({code:ce.ERROR,message:r})}catch{}}function _r(e,t={},n){if(ue())try{bn.logs.getLogger(M).emit({body:e,timestamp:new Date,attributes:{"event.name":n?.eventName??gr,...t},...n?.severityNumber!=null?{severityNumber:n.severityNumber}:{}})}catch{}}function In(){return{context:_.active()}}async function On(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 wn(e){let t=e._meta,n=yr(t);try{let o=Jt();o&&(n[te]=pt(o))}catch{}return!t&&!n[te]?e:{...e,_meta:n}}function Rr(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=Yt.extract(ct,r);if(k.getSpanContext(s))return s;let a=o.split("-"),l=a[1],u=a[2],d=a[3];if(!(a[0]!=="00"||!l?.match(/^[0-9a-f]{32}$/)||!u?.match(/^[0-9a-f]{16}$/)||!d?.match(/^[0-9a-f]{2}$/)||l===Cr||u===Tr))return k.setSpan(ct,k.wrapSpanContext({traceId:l,spanId:u,traceFlags:Number.parseInt(d,16),isRemote:!0}))}function br(){return{captureContext:In,runWithContext:On,withSpan:xn,event(e,t){if(ue())try{let n=k.getSpan(_.active());if(n){n.addEvent(e,t);return}let o=k.getTracer(M).startSpan(vn,{kind:ut.INTERNAL,attributes:{"event.name":e,"matilda-code.daemon.operation":`event.${e}`,...t}});o.addEvent(e,t),o.setStatus({code:ce.OK}),o.end()}catch{}},injectPromptContext:wn}}f();X();var vr=`${M}.daemon.http.request.count`,xr=`${M}.daemon.http.request.duration`,kr=`${M}.daemon.session.active`,Ir=`${M}.daemon.session.lifecycle`,Or=`${M}.daemon.channel.lifecycle`,wr=`${M}.daemon.prompt.queue_wait`,Pr=`${M}.daemon.prompt.duration`,Dr=`${M}.daemon.bridge.error.count`,Lr=`${M}.daemon.cancel.count`,Nr=`${M}.daemon.sse.active`,Ur=`${M}.daemon.process.heap_used`,Fr=new Set(["SessionNotFoundError","WorkspaceMismatchError","InvalidClientIdError","SessionLimitExceededError","RestoreInProgressError","InvalidSessionScopeError","TrustGateError","WorkspaceInitConflictError","WorkspaceInitPathEscapeError","WorkspaceInitSymlinkError","WorkspaceInitRaceError","McpServerNotFoundError","McpServerRestartFailedError","PromptDeadlineExceededError","InvalidSessionMetadataError","SubscriberLimitExceededError","BridgeChannelClosedError","BridgeTimeoutError","PermissionForbiddenError"]),D=!1,Dn,Ln,Nn,Un,Fn,Gn,Kn,$n;function Gr(e){let t=e instanceof Error?e.name:typeof e;return Fr.has(t)?t:"unknown"}function Kr(){if(D)return;let e=ft();e&&(Dn=e.createCounter(vr,{description:"Daemon HTTP request count by route and status class.",valueType:b.INT}),Ln=e.createHistogram(xr,{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]}}),Nn=e.createCounter(Ir,{description:"Daemon session lifecycle events (spawn, close, die).",valueType:b.INT}),Un=e.createCounter(Or,{description:"Daemon ACP channel lifecycle events (spawn, exit).",valueType:b.INT}),Fn=e.createHistogram(wr,{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]}}),Gn=e.createHistogram(Pr,{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]}}),Kn=e.createCounter(Dr,{description:"Daemon bridge error count by normalized error type.",valueType:b.INT}),$n=e.createCounter(Lr,{description:"Daemon cancel request count.",valueType:b.INT}),D=!0)}var Pn=!1;function $r(e){if(Pn)return;let t=ft();t&&(t.createObservableGauge(kr,{description:"Current number of active daemon sessions.",valueType:b.INT}).addCallback(n=>{try{n.observe(e.sessionCount())}catch{}}),t.createObservableGauge(Nr,{description:"Current number of active SSE connections.",valueType:b.INT}).addCallback(n=>{try{n.observe(e.sseCount())}catch{}}),t.createObservableGauge(Ur,{description:"Daemon process heap memory usage in bytes.",unit:"bytes",valueType:b.INT}).addCallback(n=>{try{n.observe(e.heapUsed())}catch{}}),Pn=!0)}function jr(e,t,n){if(!D)return;let o=`${Math.floor(n/100)}xx`;Dn?.add(1,{route:t,status_class:o}),Ln?.record(e,{route:t})}function Hr(e){D&&Nn?.add(1,{action:e})}function Vr(e,t){D&&Un?.add(1,{action:e,...t!=null?{expected:t}:{}})}function Br(e){D&&Fn?.record(e)}function qr(e){D&&Gn?.record(e)}function zr(e){D&&Kn?.add(1,{error_type:Gr(e)})}function Wr(){D&&$n?.add(1)}f();X();import*as $ from"node:fs";import*as lt from"node:path";f();f();f();f();X();f();import{AsyncLocalStorage as Yr}from"node:async_hooks";var jn=new Yr;f();function Hn(e){let t=e.candidates?.[0]?.content?.parts;return!t||t.length===0?!1:t.some(Jr)}function Jr(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 Vn(){let e=nn.getStore();return{attempt:e?.attempt??1,requestSetupMs:e?.requestSetupMs,retryTotalDelayMs:e?.retryTotalDelayMs}}var W=w("LOGGING_CONTENT_GENERATOR"),Xr=4096,Bn="...[truncated]",Qr=Xr-Bn.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=Wt(o),a=de(o),l=o?.requestID||o?.request_id||t,u=U(o);ht(this.config,new yt({responseId:l,model:r,durationMs:n,promptId:i,authType:this.generatorAuthType,errorMessage:s,errorType:a,statusCode:u,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=Vn(),r=we(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 u=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,c=a?void 0:this.extractResponseText(d);a||Oe(this.config,r,c),this.safelyLogApiResponse(d.responseId??"",p,this.getClientVisibleModelId(t.model,d.modelVersion),n,d.usageMetadata,c);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:u.usageMetadata?.promptTokenCount,outputTokens:u.usageMetadata?.candidatesTokenCount,cachedInputTokens:u.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-s,responseId:u.responseId||void 0,finishReason:u.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:u.usageMetadata?.thoughtsTokenCount,subagentName:F.getStore()||void 0,...o}),u}catch(u){let d=Date.now()-s,p=t.config?.abortSignal?.aborted??!1;throw B(r,{success:!1,durationMs:d,error:p?De:Pe,errorType:de(u),errorStatusCode:U(u),subagentName:F.getStore()||void 0,...o}),await _.with(i,async()=>{this.safelyLogApiError("",d,u,this.getClientVisibleModelId(t.model),n);try{await this.safelyLogOpenAIInteraction(await l.resolve(t),void 0,u,n)}catch(c){W.warn("Failed to log OpenAI interaction:",c)}}),u}}async generateContentStream(t,n){let o=Vn(),r=we(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(),u;try{Et.recordGenerateContentRequest(t,{stream:!0,source:"generateContentStream"}),a||(ke(this.config,r,t.config?.systemInstruction),Ie(this.config,r,t.config?.tools)),u=await _.with(i,async()=>(a||this.logApiRequest(this.toContents(t.contents),t.model,n),l.wrap(()=>this.wrapped.generateContentStream(t,n))))}catch(p){let c=Date.now()-s;_.with(i,()=>this.safelyLogApiError("",c,p,t.model,n));let h=t.config?.abortSignal?.aborted??!1;B(r,{success:!1,durationMs:c,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(u,s,n,t.model,d,r,i,t.config?.abortSignal,o))}startCaptureSession(){let t,n=!this.openaiLogger;return{wrap:o=>n?o():jn.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,u){let d=Q(o),p=!d||!!this.openaiLogger,c=[],h="",m="",g,C=!1,T,y=!1,E,R=F.getStore(),j,H=!1,N=x=>a?_.with(a,x):x(),ko=5*6e4,v,Io=s?()=>{H||(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,...u}),H=!0},ko),v.unref())}:void 0;try{for await(let I of t){!h&&I.responseId&&(h=I.responseId),!m&&I.modelVersion&&(m=I.modelVersion),p&&c.push(I),I.usageMetadata&&(g=I.usageMetadata);let qt=I.candidates?.[0];qt?.finishReason&&(T=qt.finishReason),I.functionCalls?.length&&(y=!0),j===void 0&&Hn(I)&&(j=Date.now()-n),Io?.(),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(c):void 0,Bt=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),H||(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,Bt)),!d&&s&&Oe(this.config,s,Bt),await N(()=>this.safelyLogOpenAIInteraction(i,ae,void 0,o))))}catch(x){if(C=!0,E=x,!H){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&&!H){let x=l?.aborted??!1;B(s,{success:!C,inputTokens:g?.promptTokenCount,outputTokens:g?.candidatesTokenCount,cachedInputTokens:g?.cachedContentTokenCount,ttftMs:j,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,...u})}}}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 u of t){u.usageMetadata&&(s=u.usageMetadata);let d=u.candidates?.[0];d?.finishReason&&(i=d.finishReason);let p=d?.content?.parts??[];for(let c of p){if(typeof c=="string"){o.push({text:c});continue}if("text"in c){c.text&&o.push({text:c.text,...c.thought?{thought:!0}:{},...c.thoughtSignature?{thoughtSignature:c.thoughtSignature}:{}});continue}if("functionCall"in c&&c.functionCall){let h=c.functionCall.id||c.functionCall.name||"tool_call",m=r.get(h),g={functionCall:c.functionCall};m!==void 0?o[m]=g:(r.set(h,o.length),o.push(g));continue}if("functionResponse"in c&&c.functionResponse){o.push({functionResponse:c.functionResponse});continue}o.push(c)}}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=Qr-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}${Bn}`: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();function qn(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 zn(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 ti from"node:process";f();var Wn={image:!0,pdf:!0,audio:!0,video:!0},Zr=[[/^gemini-3/,Wn],[/^gemini-/,Wn],[/^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=sn(e);for(let[n,o]of Zr)if(n.test(t))return{...o};return{}}f();var Qe="$runtime|";function gl(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"],Yn=["model","apiKey","apiKeyEnvKey","baseUrl"],et=[...Yn,...Ze],yl={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:[]}},Al={openai:rn,"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}}],El=tt.map(e=>e.id);var Ot=w("MODEL_REGISTRY");function Jn(e){if(Object.values(L).includes(e))return e}function ei(e){return/^minimax-m3/i.test(e.trim().toLowerCase())}function Xn(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 en;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=Jn(n);if(!r){Ot.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(L).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}registerAuthTypeModels(t,n){let o=new Map;for(let r of n){let i=Xn(r.id,r.baseUrl);if(o.has(i)){Ot.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(Xn(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||ei(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=Jn(n);if(!r){Ot.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(L).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}};var Qn=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(L),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===an&&t?.baseUrl===dn&&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)?ln: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||"",u=!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&&u?.envKey===a.envKey&&u.baseUrl===a.baseUrl,p=d?i.generationConfig.apiKey:void 0,c=d?i.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(a),!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,c&&(this.generationConfigSources.apiKey=e.deepClone(c))),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=ti.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),u={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,u),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 Ai}from"node:fs";import{join as Ei}from"node:path";f();f();import{randomBytes as ni,createHash as oi}from"node:crypto";function Zn(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}function wt(){let e=ni(32).toString("base64url"),t=oi("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 ri=15e3;async function Pt(e){let t=e.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",t);if(n.protocol!=="https:"&&!Zn(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(ri)});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 ii,closeSync as si,unlinkSync as eo,statSync as ai}from"node:fs";import{dirname as li}from"node:path";var di=2e4,ci=3e4,ui=50;function Dt(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(li(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:pi(`${e}.lock`,t.lockTimeoutMs??di)}}function pi(e,t){let n=Promise.resolve();return o=>{let r=n.then(async()=>{await fi(e,t);try{return await o()}finally{gi(e)}});return n=r.then(()=>{},()=>{}),r}}async function fi(e,t){let n=Date.now()+t;for(;;)try{si(ii(e,"wx"));return}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-ai(e).mtimeMs>ci){eo(e);continue}}catch{continue}if(Date.now()>n)throw Object.assign(new Error(`Timed out acquiring credential lock at ${e}`),{code:"ETIMEDOUT"});await mi(ui)}}function gi(e){try{eo(e)}catch{}}function mi(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 Lt(e){let t=e.storageKey??"default",n=e.fetchImpl??fetch,o=e.expirySkewMs??6e4,r=e.refreshTimeoutMs??15e3,i=null,s=async()=>{let u=await e.store.get(t);if(!u)return null;try{let d=JSON.parse(u);return d.accessToken?d:null}catch{return null}},a=u=>u.expiresAt-Date.now()>o,l=u=>e.lock(async()=>{let d=await s()??u;if(d.accessToken!==u.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&&hi(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 c=ye(p,d);return await e.store.set(t,JSON.stringify(c)),c.accessToken});return{async getAccessToken(u){let d=await s();if(!d)throw new ne("Not signed in.");return!u?.forceRefresh&&a(d)?d.accessToken:(i||(i=l(d).finally(()=>{i=null})),i)}}}function hi(e){try{return JSON.parse(e).error}catch{return}}f();import{createServer as Ci}from"node:http";import{randomBytes as Ti}from"node:crypto";async function Nt(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}=wt(),r=Ti(16).toString("hex"),i=e.timeoutMs??5*60*1e3,s=e.transport.successRedirect;t({type:"state",status:"idle"});let a,l,u=new Promise((m,g)=>{a=m,l=g});u.catch(()=>{});let d=Ci((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"),j=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(j)));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}yi(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)})}),c=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 u;await to(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(c),e.signal?.removeEventListener("abort",h),await to(d)}}function to(e){return e.listening?new Promise(t=>{e.close(()=>t()),e.closeAllConnections()}):Promise.resolve()}function yi(e,t,n){e.writeHead(302,{location:t}).end(n)}var Ae="matilda-code",oo="matilda-desktop",Si="openid profile email offline_access",Ee="MATILDA_API_KEY",Mi="matilda";function Se(e){return e.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function ro(){return Ei(ve.getGlobalMatildaDir(),"matilda-auth.json")}function rt(){return Dt(ro())}function _i(e){return e==="desktop"}function Me(e){return e?.clientId?e.clientId:_i(e?.channel)?oo:Ae}function re(e){return`matilda:${e}`}function it(e){return`${re(e)}:refresh-rejected`}function _e(e){return e===Ae?[re(e),Mi]:[re(e)]}function Ri(){try{let e=Ai(ro(),"utf8");return JSON.parse(e)}catch{return{}}}function Ut(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 bi(e,t){return Se(e)===Se(t)}function vi(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 xi(e,t){let n=vi(e.idToken);return{accessToken:e.accessToken,accessTokenExpiresAt:e.expiresAt,refreshToken:e.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:t}}var no=new Map;async function io(e){let t=no.get(e);if(t)return t;try{let n=await Pt(e);return no.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=Ri(),n=Me(e);for(let o of _e(n)){let r=Ut(t[o]);if(r)return r}return null}catch{return null}}function so(e){let t=Y(e);return!t||e?.baseUrl&&!bi(t.baseUrl,e.baseUrl)?null:t}function Md(e){return so(e)!==null}async function ki(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 Ii(e){return e instanceof Error?e.code==="invalid_grant"||e.name==="InvalidGrantError"?!0:e.message==="Token refresh failed (401)":!1}function oe(e){Ft({authStage:e.authStage,authOutcome:e.authOutcome,occurrenceCount:e.occurrenceCount},{baseUrl:e.baseUrl,token:e.token}).catch(()=>{})}async function Oi(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 wi(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 _d(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 Rd(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 wi(t)}async function Gt(e){let t=Me(e),n=re(t),o=so({baseUrl:e?.baseUrl,channel:e?.channel,clientId:t});if(!o)return e?.fallbackAccessToken??process.env[Ee]??"";let r=Se(o.baseUrl),i=await io(r),{store:s,lock:a}=rt(),l=Pi(s,a,i.token_endpoint,o.baseUrl,t,n,e?.signal),u=t===Ae&&(!!e?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=3e5),d;try{d=await l.getAccessToken({forceRefresh:e?.forceRefresh})}catch(p){throw u&&oe({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"}),t===oo&&Ii(p)&&await ki({channel:e?.channel,clientId:t}),p}return u&&oe({baseUrl:o.baseUrl,token:d,authStage:"refresh",authOutcome:"succeeded"}),process.env[Ee]=d,d}async function bd(e){await Gt(e);let t=Y(e);if(!t)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return t}function Pi(e,t,n,o,r,i,s){let a=_e(r);return Lt({tokenEndpoint:n,clientId:r,store:{get:async d=>{let p=d===i?a:[d],c=null;for(let m of p)if(c=Ut(await e.get(m)),c)break;if(!c?.accessToken)return null;let h={accessToken:c.accessToken,refreshToken:c.refreshToken,expiresAt:c.accessTokenExpiresAt};return JSON.stringify(h)},set:async(d,p)=>{let c=JSON.parse(p),h=d===i?a:[d],m={};for(let C of h){let T=Ut(await e.get(C));if(T){m=T;break}}let g={...m,accessToken:c.accessToken,accessTokenExpiresAt:c.expiresAt,refreshToken:c.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 c of p)await e.remove(c)}},storageKey:i,lock:t,fetchImpl:(d,p)=>{let c=[p?.signal,s].filter(h=>h instanceof AbortSignal);return fetch(d,{...p,signal:c.length>1?AbortSignal.any(c):c[0]})},expirySkewMs:3e5})}function Di(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&Xt()}async function vd(e){let t=Se(e.baseUrl),n=await io(t),o="",r=0,i=0,s={},a=p=>{s[p]=(s[p]??0)+1},u=await(p=>(r+=1,Nt({metadata:n,clientId:Ae,scope:p,transport:{kind:"loopback",successRedirect:`${t}/api/auth/oauth/success?client_id=${encodeURIComponent(Ae)}`},signal:e.signal,onEvent:c=>{c.type==="authorize_url"&&(o=c.url,e.onAuthorizeUrl?.(c.url)),c.type==="state"&&c.status==="exchanging"&&(i+=1)},openBrowser:async c=>{if(e.openBrowser===!1||!Di()){a("skipped");return}try{let{default:h}=await import("./open-QQ7FWG4A.js");(await h(c)).once("error",()=>{}),a("succeeded")}catch{a("failed")}}})))(Si),d=xi(u,e.baseUrl);await Oi(d),oe({baseUrl:e.baseUrl,token:d.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:r});for(let[p,c]of Object.entries(s))oe({baseUrl:e.baseUrl,token:d.accessToken,authStage:"browser_opened",authOutcome:p,occurrenceCount:c});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 Id(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 Od(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 ao(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 lo(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:Li(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,u=r*a*(l()*2-1);return Math.min(Math.max(0,r+u),n)}function Li(e){let t=co(e,"retry-after")??Ni(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 co(e,t){if(!Ui(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 Ni(e,t){return Fi(e)?co(e.response,t):null}function Ui(e){return typeof e=="object"&&e!==null&&"headers"in e&&e.headers!=null}function Fi(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 Gi=new Set([429,503,1302,1305]);function Kt(e,t){if($t(e))return!1;let n=Ki(e);return n===null?!1:!!(Gi.has(n)||t&&t.includes(n))}function $t(e){let t=po(e)?.code,n=typeof e=="object"&&e!==null&&"code"in e?e.code:void 0;return(t??n)==="insufficient_quota"}function uo(e){let t=U(e),n=po(e),o=fo(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 Gd(e,t){return lo({attempt:e,initialDelayMs:t.initialDelayMs,maxDelayMs:t.maxDelayMs,retryAfterMode:"minimum",retryAfterMaxDelayMs:t.maxDelayMs,error:t.error})}function Ki(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 po(e){for(let t of $i(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 $i(e){let t=fo(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 fo(e){return e instanceof Error?e.message:typeof e=="string"?e:null}function ji(e,t={}){if(Hi(e))return{kind:"abort",diagnosis:"fail-fast",reason:"aborted"};let n=uo(e),o=n.statusCode,r=Yi(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"&&ao(e))return{kind:"provider-business",diagnosis:"fail-fast",reason:"matilda-oauth-free-tier-quota",...l};if(Wi(i))return{kind:"provider-business",diagnosis:"fail-fast",reason:"allocated-quota-exceeded",...l};if($t(e))return{kind:"provider-business",diagnosis:"fail-fast",reason:"insufficient-quota",...l};if(Kt(e,t.extraRetryErrorCodes))return{kind:n.transport==="sse"?"sse-provider":o!==void 0?"http":"provider",diagnosis:"retryable",reason:"rate-limit",...l};let u=Bi(e);if(u!==void 0&&(o===void 0||o>=500))return{kind:"transport",diagnosis:"retryable",reason:"transport-error",transportCode:u,...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 qd(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 go(e,t){return Kt(e,t)||ji(e,{extraRetryErrorCodes:t}).diagnosis==="retryable"}function Hi(e){return zt(e)?!0:e instanceof Error&&e.name==="CanceledError"}var Vi=5;function Bi(e){let t=e;for(let n=0;n<=Vi;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 Wi(e){return e==="Throttling.AllocationQuota"}function Yi(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 L=(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))(L||{}),Ji="MATILDA_AGENT_SDK",at="MATILDA_API_KEY";function Xi(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 Qi(e,t){if(e.apiKeyEnvKey!==at)return;let n=Y({channel:t});if(!n?.accessToken)return;let o;try{o=await Gt({baseUrl:e.baseUrl,fallbackAccessToken:n.accessToken,channel:t})}catch(r){if(!go(r))throw r;o=n.accessToken}o&&(e.apiKey=o,process.env[at]=o)}function Zi(e){return e.matildaAgentSdk===!0||process.env[Ji]==="1"}function jt(e,t,n){e[t]=n}function es(e,t){return e?.[t]}function ts(e,t,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:t,proxy:e?.getProxy()};jt(i,"authType",{kind:"computed",detail:"provided by caller"}),e?.getProxy()&&jt(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=d=>es(o,d)??{kind:"unknown"};for(let d of et)n&&d in n&&!i[d]&&jt(i,d,l(d));Xi(a,e.getChannel());let u=ho(a,s);if(!u.valid)throw new Error(u.errors.map(d=>d.message).join(`
10
+ `));return{config:a,sources:i}}function ho(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||qn(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=zn(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 ec(e,t,n){return ts(e,t,n).config}function mo(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 tc(e,t,n){await Qi(e,t.getChannel());let o=ho(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(Zi(e)){let{createMatildaAgentContentGenerator:s}=await import("./matildaAgentContentGenerator-YUYS4336.js");i=s(e,t)}else{let{createOpenAIContentGenerator:s}=await import("./openaiContentGenerator-2EALAM3U.js");i=s(e,t)}else if(r==="matilda-oauth"){let{getMatildaOAuthClient:s}=await import("./matildaOAuth2-7COTQQR2.js"),{MatildaContentGenerator:a}=await import("./matildaContentGenerator-O4Z2QPCP.js");try{let l=await s(t,n?{requireCachedCredentials:!0}:void 0);i=new a(l,e,t)}catch(l){throw mo(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(r==="anthropic"){let{createAnthropicContentGenerator:s}=await import("./anthropicContentGenerator-VKFTAIU3.js");i=s(e,t)}else if(r==="gemini"||r==="vertex-ai"){let{createGeminiContentGenerator:s}=await import("./geminiContentGenerator-RJ73DQAP.js");i=s(e,t)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=mo(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 ns=["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"],os=new Set([...ns,...on]),rs=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})",is="[A-Za-z][0-9A-Za-z-]{0,23}",Co="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",ss=new RegExp(`^${se}(?:-${is}(?:\\.${Co})+)?$`),as=63,ls=new RegExp(`^${se}$`),ds=new RegExp(`^${se}-preview\\.(?:0|[1-9]\\d{0,11})$`),cs=new RegExp(`^${se}-canary\\.(?:0|[1-9]\\d{0,11})$`),us=new RegExp(`^${se}-nightly\\.(?:0|[1-9]\\d{0,11})\\.[0-9A-Fa-f]{7,12}$`),ps=new RegExp(`^${se}-(preview|canary|nightly|development|internal)(?:\\.${Co})+$`);function fs(e){return e==="desktop"?"desktop":e===void 0||rs.has(e)?"code_cli":"unknown"}function gs(e){if(e==="android")return"android";if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux")return"linux"}function ms(e){if(e==="x64")return"x64";if(e==="arm64")return"arm64"}function hs(e){if(e===void 0)return"npm";if(e==="desktop")return"direct-download";if(e==="VSCode")return"vscode-marketplace"}function Cs(e,t){if(t==="desktop")return"matilda-desktop";if(e==="VSCode")return"matilda-vscode";if(t==="code_cli")return"matilda-code"}function Ts(e){if(typeof e=="string"&&!(e.length>as||!ss.test(e)))return e}function ys(e){if(e!==void 0)return ls.test(e)?"stable":ds.test(e)?"preview":cs.test(e)?"canary":us.test(e)?"nightly":ps.exec(e)?.[1]}function To(e,t=process.platform,n=process.arch){let o=e.getChannel?.(),r=fs(o),i=Ts(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:e.getCliVersion?.()),s=ys(i),a=gs(t),l=ms(n),u=hs(o),d=Cs(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}:{},...u?{"x-matilda-client-distribution-channel":u}:{},...s?{"x-matilda-client-release-channel":s}:{}}}function ac(e){let t=e.toLowerCase();return os.has(t)||t.startsWith("x-matilda-reported-")}function As(e){let t=e??tn;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 lc(e,t=e.apiKey){return e.authType==="matilda-oauth"?!0:e.authType==="openai"&&!!t&&As(e.baseUrl)}var Es=3e3,Re=1,Ss=24*60*60*1e3,yo=20,Ao=999,Ms=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"]),_s=new Set(["ENOTFOUND","EAI_AGAIN"]),Rs=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),bs=new Set(["ABORT_ERR","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT"]),vs=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]);function xs(e){return`${new URL(e).origin}/api/client-events`}function ks(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 Ht(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??Es);try{let a=await r(xs(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(ks(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 Ft(e,t){let n=typeof e.occurrenceCount=="number"&&Number.isFinite(e.occurrenceCount)?Math.max(1,Math.min(Math.floor(e.occurrenceCount),Ao)):1;return Ht({eventType:"auth_funnel",authStage:e.authStage,authOutcome:e.authOutcome,occurrenceCount:n},t)}function Eo(){try{let e=$.readFileSync(_o(),"utf8"),t=JSON.parse(e);return t.schemaVersion!==Re||!Array.isArray(t.failures)?void 0:{schemaVersion:Re,failures:t.failures.filter(Is)}}catch{return}}function Is(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 So(e){let t=_o();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 Mo(e,t){return e.filter(n=>t-n.lastObservedAtMs<=Ss).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-yo)}function Os(e){let t=To(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 ws(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 Ps(e){if(!(!e||typeof e!="object"))for(let t of["status","statusCode"]){let n=e[t];if(typeof n=="number")return n}}function Ds(e,t){let n=ws(e);if(n&&Ms.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&_s.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&Rs.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&bs.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&vs.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=Ps(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 Ls(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 gc(e,t){let n=Os(t.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=Ds(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=Eo()??{schemaVersion:Re,failures:[]},a=Mo(s.failures,r),l=Ls(a,i);if(l>=0){let u=a[l];a[l]={...u,occurrenceCount:Math.min(u.occurrenceCount+1,Ao),lastObservedAtMs:r}}else a.push(i);return So({schemaVersion:Re,failures:a.slice(-yo)}),!0}async function mc(e){let t=Eo();if(!t)return;let n=Mo(t.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await Ht({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}}So({schemaVersion:Re,failures:o})}function _o(){return lt.join(ve.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var bo=(n=>(n.GCP="gcp",n.LOCAL="local",n))(bo||{}),Sp="local",Mp="http://localhost:4317";f();X();var Us=new Set(["service.version","service.instance.id","session.id"]);function J(e,t){xe.warn(e),t?.push(e)}function vo(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 u;try{u=decodeURIComponent(a)}catch{J(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${l}", using raw value`,t),u=a}n[l]=u}return n}function Vt(e,t,n){for(let o of Us)o in e&&(J(`${t} cannot override reserved key "${o}"; ignoring`,n),delete e[o]);return e}function xo(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 Ro(e){if(e!==void 0){if(e==="local"||e==="local")return"local";if(e==="gcp"||e==="gcp")return"gcp"}}async function Ns(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=Ro(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,u=["grpc","http"].find(N=>N===l);if(l!==void 0&&u===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,c=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=Vt(vo(n.OTEL_RESOURCE_ATTRIBUTES,C),"OTEL_RESOURCE_ATTRIBUTES",C),y=Vt(xo(o.resourceAttributes,C),"settings.telemetry.resourceAttributes",C),E={...T,...y},R=n.OTEL_SERVICE_NAME?.trim();R&&(E["service.name"]=R);let j=Object.keys(E).length?E:void 0,H=be(n.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??o.metrics?.includeSessionId??!1;return{enabled:r,target:s,otlpEndpoint:a,otlpProtocol:u,otlpTracesEndpoint:h,otlpLogsEndpoint:m,otlpMetricsEndpoint:g,logPrompts:d,includeSensitiveSpanAttributes:p,outfile:c,resourceAttributes:j,metrics:{includeSessionId:H},resourceAttributeWarnings:C.length?C:void 0}}export{_t as a,Z as b,Le as c,Do as d,Lo as e,yn as f,Ke as g,jn as h,ar as i,he as j,Ea as k,be as l,Ro as m,Ns as n,te as o,Be as p,Ar as q,It as r,Er as s,xn as t,Sr as u,Mr as v,kn as w,_r as x,In as y,On as z,wn as A,Rr as B,br as C,Kr as D,$r as E,jr as F,Hr as G,Vr as H,Br as I,qr as J,zr as K,Wr as L,To as M,ac as N,lc as O,Ht as P,Ft as Q,gc as R,mc as S,bo as T,Sp as U,Mp as V,Te as W,Qe as X,gl as Y,Ze as Z,yl as _,Al as $,tt as aa,El as ba,Xn as ca,nt as da,Qn as ea,ro as fa,Y as ga,Md as ha,Ii as ia,Oi as ja,wi as ka,_d as la,Rd as ma,Gt as na,bd as oa,Di as pa,vd as qa,ie as ra,st as sa,Id as ta,Od as ua,ao as va,lo as wa,Li as xa,Kt as ya,$t as za,uo as Aa,Gd as Ba,ji as Ca,qd as Da,go as Ea,L as Fa,ts as Ga,ho as Ha,ec as Ia,tc as Ja};
14
14
  /**
15
15
  * @license
16
16
  * Copyright 2026 Matilda Team