@maincode-ai/matilda-code 0.21.2-nightly.20260823.b0c771373 → 0.21.3

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 (39) hide show
  1. package/chunks/{agent-H26MWKNV.js → agent-WBKEN3MM.js} +1 -1
  2. package/chunks/{agent-headless-4PFHOQG6.js → agent-headless-OJM6RWIA.js} +1 -1
  3. package/chunks/{chunk-CFBZKYFB.js → chunk-6QP5C76Y.js} +52 -52
  4. package/chunks/{chunk-EBPJIU5O.js → chunk-7LNKXNEZ.js} +443 -443
  5. package/chunks/{chunk-CNRE4GFU.js → chunk-DBSJNFFU.js} +1 -1
  6. package/chunks/{chunk-5RG6AVD6.js → chunk-FU2PKCG5.js} +2 -2
  7. package/chunks/{chunk-FMNQXZTW.js → chunk-IZ6YBZWM.js} +1 -1
  8. package/chunks/{chunk-MKHNJ5O6.js → chunk-JDXISO3F.js} +2 -2
  9. package/chunks/{chunk-E5OOREZC.js → chunk-ZYW5GLYY.js} +1 -1
  10. package/chunks/{computer-use-SS2QBIWN.js → computer-use-MCXFHFTP.js} +1 -1
  11. package/chunks/{contextCommand-OUZMJMAI.js → contextCommand-G4LS5GW6.js} +1 -1
  12. package/chunks/{edit-TL5Y5RUA.js → edit-KNZAPSGJ.js} +1 -1
  13. package/chunks/{enter-worktree-BZBR2XNW.js → enter-worktree-LJ66TFYR.js} +1 -1
  14. package/chunks/{enterPlanMode-ZN5LSUSX.js → enterPlanMode-P6EIGU3Y.js} +1 -1
  15. package/chunks/{exit-worktree-YZ5EFC22.js → exit-worktree-QVQ3TLW5.js} +1 -1
  16. package/chunks/{exitPlanMode-PF2NGKDC.js → exitPlanMode-I7SGPSG4.js} +1 -1
  17. package/chunks/{geminiContentGenerator-KREJG645.js → geminiContentGenerator-SBVCQ423.js} +1 -1
  18. package/chunks/{glob-5KRIE6H7.js → glob-F5YOX6YA.js} +1 -1
  19. package/chunks/{grep-7DFZLLVF.js → grep-UOIHSM5U.js} +1 -1
  20. package/chunks/{matildaAgentContentGenerator-26CUAKWA.js → matildaAgentContentGenerator-EIQI4YCP.js} +1 -1
  21. package/chunks/{matildaContentGenerator-BSVWQR2W.js → matildaContentGenerator-QMMGDPIK.js} +1 -1
  22. package/chunks/{monitor-H2MC6NKG.js → monitor-GDKHPTET.js} +1 -1
  23. package/chunks/{notebook-edit-5QODZMUP.js → notebook-edit-LWH7H4WX.js} +1 -1
  24. package/chunks/{openaiContentGenerator-EKVEUZ2K.js → openaiContentGenerator-TNZ6SB7H.js} +1 -1
  25. package/chunks/{read-file-HEVXSNSO.js → read-file-URGJTANM.js} +1 -1
  26. package/chunks/{ripGrep-K7VQSLJ5.js → ripGrep-SL4ICAX6.js} +1 -1
  27. package/chunks/{scheduler-F3YFD46T.js → scheduler-EX674HYK.js} +1 -1
  28. package/chunks/{serve-4VYPXKC7.js → serve-FZ4FTA5D.js} +1 -1
  29. package/chunks/{shell-OCVLJZLW.js → shell-LLU55LCI.js} +1 -1
  30. package/chunks/{skill-OJXOVFQ2.js → skill-KSYY6BM6.js} +1 -1
  31. package/chunks/src-UXJDJ3RJ.js +3 -0
  32. package/chunks/{team-create-M4PATT2E.js → team-create-7PFAVYVV.js} +1 -1
  33. package/chunks/{tool-search-47TA6SG4.js → tool-search-7D46IF5G.js} +1 -1
  34. package/chunks/{workflow-7MKBMBDX.js → workflow-2TGFLD2R.js} +2 -2
  35. package/chunks/{write-file-XQIFTZC6.js → write-file-DQ6NYEJ7.js} +1 -1
  36. package/cli.js +402 -402
  37. package/package.json +2 -2
  38. package/sandbox-macos-restrictive-open.sb +22 -2
  39. package/chunks/src-7GFXY42I.js +0 -3
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Lh as T}from"./chunk-EBPJIU5O.js";import{L as b}from"./chunk-QWBNNEV2.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var B=e=>{process.stdout.write(e.endsWith(`
3
+ import{Mh as T}from"./chunk-7LNKXNEZ.js";import{L as b}from"./chunk-QWBNNEV2.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var B=e=>{process.stdout.write(e.endsWith(`
4
4
  `)?e:`${e}
5
5
  `)},m=e=>{process.stderr.write(e.endsWith(`
6
6
  `)?e:`${e}
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as j,d as Zt}from"./chunk-4F4DA5UI.js";import{a as tn,b as At,c as nn,d as on}from"./chunk-DC7LAFZZ.js";import{b as Wt,d as qt,g as yt,j as Yt,k as Jt,s as en,v as ue}from"./chunk-QLEJOI4X.js";import{b as A,e as B}from"./chunk-4J6DC24J.js";import{a as Xt,d as Qt}from"./chunk-SDTWBD62.js";import{Bb as de,Jc as ht,Kc as Ct,Mb as ft,Mc as Tt,Pa as Co,Pb as gt,Ra as To,Rb as mt,Sa as X,Wa as xe,Xa as ke,Ya as Ie,a as _,ab as pt,eb as Oe,f as U,fb as V,na as ut,tb as we,ub as Pe}from"./chunk-CFBZKYFB.js";import{b as rn}from"./chunk-3YLXGE6T.js";import{L as ve,P as zt,R as dt,Y as O,c as Vt,d as ae,e as le,j as at}from"./chunk-QWBNNEV2.js";import{b as lt,c as v,f as ct,g as ce,h as M,i as be,k as jt,l as x,n as J}from"./chunk-FWDMPRKU.js";import{b as g}from"./chunk-GZPNIYVZ.js";import{f as ho}from"./chunk-OWGSC52X.js";g();function Q(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function De(t){let e=t.candidates||0,n=t.thoughts||0;return n>e?e+n:Math.max(e,n)}function yo(t){return t.total&&t.total>0?Math.max(t.total,(t.prompt||0)+De(t)):(t.prompt||0)+De(t)}function Ao(t){let e=Math.max(0,t.thoughtsTokens||0),n=De({candidates:t.outputTokens||0,thoughts:e}),o=Math.max(t.totalTokens||0,(t.inputTokens||0)+n);return{...t,outputTokens:n,thoughtsTokens:e,totalTokens:o}}g();g();var So=/[A-Za-z\u00C0-\u024F]/g;function Eo(t){return t>=1024&&t<=1279||t>=1280&&t<=1327||t>=11744&&t<=11775||t>=42560&&t<=42655||t>=12352&&t<=12543||t>=13312&&t<=19903||t>=19968&&t<=40959||t>=63744&&t<=64255||t>=44032&&t<=55215}function St(t){let e=t.codePointAt(0);return e!==void 0&&Eo(e)}function _o(t){let e=t.match(So)?.length??0;if(e<24)return!1;let n=0;for(let o of t)St(o)&&n++;return n===0||e>=n*8}function Le(t){if(!t||!_o(t))return t;let e="",n=0,o=[...t];for(;n<o.length;){if(!St(o[n])){e+=o[n],n++;continue}let r=n;for(;r>0&&o[r-1]===" ";)r--;let i=n+1;for(;i<o.length&&St(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]===" ")&&(e+=" "),n=i,r<n&&o[r]===" "&&e.endsWith(" ")&&(e=e.slice(0,-1))}return e.replace(/ {2,}/g," ")}g();var Z=O("TAGGED_THINKING_PARSER"),fe=["<think>","<thinking>"],ge=["</think>","</thinking>"],Mo=Math.max(...fe.map(t=>t.length),...ge.map(t=>t.length));function pe(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function Ue(t,e,n){let o=t.length-e;return o<=0||o>Mo?!1:n.some(r=>r.startsWith(t.slice(e,e+o)))}function Ne(t,e,n){return n.find(o=>t.startsWith(o,e))}function _t(t){if(!t)return t;let e=t;return e=e.replace(/<\/?think(?:ing)?>/gi,""),e=e.replace(/[A-Za-z]*long[_-]?message[_-]?THINKING/gi,""),e=e.replace(/\bM?long[_-]?message\b/gi,""),e=e.replace(/(^|[\s>])THINKING(?=[\sA-Z<]|$)/g,"$1"),e!==t&&(e=e.replace(/[ \t]{2,}/g," ")),e}function sn(t){let e=[];for(let n of t){if(n.thought===!0||typeof n.text!="string"){e.push(n);continue}let o=Le(_t(n.text));(o.length>0||/^\s+$/.test(n.text))&&e.push({text:o.length>0?o:n.text})}return e}var Et=class{mode="text";buffer="";parse(e,n=!1){this.buffer+=e;let o=this.buffer.toLowerCase(),r=[],i="",s=0;for(;s<this.buffer.length;){if(this.mode==="text"){let a=Ne(o,s,fe);if(a){Z.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),pe(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=Ne(o,s,ge);if(l){Z.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),pe(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(Ue(o,s,fe)||Ue(o,s,ge)))break}else{let a=Ne(o,s,ge);if(a){Z.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),pe(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=Ne(o,s,fe);if(l){s+=l.length;continue}if(!n&&(Ue(o,s,ge)||Ue(o,s,fe)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(pe(r,i,this.mode),this.buffer=this.buffer.slice(s),Z.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),sn(r)):(this.buffer="",this.mode==="thought"&&i&&Z.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),pe(r,i,this.mode),Z.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),sn(r))}};function an(t){return new Et().parse(t,!0)}var P=O("CONVERTER"),gn="(attached media from previous tool call)";function mn(t,e={}){let n=t.prompt_tokens||0,o=t.completion_tokens||0,r=t.total_tokens||0,i=t.prompt_tokens_details,s=i?.cached_tokens??i?.cachedTokens??t.cached_tokens??t.prompt_cache_hit_tokens??t.cache_read_input_tokens??0,a=t.completion_tokens_details,l=a?.reasoning_tokens??a?.reasoningTokens??t.reasoning_tokens??0,c=Math.max(0,e.estimatedReasoningTokens??0),u=Math.max(0,e.estimatedContentTokens??0),p=l>0?l:c,d=o;p>0&&(o>=p?d=o:d=o+p),(u>0||c>0)&&(d=Math.max(d,u+(l>0?0:c),u+p)),r>n&&(n>0||o>0||p>0)&&(d=Math.max(d,r-n)),p===0&&c>0&&(p=c),p>d&&(p=d);let h=t.usage_is_incomplete===!0||o>0&&n===0||r>0&&n===0&&o===0,m=n,f=r;return(f===0&&(m>0||d>0)||f>0&&m>0&&f<m+d)&&(f=m+d),{promptTokenCount:m,candidatesTokenCount:d,totalTokenCount:f,cachedContentTokenCount:s,thoughtsTokenCount:p,...h?{usageIsIncomplete:!0}:{}}}var Ro=64,ln=1024;function cn(t,e){if(t.length===0)return"";if(e.emittedText.length===0)return e.emittedText=t,e.emittedLength=t.length,t;if(e.cumulativeMode){if(t.startsWith(e.emittedText)){let n=t.slice(e.emittedText.length);return e.emittedText=t,e.emittedLength=t.length,n}return e.emittedText.startsWith(t)?(P.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(P.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),e.cumulativeMode=!1,e.emittedText=t,e.emittedLength+=t.length,t)}if(t.length>e.emittedText.length&&t.startsWith(e.emittedText)){let n=e.emittedText.length,r=n>=ln&&e.emittedLength>n?e.emittedLength:n;if(t.length>r){let i=t.slice(r);return e.emittedText=t,e.emittedLength=t.length,e.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${t.length}b)`),i}}return t===e.emittedText?t.length>=Ro?(e.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<ln&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function hn(t){if(!t||typeof t!="object")return t;let e=JSON.parse(JSON.stringify(t)),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(e)}async function vo(t,e="auto"){let n=[];for(let o of t){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=hn(i.parameters)),s&&(s=qt(s,e)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function bo(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return ko(t,o),Io(t.contents,o,e),o=fn(o),n.cleanOrphanToolCalls&&(o=Ko(o),o=fn(o)),o}function xo(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],r=[],i=[],s=[],a=0;for(let f of o)typeof f=="string"?i.push(f):"text"in f&&f.text?"thought"in f&&f.thought?r.push(f.text):i.push(f.text):"functionCall"in f&&f.functionCall&&(s.push({id:f.functionCall.id||`call_${a}`,type:"function",function:{name:f.functionCall.name||"",arguments:JSON.stringify(f.functionCall.args||{})}}),a+=1);let l={role:"assistant",content:i.join("")||null,refusal:null},c=r.join("");c&&(l.reasoning_content=c),s.length>0&&(l.tool_calls=s);let u=Go(n?.finishReason),p=t.usageMetadata,d={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(d.prompt_tokens_details={cached_tokens:p.cachedContentTokenCount});let h=t.createTime?Number(t.createTime):Date.now(),m=Number.isFinite(h)?Math.floor(h/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:m,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:u,logprobs:null}],usage:d}}function ko(t,e){if(!t.config?.systemInstruction)return;let n=Tn(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function Io(t,e,n){if(Array.isArray(t))for(let o of t)dn(o,e,n);else t&&dn(t,e,n)}function dn(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!Do(t))return;let o=t.parts||[],r=t.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,c=new Set,u=new Set,p=[];for(let d of o){if(typeof d=="string"){i.push({type:"text",text:d});continue}"text"in d&&"thought"in d&&d.thought&&r==="assistant"&&d.text&&s.push(d.text),"text"in d&&d.text&&!("thought"in d&&d.thought)&&i.push({type:"text",text:d.text});let h=Cn(d,n);if(h&&r==="user"&&i.push(h),"functionCall"in d&&d.functionCall&&r==="assistant"){let m=d.functionCall.id;if(m){if(c.has(m)){P.debug(`Dropping duplicate functionCall id=${m} while converting content`);continue}c.add(m)}a.push({id:m||`call_${l}`,type:"function",function:{name:d.functionCall.name||"",arguments:JSON.stringify(d.functionCall.args||{})}}),l+=1}if(d.functionResponse&&r==="user"){let m=d.functionResponse.id;if(m){if(u.has(m))continue;u.add(m)}let f=wo(d.functionResponse,n);if(f){if(n.splitToolMedia&&Array.isArray(f.content)){let C=[],T=[];for(let y of f.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(S=>S.text).join(`
3
+ import{a as j,d as Zt}from"./chunk-4F4DA5UI.js";import{a as tn,b as At,c as nn,d as on}from"./chunk-DC7LAFZZ.js";import{b as Wt,d as qt,g as yt,j as Yt,k as Jt,s as en,v as ue}from"./chunk-QLEJOI4X.js";import{b as A,e as B}from"./chunk-4J6DC24J.js";import{a as Xt,d as Qt}from"./chunk-SDTWBD62.js";import{Bb as de,Jc as ht,Kc as Ct,Mb as ft,Mc as Tt,Pa as Co,Pb as gt,Ra as To,Rb as mt,Sa as X,Wa as xe,Xa as ke,Ya as Ie,a as _,ab as pt,eb as Oe,f as U,fb as V,na as ut,tb as we,ub as Pe}from"./chunk-6QP5C76Y.js";import{b as rn}from"./chunk-3YLXGE6T.js";import{L as ve,P as zt,R as dt,Y as O,c as Vt,d as ae,e as le,j as at}from"./chunk-QWBNNEV2.js";import{b as lt,c as v,f as ct,g as ce,h as M,i as be,k as jt,l as x,n as J}from"./chunk-FWDMPRKU.js";import{b as g}from"./chunk-GZPNIYVZ.js";import{f as ho}from"./chunk-OWGSC52X.js";g();function Q(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function De(t){let e=t.candidates||0,n=t.thoughts||0;return n>e?e+n:Math.max(e,n)}function yo(t){return t.total&&t.total>0?Math.max(t.total,(t.prompt||0)+De(t)):(t.prompt||0)+De(t)}function Ao(t){let e=Math.max(0,t.thoughtsTokens||0),n=De({candidates:t.outputTokens||0,thoughts:e}),o=Math.max(t.totalTokens||0,(t.inputTokens||0)+n);return{...t,outputTokens:n,thoughtsTokens:e,totalTokens:o}}g();g();var So=/[A-Za-z\u00C0-\u024F]/g;function Eo(t){return t>=1024&&t<=1279||t>=1280&&t<=1327||t>=11744&&t<=11775||t>=42560&&t<=42655||t>=12352&&t<=12543||t>=13312&&t<=19903||t>=19968&&t<=40959||t>=63744&&t<=64255||t>=44032&&t<=55215}function St(t){let e=t.codePointAt(0);return e!==void 0&&Eo(e)}function _o(t){let e=t.match(So)?.length??0;if(e<24)return!1;let n=0;for(let o of t)St(o)&&n++;return n===0||e>=n*8}function Le(t){if(!t||!_o(t))return t;let e="",n=0,o=[...t];for(;n<o.length;){if(!St(o[n])){e+=o[n],n++;continue}let r=n;for(;r>0&&o[r-1]===" ";)r--;let i=n+1;for(;i<o.length&&St(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]===" ")&&(e+=" "),n=i,r<n&&o[r]===" "&&e.endsWith(" ")&&(e=e.slice(0,-1))}return e.replace(/ {2,}/g," ")}g();var Z=O("TAGGED_THINKING_PARSER"),fe=["<think>","<thinking>"],ge=["</think>","</thinking>"],Mo=Math.max(...fe.map(t=>t.length),...ge.map(t=>t.length));function pe(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function Ue(t,e,n){let o=t.length-e;return o<=0||o>Mo?!1:n.some(r=>r.startsWith(t.slice(e,e+o)))}function Ne(t,e,n){return n.find(o=>t.startsWith(o,e))}function _t(t){if(!t)return t;let e=t;return e=e.replace(/<\/?think(?:ing)?>/gi,""),e=e.replace(/[A-Za-z]*long[_-]?message[_-]?THINKING/gi,""),e=e.replace(/\bM?long[_-]?message\b/gi,""),e=e.replace(/(^|[\s>])THINKING(?=[\sA-Z<]|$)/g,"$1"),e!==t&&(e=e.replace(/[ \t]{2,}/g," ")),e}function sn(t){let e=[];for(let n of t){if(n.thought===!0||typeof n.text!="string"){e.push(n);continue}let o=Le(_t(n.text));(o.length>0||/^\s+$/.test(n.text))&&e.push({text:o.length>0?o:n.text})}return e}var Et=class{mode="text";buffer="";parse(e,n=!1){this.buffer+=e;let o=this.buffer.toLowerCase(),r=[],i="",s=0;for(;s<this.buffer.length;){if(this.mode==="text"){let a=Ne(o,s,fe);if(a){Z.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),pe(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=Ne(o,s,ge);if(l){Z.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),pe(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(Ue(o,s,fe)||Ue(o,s,ge)))break}else{let a=Ne(o,s,ge);if(a){Z.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),pe(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=Ne(o,s,fe);if(l){s+=l.length;continue}if(!n&&(Ue(o,s,ge)||Ue(o,s,fe)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(pe(r,i,this.mode),this.buffer=this.buffer.slice(s),Z.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),sn(r)):(this.buffer="",this.mode==="thought"&&i&&Z.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),pe(r,i,this.mode),Z.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),sn(r))}};function an(t){return new Et().parse(t,!0)}var P=O("CONVERTER"),gn="(attached media from previous tool call)";function mn(t,e={}){let n=t.prompt_tokens||0,o=t.completion_tokens||0,r=t.total_tokens||0,i=t.prompt_tokens_details,s=i?.cached_tokens??i?.cachedTokens??t.cached_tokens??t.prompt_cache_hit_tokens??t.cache_read_input_tokens??0,a=t.completion_tokens_details,l=a?.reasoning_tokens??a?.reasoningTokens??t.reasoning_tokens??0,c=Math.max(0,e.estimatedReasoningTokens??0),u=Math.max(0,e.estimatedContentTokens??0),p=l>0?l:c,d=o;p>0&&(o>=p?d=o:d=o+p),(u>0||c>0)&&(d=Math.max(d,u+(l>0?0:c),u+p)),r>n&&(n>0||o>0||p>0)&&(d=Math.max(d,r-n)),p===0&&c>0&&(p=c),p>d&&(p=d);let h=t.usage_is_incomplete===!0||o>0&&n===0||r>0&&n===0&&o===0,m=n,f=r;return(f===0&&(m>0||d>0)||f>0&&m>0&&f<m+d)&&(f=m+d),{promptTokenCount:m,candidatesTokenCount:d,totalTokenCount:f,cachedContentTokenCount:s,thoughtsTokenCount:p,...h?{usageIsIncomplete:!0}:{}}}var Ro=64,ln=1024;function cn(t,e){if(t.length===0)return"";if(e.emittedText.length===0)return e.emittedText=t,e.emittedLength=t.length,t;if(e.cumulativeMode){if(t.startsWith(e.emittedText)){let n=t.slice(e.emittedText.length);return e.emittedText=t,e.emittedLength=t.length,n}return e.emittedText.startsWith(t)?(P.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(P.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),e.cumulativeMode=!1,e.emittedText=t,e.emittedLength+=t.length,t)}if(t.length>e.emittedText.length&&t.startsWith(e.emittedText)){let n=e.emittedText.length,r=n>=ln&&e.emittedLength>n?e.emittedLength:n;if(t.length>r){let i=t.slice(r);return e.emittedText=t,e.emittedLength=t.length,e.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${t.length}b)`),i}}return t===e.emittedText?t.length>=Ro?(e.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<ln&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function hn(t){if(!t||typeof t!="object")return t;let e=JSON.parse(JSON.stringify(t)),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(e)}async function vo(t,e="auto"){let n=[];for(let o of t){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=hn(i.parameters)),s&&(s=qt(s,e)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function bo(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return ko(t,o),Io(t.contents,o,e),o=fn(o),n.cleanOrphanToolCalls&&(o=Ko(o),o=fn(o)),o}function xo(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],r=[],i=[],s=[],a=0;for(let f of o)typeof f=="string"?i.push(f):"text"in f&&f.text?"thought"in f&&f.thought?r.push(f.text):i.push(f.text):"functionCall"in f&&f.functionCall&&(s.push({id:f.functionCall.id||`call_${a}`,type:"function",function:{name:f.functionCall.name||"",arguments:JSON.stringify(f.functionCall.args||{})}}),a+=1);let l={role:"assistant",content:i.join("")||null,refusal:null},c=r.join("");c&&(l.reasoning_content=c),s.length>0&&(l.tool_calls=s);let u=Go(n?.finishReason),p=t.usageMetadata,d={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(d.prompt_tokens_details={cached_tokens:p.cachedContentTokenCount});let h=t.createTime?Number(t.createTime):Date.now(),m=Number.isFinite(h)?Math.floor(h/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:m,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:u,logprobs:null}],usage:d}}function ko(t,e){if(!t.config?.systemInstruction)return;let n=Tn(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function Io(t,e,n){if(Array.isArray(t))for(let o of t)dn(o,e,n);else t&&dn(t,e,n)}function dn(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!Do(t))return;let o=t.parts||[],r=t.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,c=new Set,u=new Set,p=[];for(let d of o){if(typeof d=="string"){i.push({type:"text",text:d});continue}"text"in d&&"thought"in d&&d.thought&&r==="assistant"&&d.text&&s.push(d.text),"text"in d&&d.text&&!("thought"in d&&d.thought)&&i.push({type:"text",text:d.text});let h=Cn(d,n);if(h&&r==="user"&&i.push(h),"functionCall"in d&&d.functionCall&&r==="assistant"){let m=d.functionCall.id;if(m){if(c.has(m)){P.debug(`Dropping duplicate functionCall id=${m} while converting content`);continue}c.add(m)}a.push({id:m||`call_${l}`,type:"function",function:{name:d.functionCall.name||"",arguments:JSON.stringify(d.functionCall.args||{})}}),l+=1}if(d.functionResponse&&r==="user"){let m=d.functionResponse.id;if(m){if(u.has(m))continue;u.add(m)}let f=wo(d.functionResponse,n);if(f){if(n.splitToolMedia&&Array.isArray(f.content)){let C=[],T=[];for(let y of f.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(S=>S.text).join(`
4
4
  `);f.content=y||"[media attached in following user message]",p.push(...C)}}e.push(f)}}}if(p.length>0&&e.push({role:"user",content:[{type:"text",text:gn},...p]}),r==="assistant"){if(i.length===0&&a.length===0&&s.length===0)return;let h={role:"assistant",content:i.filter(f=>f.type==="text").map(f=>f.text).join("")||(s.length>0?"":null)};a.length>0&&(h.tool_calls=a);let m=s.join("");m&&(h.reasoning_content=m),e.push(h);return}i.length>0&&e.push({role:"user",content:i})}function Oo(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="object"){let e=t,n=e.output;if(typeof n=="string")return n;let o=e.error;if(typeof o=="string")return o}try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function wo(t,e){let n=Oo(t.response),o=[];n&&o.push({type:"text",text:n});for(let r of t.parts||[]){if("text"in r&&typeof r.text=="string"){r.text.length>0&&o.push({type:"text",text:r.text});continue}let i=Cn(r,e);i&&o.push(i)}return o.length===0?{role:"tool",tool_call_id:t.id||"",content:""}:{role:"tool",tool_call_id:t.id||"",content:o}}function Cn(t,e){let{modalities:n}=e;if(t.inlineData?.mimeType&&t.inlineData?.data){let o=t.inlineData.mimeType,r=un(o),i=t.inlineData.displayName||o;if(r==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${t.inlineData.data}`}}:z("image",i,e);if(o==="application/pdf")return n.pdf?{type:"file",file:{filename:t.inlineData.displayName||"document.pdf",file_data:`data:${o};base64,${t.inlineData.data}`}}:z("pdf",i,e);if(r==="audio"){if(!n.audio)return z("audio",i,e);let s=Po(o);if(s)return{type:"input_audio",input_audio:{data:`data:${o};base64,${t.inlineData.data}`,format:s}}}return r==="video"?n.video?{type:"video_url",video_url:{url:`data:${o};base64,${t.inlineData.data}`}}:z("video",i,e):{type:"text",text:`Unsupported inline media type: ${o} (${i}).`}}if(t.fileData?.mimeType&&t.fileData?.fileUri){let o=t.fileData.displayName||"file",r=t.fileData.fileUri,i=t.fileData.mimeType,s=un(i);if(s==="image")return n.image?{type:"image_url",image_url:{url:r}}:z("image",o,e);if(i==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:r}}:z("pdf",o,e);if(s==="video")return n.video?{type:"video_url",video_url:{url:r}}:z("video",o,e);let a=t.fileData.displayName?` (${t.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${i}${a}.`}}return null}function z(t,e,n){P.warn(`Model '${n.model}' does not support ${t} input. Replacing with text placeholder: ${e}`);let o;return t==="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
5
  /extensions install https://github.com/anthropics/skills:document-skills`:o=`This model does not support ${t} 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 ${t} file: "${e}". ${o}]`}}function un(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function Po(t){return t.includes("wav")?"wav":t.includes("mp3")||t.includes("mpeg")?"mp3":null}function Do(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&Array.isArray(t.parts)}function Tn(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>Tn(e)).filter(Boolean).join(`
6
6
  `):typeof t=="object"&&t!==null&&"parts"in t&&t.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
@@ -8,7 +8,7 @@ import{a as j,d as Zt}from"./chunk-4F4DA5UI.js";import{a as tn,b as At,c as nn,d
8
8
  ${n}`:n;return{...o,text:a}}return e}};g();function Hn(t){switch(t){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 Bn(t){switch(t){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 F=class extends Error{constructor(e){super(e),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},je=class extends F{code="STRICT_MISSING_CREDENTIALS";constructor(e,n,o){let r=e||"(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 F{code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},We=class extends F{code="MISSING_API_KEY";constructor(e){super(`Missing API key for ${e.authType} auth. Current model: '${e.model||"(unknown)"}', baseUrl: '${e.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${e.envKey}'.`)}},qe=class extends F{code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}},Ye=class extends F{code="MISSING_BASE_URL";constructor(e){super(`Missing baseUrl for modelProviders model '${e.model||"(unknown)"}'. Configure modelProviders.${e.authType||"(unknown)"}[].baseUrl.`)}},Je=class extends F{code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};g();import Kr from"node:process";g();var Vn={image:!0,pdf:!0,audio:!0,video:!0},Fr=[[/^gemini-3/,Vn],[/^gemini-/,Vn],[/^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 Ce(t){let e=en(t);for(let[n,o]of Fr)if(n.test(e))return{...o};return{}}g();var Xe="$runtime|";function Na(t){let e=t;for(;e.startsWith(Xe);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}g();g();g();var Qe=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],jn=["model","apiKey","apiKeyEnvKey","baseUrl"],Ze=[...jn,...Qe],Ha={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:[]}},Ba={openai:Zt,"matilda-oauth":j},et=[{id:"coder-model",name:"coder-model",description:"Matilda 3.6 Plus \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:!0}}],Va=et.map(t=>t.id);var kt=O("MODEL_REGISTRY");function zn(t){if(Object.values(G).includes(t))return t}function Gr(t){return/^minimax-m3/i.test(t.trim().toLowerCase())}function Wn(t,e){return e?`${t}\0${e}`:t}var tt=class{modelsByAuthType;getDefaultBaseUrl(e){switch(e){case"matilda-oauth":return"DYNAMIC_MATILDA_OAUTH_BASE_URL";case"openai":return Yt;default:return""}}constructor(e){if(this.modelsByAuthType=new Map,this.registerAuthTypeModels("matilda-oauth",et),e)for(let[n,o]of Object.entries(e)){let r=zn(n);if(!r){kt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}registerAuthTypeModels(e,n){let o=new Map;for(let r of n){let i=Wn(r.id,r.baseUrl);if(o.has(i)){kt.warn(`Duplicate model id "${r.id}"${r.baseUrl?` with baseUrl "${r.baseUrl}"`:""} for authType "${e}". Using the first registered config.`);continue}let s=this.resolveModelConfig(r,e);o.set(i,s)}this.modelsByAuthType.set(e,o)}getModelsForAuthType(e){let n=this.modelsByAuthType.get(e);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??ue(o.id),modalities:o.generationConfig.modalities,baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(e,n,o){let r=this.modelsByAuthType.get(e);if(!r)return;if(o)return r.get(Wn(n,o));let i=r.get(n);if(i)return i;for(let s of r.values())if(s.id===n)return s}hasModel(e,n,o){return this.getModel(e,n,o)!==void 0}getDefaultModelForAuthType(e){if(e==="matilda-oauth")return this.getModel(e,j);let n=this.modelsByAuthType.get(e);if(!(!n||n.size===0))return Array.from(n.values())[0]}resolveModelConfig(e,n){this.validateModelConfig(e,n);let o={...e.generationConfig??{}};return(o.modalities===void 0||Gr(e.id))&&(o.modalities=Ce(e.id)),{...e,authType:n,name:e.name||e.id,baseUrl:e.baseUrl||this.getDefaultBaseUrl(n),generationConfig:o,capabilities:e.capabilities||{}}}validateModelConfig(e,n){if(!e.id)throw new Error(`Model config in authType '${n}' missing required field: id`)}reloadModels(e){for(let n of this.modelsByAuthType.keys())n!=="matilda-oauth"&&this.modelsByAuthType.delete(n);if(e)for(let[n,o]of Object.entries(e)){let r=zn(n);if(!r){kt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}};var qn=class t{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;requireCachedMatildaCredentialsOnce=!1;hasManualCredentials=!1;onModelChange;authTypeWasExplicitlyProvided;runtimeModelSnapshots=new Map;activeRuntimeModelSnapshotId;static deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>t.deepClone(o));let n={};for(let o of Object.keys(e))n[o]=t.deepClone(e[o]);return n}constructor(e={}){this.modelRegistry=new tt(e.modelProvidersConfig),this.onModelChange=e.onModelChange,this._generationConfig={...e.generationConfig||{}},this.generationConfigSources=e.generationConfigSources||{},this.authTypeWasExplicitlyProvided=e.initialAuthType!==void 0,this.currentAuthType=e.initialAuthType}createStateSnapshotForRollback(){return{currentAuthType:this.currentAuthType,generationConfig:t.deepClone(this._generationConfig),generationConfigSources:t.deepClone(this.generationConfigSources),strictModelProviderSelection:this.strictModelProviderSelection,requireCachedMatildaCredentialsOnce:this.requireCachedMatildaCredentialsOnce,hasManualCredentials:this.hasManualCredentials,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(e){this.currentAuthType=e.currentAuthType,this._generationConfig=e.generationConfig,this.generationConfigSources=e.generationConfigSources,this.strictModelProviderSelection=e.strictModelProviderSelection,this.requireCachedMatildaCredentialsOnce=e.requireCachedMatildaCredentialsOnce,this.hasManualCredentials=e.hasManualCredentials,this.activeRuntimeModelSnapshotId=e.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||j}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModelsForAuthType(this.currentAuthType):[]}getAvailableModelsForAuthType(e){return this.modelRegistry.getModelsForAuthType(e)}getAllConfiguredModels(e){let n=e&&e.length>0?e:Object.values(G),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(e,n){return this.modelRegistry.hasModel(e,n)}getResolvedModel(e,n){return this.modelRegistry.getModel(e,n)}isManagedMatildaResolvedModel(e){return e?.id===At&&e?.envKey===tn&&e?.baseUrl===on&&e?.generationConfig?.openAIRequestProfile==="matilda-code"}isManagedMatildaModel(e){let n=e.trim();return!n||!this.currentAuthType?!1:this.isManagedMatildaResolvedModel(this.modelRegistry.getModel(this.currentAuthType,n))}getPublicModelId(e){return this.isManagedMatildaModel(e)?At:e}getModelDisplayName(e){return this.isManagedMatildaModel(e)?nn:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,e)?.name??e:e}async setModel(e,n){if(this.currentAuthType==="matilda-oauth"&&e===j){this.strictModelProviderSelection=!1,this._generationConfig.model=e,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,e)){await this.switchModel(this.currentAuthType,e);return}let o=this.createStateSnapshotForRollback();try{this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.applyRawModelDerivedDefaults(e),this.onModelChange&&this.currentAuthType&&await this.onModelChange(this.currentAuthType,!0)}catch(r){throw this.rollbackToStateSnapshot(o),r}}applyRawModelDerivedDefaults(e){this.shouldUpdateModelDerivedDefault("modalities")&&(this._generationConfig.modalities=Ce(e),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=ue(e,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"})}shouldUpdateModelDerivedDefault(e){let n=this.generationConfigSources[e];return n===void 0||n.kind==="computed"||n.kind==="default"||n.kind==="modelProviders"||n.kind==="programmatic"||n.kind==="unknown"}async switchModel(e,n,o){let r=this.extractRuntimeModelSnapshotId(n);if(r){await this.switchToRuntimeModel(r);return}let i=this.createStateSnapshotForRollback();e==="matilda-oauth"&&o?.requireCachedCredentials&&(this.requireCachedMatildaCredentialsOnce=!0);try{let s=e!==this.currentAuthType;this.currentAuthType=e;let a=this.modelRegistry.getModel(e,n,o?.baseUrl);if(!a)throw new Error(`Model '${n}' not found for authType '${e}'`);let l=i.generationConfig.model||"",c=!s&&l?this.modelRegistry.getModel(e,l,i.generationConfig.baseUrl)??this.modelRegistry.getModel(e,l):void 0,u=e!=="matilda-oauth"&&!s&&!!i.generationConfig.apiKey&&!!a.envKey&&c?.envKey===a.envKey&&c.baseUrl===a.baseUrl,p=u?i.generationConfig.apiKey:void 0,d=u?i.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(a),!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,d&&(this.generationConfigSources.apiKey=t.deepClone(d))),this.activeRuntimeModelSnapshotId=void 0;let h=s?!0:this.checkRequiresRefresh(l);this.onModelChange&&await this.onModelChange(e,h)}catch(s){throw this.rollbackToStateSnapshot(i),s}}buildRuntimeModelSnapshotId(e,n){return`${Xe}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(Xe))return this.runtimeModelSnapshots.has(e)?e:void 0;if(this.runtimeModelSnapshots.has(e))return e}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}mergeSettingsGenerationConfig(e){if(e)for(let n of Qe)!(n in this._generationConfig)&&n in e&&(this._generationConfig[n]=e[n],this.generationConfigSources[n]={kind:"settings",detail:`model.generationConfig.${n}`})}updateCredentials(e,n){(e.apiKey||e.baseUrl||e.model)&&(this.hasManualCredentials=!0,this.clearProviderSourcedConfig()),e.apiKey&&(this._generationConfig.apiKey=e.apiKey,this.generationConfigSources.apiKey={kind:"programmatic",detail:"updateCredentials"}),e.baseUrl&&(this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"programmatic",detail:"updateCredentials"}),e.model&&(this._generationConfig.model=e.model,this.generationConfigSources.model={kind:"programmatic",detail:"updateCredentials"}),this.strictModelProviderSelection=!1,this._generationConfig.apiKeyEnvKey=void 0,n&&this.mergeSettingsGenerationConfig(n),this.syncRuntimeModelSnapshotWithCredentials()}syncRuntimeModelSnapshotWithCredentials(){let e=this.currentAuthType,{model:n,apiKey:o,baseUrl:r}=this._generationConfig;if(!(!n||!e||!o||!r)&&!this.modelRegistry.hasModel(e,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 e of Ze)this.generationConfigSources[e]?.kind==="modelProviders"&&(delete this._generationConfig[e],delete this.generationConfigSources[e])}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=!1}consumeRequireCachedCredentialsFlag(){let e=this.requireCachedMatildaCredentialsOnce;return this.requireCachedMatildaCredentialsOnce=!1,e}applyResolvedModelDefaults(e){if(this.strictModelProviderSelection=!0,this.hasManualCredentials=!1,this._generationConfig.model=e.id,this.generationConfigSources.model={kind:"modelProviders",authType:e.authType,modelId:e.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),e.envKey!==void 0){let o=Kr.env[e.envKey];o&&(this._generationConfig.apiKey=o,this.generationConfigSources.apiKey={kind:"env",envKey:e.envKey,via:{kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}),this._generationConfig.apiKeyEnvKey=e.envKey,this.generationConfigSources.apiKeyEnvKey={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"baseUrl"};let n=e.generationConfig;for(let o of Qe)this._generationConfig[o]=n[o],this.generationConfigSources[o]={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:`generationConfig.${o}`};n.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=ue(e.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=Ce(e.id),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"})}checkRequiresRefresh(e){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,e);return!r||!o||r.envKey!==o.envKey||r.baseUrl!==o.baseUrl}syncAfterAuthRefresh(e,n){this.strictModelProviderSelection=!1;let o=this.currentAuthType;this.currentAuthType=e;let r=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,i=n?this.modelRegistry.getModel(e,n,r)??this.modelRegistry.getModel(e,n):void 0;if(i){let h=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==i.envKey||this._generationConfig.baseUrl!==i.baseUrl),m=o===e&&this._generationConfig.model===n&&!h,f=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"),S=y?this._generationConfig.baseUrl:void 0,R=y&&T?{...T}:void 0;this.applyResolvedModelDefaults(i),m&&!this._generationConfig.apiKey&&f&&(this._generationConfig.apiKey=f,C&&(this.generationConfigSources.apiKey=C)),S&&(this._generationConfig.baseUrl=S,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!==e)&&(n===void 0||!this.modelRegistry.hasModel(e,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(e);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(e){this.onModelChange=e}detectAndCaptureRuntimeModel(){let{model:e,apiKey:n,baseUrl:o,apiKeyEnvKey:r,...i}=this._generationConfig,s=this.currentAuthType;if(!e||!s)return;if(this.modelRegistry.hasModel(s,e,o)){this.clearRuntimeModelSnapshotForAuthType(s);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(s,e),c={id:l,authType:s,modelId:e,apiKey:n,baseUrl:o,apiKeyEnvKey:r,generationConfig:i,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(l,c),this.activeRuntimeModelSnapshotId=l,this.cleanupOldRuntimeModelSnapshots(),l}getActiveRuntimeModelSnapshot(){if(this.activeRuntimeModelSnapshotId)return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId)}getActiveRuntimeModelSnapshotId(){return this.activeRuntimeModelSnapshotId}async switchToRuntimeModel(e){let n=this.runtimeModelSnapshots.get(e);if(!n)throw new Error(`Runtime model snapshot '${e}' not found`);let o=this.createStateSnapshotForRollback();try{let r=n.authType!==this.currentAuthType;this.currentAuthType=n.authType,this.activeRuntimeModelSnapshotId=e,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 e=this.getActiveRuntimeModelSnapshot();if(e)return{id:e.modelId,label:e.modelId,authType:e.authType,isVision:!1,contextWindowSize:e.generationConfig?.contextWindowSize,isRuntimeModel:!0,runtimeSnapshotId:e.id}}clearRuntimeModelSnapshotForAuthType(e){for(let[n,o]of this.runtimeModelSnapshots.entries())o.authType===e&&(this.runtimeModelSnapshots.delete(n),this.activeRuntimeModelSnapshotId===n&&(this.activeRuntimeModelSnapshotId=void 0))}cleanupOldRuntimeModelSnapshots(){let e=new Map;for(let n of this.runtimeModelSnapshots.values()){let o=e.get(n.authType);(!o||n.createdAt>o.createdAt)&&e.set(n.authType,n)}this.runtimeModelSnapshots.clear();for(let n of e.values())this.runtimeModelSnapshots.set(n.id,n);this.activeRuntimeModelSnapshotId&&!this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)&&(this.activeRuntimeModelSnapshotId=void 0)}reloadModelProvidersConfig(e){this.modelRegistry.reloadModels(e)}};g();import{readFileSync as ri}from"node:fs";import{join as ii}from"node:path";g();g();import{randomBytes as $r,createHash as Hr}from"node:crypto";function Yn(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function It(){let t=$r(32).toString("base64url"),e=Hr("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function Te(t,e){return{accessToken:t.access_token,refreshToken:t.refresh_token??e?.refreshToken,expiresAt:Date.now()+(t.expires_in??3600)*1e3,idToken:t.id_token??e?.idToken}}async function Ot(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!Yn(n.hostname))throw new Error(`Refusing OAuth discovery over insecure transport: ${n.origin}`);let o=await fetch(n,{headers:{accept:"application/json"}});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}}g();import{promises as nt,openSync as Br,closeSync as Vr,unlinkSync as Jn,statSync as jr}from"node:fs";import{dirname as zr}from"node:path";var Wr=1e4,qr=3e4,Yr=50;function wt(t){let e=async()=>{try{let r=await nt.readFile(t,"utf8"),i=JSON.parse(r);return i&&typeof i=="object"?i:{}}catch(r){if(r.code==="ENOENT")return{};throw r}},n=async r=>{await nt.mkdir(zr(t),{recursive:!0}),await nt.writeFile(t,JSON.stringify(r,null,2),{mode:384}),await nt.chmod(t,384).catch(()=>{})};return{store:{async get(r){return(await e())[r]??null},async set(r,i){let s=await e();s[r]=i,await n(s)},async remove(r){let i=await e();r in i&&(delete i[r],await n(i))}},lock:Jr(`${t}.lock`)}}function Jr(t){let e=Promise.resolve();return n=>{let o=e.then(async()=>{await Xr(t);try{return await n()}finally{Qr(t)}});return e=o.then(()=>{},()=>{}),o}}async function Xr(t){let e=Date.now()+Wr;for(;;)try{Vr(Br(t,"wx"));return}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-jr(t).mtimeMs>qr){Jn(t);continue}}catch{continue}if(Date.now()>e)throw new Error(`Timed out acquiring credential lock at ${t}`);await Zr(Yr)}}function Qr(t){try{Jn(t)}catch{}}function Zr(t){return new Promise(e=>setTimeout(e,t))}g();var te=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function Pt(t){let e=t.storageKey??"default",n=t.fetchImpl??fetch,o=t.expirySkewMs??6e4,r=null,i=async()=>{let l=await t.store.get(e);if(!l)return null;try{let c=JSON.parse(l);return c.accessToken?c:null}catch{return null}},s=l=>l.expiresAt-Date.now()>o,a=l=>t.lock(async()=>{let c=await i()??l;if(c.accessToken!==l.accessToken&&s(c))return c.accessToken;if(!c.refreshToken)throw new te("No refresh token available \u2014 sign in again.");let u=await n(t.tokenEndpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:c.refreshToken})});if(!u.ok){let h=await u.text().catch(()=>"");throw u.status>=400&&u.status<500&&ei(h)==="invalid_grant"?(await t.store.remove(e),new te):new Error(`Token refresh failed (${u.status})`)}let p=await u.json(),d=Te(p,c);return await t.store.set(e,JSON.stringify(d)),d.accessToken});return{async getAccessToken(l){let c=await i();if(!c)throw new te("Not signed in.");return!l?.forceRefresh&&s(c)?c.accessToken:(r||(r=a(c).finally(()=>{r=null})),r)}}}function ei(t){try{return JSON.parse(t).error}catch{return}}g();import{createServer as ti}from"node:http";import{randomBytes as ni}from"node:crypto";async function Dt(t){if(t.transport.kind!=="loopback")throw new Error(`Unsupported login transport: ${t.transport.kind}`);if(t.signal?.aborted)throw new Error("Login aborted");let e=m=>t.onEvent?.(m),{codeVerifier:n,codeChallenge:o}=It(),r=ni(16).toString("hex"),i=t.timeoutMs??5*60*1e3,s=t.transport.successRedirect;e({type:"state",status:"idle"});let a,l,c=new Promise((m,f)=>{a=m,l=f});c.catch(()=>{});let u=ti((m,f)=>{let C=new URL(m.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){f.writeHead(404).end();return}let T=C.searchParams.get("error"),y=C.searchParams.get("state"),S=C.searchParams.get("code");if(T){let R=C.searchParams.get("error_description"),$=R?`OAuth error: ${T} (${R})`:`OAuth error: ${T}`;f.writeHead(400,{"content-type":"text/plain; charset=utf-8"}).end(`Sign-in failed: ${T}
9
9
  `,()=>l(new Error($)));return}if(y!==r){f.writeHead(400).end("State mismatch"),l(new Error("OAuth state mismatch"));return}if(!S){f.writeHead(400).end("Missing authorization code");return}oi(f,s,()=>a(S))}),p=await new Promise((m,f)=>{u.once("error",f),u.listen(t.transport.port??0,"127.0.0.1",()=>{m(u.address().port)})}),d=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"));t.signal?.addEventListener("abort",h,{once:!0});try{let m=`http://127.0.0.1:${p}/callback`,f=new URL(t.metadata.authorization_endpoint);f.searchParams.set("client_id",t.clientId),f.searchParams.set("response_type","code"),f.searchParams.set("redirect_uri",m),f.searchParams.set("code_challenge",o),f.searchParams.set("code_challenge_method","S256"),f.searchParams.set("state",r),f.searchParams.set("prompt","select_account"),f.searchParams.set("scope",t.scope??"openid offline_access");let C=f.toString();e({type:"authorize_url",url:C}),e({type:"state",status:"awaiting_user"}),t.openBrowser&&await t.openBrowser(C);let T=await c;e({type:"state",status:"exchanging"});let y=await fetch(t.metadata.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,code:T,code_verifier:n,redirect_uri:m})});if(!y.ok){let R=await y.text().catch(()=>"");throw new Error(`Token exchange failed (${y.status}): ${R}`)}let S=Te(await y.json());return e({type:"state",status:"authenticated"}),S}catch(m){throw e({type:"state",status:"error"}),m}finally{clearTimeout(d),t.signal?.removeEventListener("abort",h),u.close()}}function oi(t,e,n){t.writeHead(302,{location:e}).end(n)}var ye="matilda-code",Xn="matilda-desktop",si="openid profile email offline_access",Ae="MATILDA_API_KEY",ai="matilda";function Se(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function Qn(){return ii(ve.getGlobalMatildaDir(),"matilda-auth.json")}function ot(){return wt(Qn())}function li(t){return t==="desktop"}function Ee(t){return t?.clientId?t.clientId:li(t?.channel)?Xn:ye}function oe(t){return`matilda:${t}`}function rt(t){return`${oe(t)}:refresh-rejected`}function _e(t){return t===ye?[oe(t),ai]:[oe(t)]}function ci(){try{let t=ri(Qn(),"utf8");return JSON.parse(t)}catch{return{}}}function Lt(t){if(!t)return null;try{let e=JSON.parse(t);return typeof e?.accessToken=="string"&&typeof e?.baseUrl=="string"?e:null}catch{return null}}function di(t,e){return Se(t)===Se(e)}function ui(t){if(!t)return{};try{let e=t.split(".")[1],n=Buffer.from(e.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(n);return{sub:o.sub,email:o.email,name:o.name}}catch{return{}}}function pi(t,e){let n=ui(t.idToken);return{accessToken:t.accessToken,accessTokenExpiresAt:t.expiresAt,refreshToken:t.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:e}}async function Zn(t){try{return await Ot(t)}catch{return{issuer:t,authorization_endpoint:`${t}/api/auth/oauth/authorize`,token_endpoint:`${t}/api/auth/oauth/token`,device_authorization_endpoint:`${t}/api/auth/oauth/device/code`}}}function q(t){try{let e=ci(),n=Ee(t);for(let o of _e(n)){let r=Lt(e[o]);if(r)return r}return null}catch{return null}}async function fi(t){let e=Ee(t),n=ot().store;for(let o of _e(e))await n.remove(o);await n.set(rt(e),"1"),delete process.env[Ae]}function gi(t){return t instanceof Error?t.code==="invalid_grant"||t.name==="InvalidGrantError"?!0:t.message==="Token refresh failed (401)":!1}function ne(t){Ut({authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:t.occurrenceCount},{baseUrl:t.baseUrl,token:t.token}).catch(()=>{})}async function mi(t,e){let n=Ee(e),o=ot().store;await o.set(oe(n),JSON.stringify(t)),await o.remove(rt(n));for(let r of _e(n))r!==oe(n)&&await o.remove(r);process.env[Ae]=t.accessToken}async function hi(t){let e=Ee(t),n=ot().store;for(let o of _e(e))await n.remove(o);await n.remove(rt(e)),delete process.env[Ae]}function zl(t){let e=q(t);return e?{authenticated:!0,userId:e.userId,email:e.email,displayName:e.displayName,baseUrl:e.baseUrl,accessTokenExpiresAt:e.accessTokenExpiresAt}:{authenticated:!1}}async function Wl(t){let e={channel:t?.channel,clientId:t?.clientId},n=q(e);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:t?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}await hi(e)}async function Nt(t){let e=Ee(t),n=oe(e),o=q({channel:t?.channel,clientId:e});if(!o||t?.baseUrl&&!di(o.baseUrl,t.baseUrl))return t?.fallbackAccessToken??process.env[Ae]??"";let r=Se(o.baseUrl),i=await Zn(r),{store:s,lock:a}=ot(),l=Ci(s,a,i.token_endpoint,o.baseUrl,e,n,t?.signal),c=e===ye&&(!!t?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=3e5),u;try{u=await l.getAccessToken({forceRefresh:t?.forceRefresh})}catch(p){throw c&&ne({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"}),e===Xn&&gi(p)&&await fi({channel:t?.channel,clientId:e}),p}return c&&ne({baseUrl:o.baseUrl,token:u,authStage:"refresh",authOutcome:"succeeded"}),process.env[Ae]=u,u}async function ql(t){await Nt(t);let e=q(t);if(!e)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return e}function Ci(t,e,n,o,r,i,s){let a=_e(r);return Pt({tokenEndpoint:n,clientId:r,store:{get:async u=>{let p=u===i?a:[u],d=null;for(let m of p)if(d=Lt(await t.get(m)),d)break;if(!d?.accessToken)return null;let h={accessToken:d.accessToken,refreshToken:d.refreshToken,expiresAt:d.accessTokenExpiresAt};return JSON.stringify(h)},set:async(u,p)=>{let d=JSON.parse(p),h=u===i?a:[u],m={};for(let C of h){let T=Lt(await t.get(C));if(T){m=T;break}}let f={...m,accessToken:d.accessToken,accessTokenExpiresAt:d.expiresAt,refreshToken:d.refreshToken??m.refreshToken??"",baseUrl:m.baseUrl??o};await t.set(i,JSON.stringify(f)),await t.remove(rt(r));for(let C of a)C!==i&&await t.remove(C)},remove:async u=>{let p=u===i?a:[u];for(let d of p)await t.remove(d)}},storageKey:i,lock:e,fetchImpl:(u,p)=>fetch(u,{...p,signal:s}),expirySkewMs:3e5})}function Ti(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&rn()}async function Yl(t){let e=Se(t.baseUrl),n=await Zn(e),o="",r=0,i=0,s={},a=p=>{s[p]=(s[p]??0)+1},c=await(p=>(r+=1,Dt({metadata:n,clientId:ye,scope:p,transport:{kind:"loopback",successRedirect:`${e}/api/auth/oauth/success?client_id=${encodeURIComponent(ye)}`},signal:t.signal,onEvent:d=>{d.type==="authorize_url"&&(o=d.url,t.onAuthorizeUrl?.(d.url)),d.type==="state"&&d.status==="exchanging"&&(i+=1)},openBrowser:async d=>{if(t.openBrowser===!1||!Ti()){a("skipped");return}try{let{default:h}=await import("./open-QQ7FWG4A.js");(await h(d)).once("error",()=>{}),a("succeeded")}catch{a("failed")}}})))(si),u=pi(c,t.baseUrl);await mi(u),ne({baseUrl:t.baseUrl,token:u.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:r});for(let[p,d]of Object.entries(s))ne({baseUrl:t.baseUrl,token:u.accessToken,authStage:"browser_opened",authOutcome:p,occurrenceCount:d});return i>0&&ne({baseUrl:t.baseUrl,token:u.accessToken,authStage:"callback_received",authOutcome:"succeeded",occurrenceCount:i}),ne({baseUrl:t.baseUrl,token:u.accessToken,authStage:"token_persisted",authOutcome:"succeeded"}),{...u,authorizeUrl:o}}var G=(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))(G||{}),yi="MATILDA_AGENT_SDK",it="MATILDA_API_KEY";function Ai(t,e){if(t.apiKey||t.apiKeyEnvKey!==it)return;let n=q({channel:e});n?.accessToken&&(t.apiKey=n.accessToken,process.env[it]=n.accessToken)}async function Si(t,e){if(t.apiKeyEnvKey!==it)return;let n=q({channel:e});if(!n?.accessToken)return;let o=await Nt({baseUrl:t.baseUrl,fallbackAccessToken:n.accessToken,channel:e});o&&(t.apiKey=o,process.env[it]=o)}function Ei(t){return t.matildaAgentSdk===!0||process.env[yi]==="1"}function Ft(t,e,n){t[e]=n}function _i(t,e){return t?.[e]}function Mi(t,e,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:e,proxy:t?.getProxy()};Ft(i,"authType",{kind:"computed",detail:"provided by caller"}),t?.getProxy()&&Ft(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=u=>_i(o,u)??{kind:"unknown"};for(let u of Ze)n&&u in n&&!i[u]&&Ft(i,u,l(u));Ai(a,t.getChannel());let c=to(a,s);if(!c.valid)throw new Error(c.errors.map(u=>u.message).join(`
10
10
  `));return{config:a,sources:i}}function to(t,e=!1){let n=[];if(t.authType==="matilda-oauth")return{valid:!0,errors:[]};if(!t.apiKey)if(e)n.push(new je(t.authType,t.model,t.apiKeyEnvKey));else{let o=t.apiKeyEnvKey||Hn(t.authType);n.push(new We({authType:t.authType,model:t.model,baseUrl:t.baseUrl,envKey:o}))}if(!t.model)if(e)n.push(new ze(t.authType));else{let o=Bn(t.authType);n.push(new qe({authType:t.authType,envKey:o}))}return t.authType==="anthropic"&&!t.baseUrl&&(e?n.push(new Ye({authType:t.authType,model:t.model})):t.authType==="anthropic"&&n.push(new Je)),{valid:n.length===0,errors:n}}function nc(t,e,n){return Mi(t,e,n).config}function eo(t){let e=t;for(;e instanceof Error;){if("code"in e&&e.code==="ERR_MODULE_NOT_FOUND")return e;e=e.cause}}async function oc(t,e,n){await Si(t,e.getChannel());let o=to(t,!1);if(!o.valid)throw new Error(o.errors.map(s=>s.message).join(`
11
- `));let r=t.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai")if(Ei(t)){let{createMatildaAgentContentGenerator:s}=await import("./matildaAgentContentGenerator-26CUAKWA.js");i=s(t,e)}else{let{createOpenAIContentGenerator:s}=await import("./openaiContentGenerator-EKVEUZ2K.js");i=s(t,e)}else if(r==="matilda-oauth"){let{getMatildaOAuthClient:s}=await import("./matildaOAuth2-LKOMJUC6.js"),{MatildaContentGenerator:a}=await import("./matildaContentGenerator-BSVWQR2W.js");try{let l=await s(e,n?{requireCachedCredentials:!0}:void 0);i=new a(l,t,e)}catch(l){throw eo(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(r==="anthropic"){let{createAnthropicContentGenerator:s}=await import("./anthropicContentGenerator-EFVV6ZTA.js");i=s(t,e)}else if(r==="gemini"||r==="vertex-ai"){let{createGeminiContentGenerator:s}=await import("./geminiContentGenerator-KREJG645.js");i=s(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=eo(s);throw a?new Error(`Matilda was updated in the background and needs to be restarted.
11
+ `));let r=t.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai")if(Ei(t)){let{createMatildaAgentContentGenerator:s}=await import("./matildaAgentContentGenerator-EIQI4YCP.js");i=s(t,e)}else{let{createOpenAIContentGenerator:s}=await import("./openaiContentGenerator-TNZ6SB7H.js");i=s(t,e)}else if(r==="matilda-oauth"){let{getMatildaOAuthClient:s}=await import("./matildaOAuth2-LKOMJUC6.js"),{MatildaContentGenerator:a}=await import("./matildaContentGenerator-QMMGDPIK.js");try{let l=await s(e,n?{requireCachedCredentials:!0}:void 0);i=new a(l,t,e)}catch(l){throw eo(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(r==="anthropic"){let{createAnthropicContentGenerator:s}=await import("./anthropicContentGenerator-EFVV6ZTA.js");i=s(t,e)}else if(r==="gemini"||r==="vertex-ai"){let{createGeminiContentGenerator:s}=await import("./geminiContentGenerator-SBVCQ423.js");i=s(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=eo(s);throw a?new Error(`Matilda was updated in the background and needs to be restarted.
12
12
  Please exit and restart Matilda to use the '${r}' provider.`,{cause:a}):s}return new he(i,e,t)}var Ri=["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"],vi=new Set([...Ri,...Qt]),bi=new Set(["VSCode","ACP","SDK","CI"]),re="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",xi="[A-Za-z][0-9A-Za-z-]{0,23}",no="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",ki=new RegExp(`^${re}(?:-${xi}(?:\\.${no})+)?$`),Ii=63,Oi=new RegExp(`^${re}$`),wi=new RegExp(`^${re}-preview\\.(?:0|[1-9]\\d{0,11})$`),Pi=new RegExp(`^${re}-canary\\.(?:0|[1-9]\\d{0,11})$`),Di=new RegExp(`^${re}-nightly\\.(?:0|[1-9]\\d{0,11})\\.[0-9A-Fa-f]{7,12}$`),Li=new RegExp(`^${re}-(preview|canary|nightly|development|internal)(?:\\.${no})+$`);function Ui(t){return t==="desktop"?"desktop":t===void 0||bi.has(t)?"code_cli":"unknown"}function Ni(t){if(t==="android")return"android";if(t==="darwin")return"macos";if(t==="win32")return"windows";if(t==="linux")return"linux"}function Fi(t){if(t==="x64")return"x64";if(t==="arm64")return"arm64"}function Gi(t){if(t===void 0)return"npm";if(t==="desktop")return"direct-download";if(t==="VSCode")return"vscode-marketplace"}function Ki(t,e){if(e==="desktop")return"matilda-desktop";if(t==="VSCode")return"matilda-vscode";if(e==="code_cli")return"matilda-code"}function $i(t){if(typeof t=="string"&&!(t.length>Ii||!ki.test(t)))return t}function Hi(t){if(t!==void 0)return Oi.test(t)?"stable":wi.test(t)?"preview":Pi.test(t)?"canary":Di.test(t)?"nightly":Li.exec(t)?.[1]}function oo(t,e=process.platform,n=process.arch){let o=t.getChannel?.(),r=Ui(o),i=$i(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:t.getCliVersion?.()),s=Hi(i),a=Ni(e),l=Fi(n),c=Gi(o),u=Ki(o,r);return{...u?{"x-matilda-client-name":u}:{},...i?{"x-matilda-client-version":i}:{},...a?{"x-matilda-client-operating-system":a}:{},...l?{"x-matilda-client-architecture":l}:{},...c?{"x-matilda-client-distribution-channel":c}:{},...s?{"x-matilda-client-release-channel":s}:{}}}function cc(t){let e=t.toLowerCase();return vi.has(e)||e.startsWith("x-matilda-reported-")}function Bi(t){let e=t??Jt;try{let n=new URL(e);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 dc(t,e=t.apiKey){return t.authType==="matilda-oauth"?!0:t.authType==="openai"&&!!e&&Bi(t.baseUrl)}var Vi=3e3,Me=1,ji=24*60*60*1e3,ro=20,io=999,zi=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"]),Wi=new Set(["ENOTFOUND","EAI_AGAIN"]),qi=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),Yi=new Set(["ABORT_ERR","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT"]),Ji=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]);function Xi(t){return`${new URL(t).origin}/api/client-events`}function Qi(t){let e={eventType:t.eventType,platform:"cli"};return t.eventType==="network_error"&&(e.transportReason=t.transportReason,e.transportStage=t.transportStage,e.responseReceived=t.responseReceived,e.occurrenceCount=t.occurrenceCount),t.eventType==="auth_funnel"&&(e.authStage=t.authStage,e.authOutcome=t.authOutcome,e.occurrenceCount=t.occurrenceCount),t.eventType==="network_error"&&(e.reportedSurface=t.reportedSurface,e.reportedOs=t.reportedOs,e.reportedArchitecture=t.reportedArchitecture,e.reportedProcess=t.reportedProcess,e.reportedReleaseChannel=t.reportedReleaseChannel,t.reportedVersion&&(e.reportedVersion=t.reportedVersion)),e}async function Gt(t,e){let{baseUrl:n,token:o}=e;if(!n||!o)return!1;let r=e.fetchImpl??fetch,i=new AbortController,s=setTimeout(()=>i.abort(),e.timeoutMs??Vi);try{let a=await r(Xi(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(Qi(t)),signal:i.signal});return a.ok?!0:(be.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`),!1)}catch{return!1}finally{clearTimeout(s)}}async function Ut(t,e){let n=typeof t.occurrenceCount=="number"&&Number.isFinite(t.occurrenceCount)?Math.max(1,Math.min(Math.floor(t.occurrenceCount),io)):1;return Gt({eventType:"auth_funnel",authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:n},e)}function so(){try{let t=K.readFileSync(co(),"utf8"),e=JSON.parse(t);return e.schemaVersion!==Me||!Array.isArray(e.failures)?void 0:{schemaVersion:Me,failures:e.failures.filter(Zi)}}catch{return}}function Zi(t){if(!t||typeof t!="object")return!1;let e=t;return e.eventType==="network_error"&&typeof e.transportReason=="string"&&typeof e.transportStage=="string"&&typeof e.responseReceived=="boolean"&&typeof e.occurrenceCount=="number"&&typeof e.reportedSurface=="string"&&typeof e.reportedOs=="string"&&typeof e.reportedArchitecture=="string"&&typeof e.reportedProcess=="string"&&typeof e.reportedReleaseChannel=="string"&&typeof e.firstObservedAtMs=="number"&&typeof e.lastObservedAtMs=="number"}function ao(t){let e=co();if(t.failures.length===0){try{K.rmSync(e,{force:!0})}catch{}return}try{K.mkdirSync(st.dirname(e),{recursive:!0}),K.writeFileSync(e,`${JSON.stringify(t)}
13
13
  `,"utf8")}catch{}}function lo(t,e){return t.filter(n=>e-n.lastObservedAtMs<=ji).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-ro)}function es(t){let e=oo(t);return{reportedSurface:e["x-matilda-client-name"]==="matilda-desktop"?"desktop":e["x-matilda-client-name"]==="matilda-code"||e["x-matilda-client-name"]==="matilda-vscode"?"code_cli":"unknown",reportedOs:e["x-matilda-client-operating-system"]??"unknown",reportedArchitecture:e["x-matilda-client-architecture"]??"unknown",reportedProcess:e["x-matilda-client-name"]??"unknown",reportedVersion:e["x-matilda-client-version"],reportedReleaseChannel:e["x-matilda-client-release-channel"]??"unknown"}}function ts(t){if(!t||typeof t!="object")return;let e=t.code;if(typeof e=="string")return e;if(!(t instanceof Error)||!t.cause||typeof t.cause!="object")return;let n=t.cause.code;return typeof n=="string"?n:void 0}function ns(t){if(!(!t||typeof t!="object"))for(let e of["status","statusCode"]){let n=t[e];if(typeof n=="number")return n}}function os(t,e){let n=ts(t);if(n&&zi.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&Wi.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&qi.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&Yi.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&Ji.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=ns(t),r=t instanceof Error?t.message.toLowerCase():String(t).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(e&&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 rs(t,e){return t.findIndex(n=>n.transportReason===e.transportReason&&n.transportStage===e.transportStage&&n.responseReceived===e.responseReceived&&n.reportedSurface===e.reportedSurface&&n.reportedOs===e.reportedOs&&n.reportedArchitecture===e.reportedArchitecture&&n.reportedProcess===e.reportedProcess&&n.reportedVersion===e.reportedVersion&&n.reportedReleaseChannel===e.reportedReleaseChannel)}function hc(t,e){let n=es(e.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=os(t,e.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=so()??{schemaVersion:Me,failures:[]},a=lo(s.failures,r),l=rs(a,i);if(l>=0){let c=a[l];a[l]={...c,occurrenceCount:Math.min(c.occurrenceCount+1,io),lastObservedAtMs:r}}else a.push(i);return ao({schemaVersion:Me,failures:a.slice(-ro)}),!0}async function Cc(t){let e=so();if(!e)return;let n=lo(e.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await Gt({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},t)){o.push(...n.slice(r));break}}ao({schemaVersion:Me,failures:o})}function co(){return st.join(ve.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var po=(n=>(n.GCP="gcp",n.LOCAL="local",n))(po||{}),bu="local",xu="http://localhost:4317";g();J();var ss=new Set(["service.version","service.instance.id","session.id"]);function Y(t,e){be.warn(t),e?.push(t)}function fo(t,e){if(!t)return{};let n={};for(let o of t.split(",")){let r=o.trim();if(!r)continue;let i=r.indexOf("=");if(i<0){Y(`Skipping malformed OTEL_RESOURCE_ATTRIBUTES entry: "${r}" (hint: percent-encode literal commas as %2C)`,e);continue}let s=r.slice(0,i).trim();if(!s)continue;let a=r.slice(i+1).trim(),l;try{l=decodeURIComponent(s)}catch{Y(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,e),l=s}let c;try{c=decodeURIComponent(a)}catch{Y(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${l}", using raw value`,e),c=a}n[l]=c}return n}function Kt(t,e,n){for(let o of ss)o in t&&(Y(`${e} cannot override reserved key "${o}"; ignoring`,n),delete t[o]);return t}function go(t,e){if(t==null)return{};if(typeof t!="object"||Array.isArray(t))return Y("settings.telemetry.resourceAttributes must be an object; ignoring",e),{};let n={};for(let[o,r]of Object.entries(t)){let i=o.trim();if(!i){Y("settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",e);continue}typeof r=="string"?n[i]=r:Y(`settings.telemetry.resourceAttributes value for "${i}" must be a string (got ${typeof r}); ignoring`,e)}return n}function Re(t){if(t!==void 0)return t==="true"||t==="1"}function uo(t){if(t!==void 0){if(t==="local"||t==="local")return"local";if(t==="gcp"||t==="gcp")return"gcp"}}async function is(t){let e=t.argv??{},n=t.env??{},o=t.settings??{},r=e.telemetry??Re(n.MATILDA_TELEMETRY_ENABLED)??o.enabled,i=e.telemetryTarget??n.MATILDA_TELEMETRY_TARGET??o.target,s=uo(i);if(i!==void 0&&s===void 0)throw new at(`Invalid telemetry target: ${String(i)}. Valid values are: local, gcp`);let a=e.telemetryOtlpEndpoint??n.MATILDA_TELEMETRY_OTLP_ENDPOINT??n.OTEL_EXPORTER_OTLP_ENDPOINT??o.otlpEndpoint,l=e.telemetryOtlpProtocol??n.MATILDA_TELEMETRY_OTLP_PROTOCOL??o.otlpProtocol,c=["grpc","http"].find(L=>L===l);if(l!==void 0&&c===void 0)throw new at(`Invalid telemetry OTLP protocol: ${String(l)}. Valid values are: grpc, http`);let u=e.telemetryLogPrompts??Re(n.MATILDA_TELEMETRY_LOG_PROMPTS)??o.logPrompts,p=Re(n.MATILDA_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES)??o.includeSensitiveSpanAttributes??!1,d=e.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,f=n.MATILDA_TELEMETRY_OTLP_METRICS_ENDPOINT??n.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT??o.otlpMetricsEndpoint,C=[],T=Kt(fo(n.OTEL_RESOURCE_ATTRIBUTES,C),"OTEL_RESOURCE_ATTRIBUTES",C),y=Kt(go(o.resourceAttributes,C),"settings.telemetry.resourceAttributes",C),S={...T,...y},R=n.OTEL_SERVICE_NAME?.trim();R&&(S["service.name"]=R);let $=Object.keys(S).length?S:void 0,H=Re(n.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??o.metrics?.includeSessionId??!1;return{enabled:r,target:s,otlpEndpoint:a,otlpProtocol:c,otlpTracesEndpoint:h,otlpLogsEndpoint:m,otlpMetricsEndpoint:f,logPrompts:u,includeSensitiveSpanAttributes:p,outfile:d,resourceAttributes:$,metrics:{includeSessionId:H},resourceAttributeWarnings:C.length?C:void 0}}export{Et as a,Q as b,De as c,yo as d,Ao as e,mn as f,Ge as g,Fn as h,zo as i,me as j,Vs as k,Re as l,uo as m,is as n,ee as o,Ve as p,ir as q,xt as r,sr as s,Mn as t,ar as u,lr as v,Rn as w,cr as x,vn as y,bn as z,xn as A,dr as B,ur as C,Rr as D,vr as E,br as F,xr as G,kr as H,Ir as I,Or as J,wr as K,Pr as L,oo as M,cc as N,dc as O,Gt as P,Ut as Q,hc as R,Cc as S,po as T,bu as U,xu as V,Ce as W,Xe as X,Na as Y,Qe as Z,Ha as _,Ba as $,et as aa,Va as ba,Wn as ca,tt as da,qn as ea,Qn as fa,q as ga,mi as ha,hi as ia,zl as ja,Wl as ka,Nt as la,ql as ma,Ti as na,Yl as oa,G as pa,Mi as qa,to as ra,nc as sa,oc as ta};
14
14
  /**
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as ls}from"./chunk-QCIDUZV6.js";import{c as yr,f as Te}from"./chunk-S4K76QPI.js";import{M as Zn,N as es,O as qt,Q as ts,R as Cr,S as rs,a as Vn,g as ve,h as Kn,la as as}from"./chunk-5RG6AVD6.js";import{a as is}from"./chunk-DC7LAFZZ.js";import{a as Xn,g as zn,k as Yn,l as mr,o as ns,t as ss,v as os}from"./chunk-QLEJOI4X.js";import{e as Jn}from"./chunk-4J6DC24J.js";import{b as gr,c as _r,f as Qn,n as br}from"./chunk-SDTWBD62.js";import{b as rn}from"./chunk-ESSYHTAZ.js";import{Y as he,b as qn,p as tn}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();a();a();a();a();a();a();function A(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t}function c(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}a();var nn=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return nn=n.randomUUID.bind(n),n.randomUUID();let e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};a();a();a();function Jt(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var Xt=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){let e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};var y=class extends Error{},$=class n extends y{constructor(e,t,r,s){super(`${n.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new me({message:r,cause:Xt(t)});let o=t?.error;return e===400?new it(e,o,r,s):e===401?new at(e,o,r,s):e===403?new lt(e,o,r,s):e===404?new ct(e,o,r,s):e===409?new ut(e,o,r,s):e===422?new ft(e,o,r,s):e===429?new pt(e,o,r,s):e>=500?new dt(e,o,r,s):new n(e,o,r,s)}},k=class extends ${constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},me=class extends ${constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends me{constructor({message:e}={}){super({message:e??"Request timed out."})}},it=class extends ${},at=class extends ${},lt=class extends ${},ct=class extends ${},ut=class extends ${},ft=class extends ${},pt=class extends ${},dt=class extends ${},ht=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},mt=class extends y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Z=class extends Error{constructor(e){super(e)}};var go=/^[a-z][a-z0-9+.-]*:/i,cs=n=>go.test(n),W=n=>(W=Array.isArray,W(n)),sn=W;function us(n){return typeof n!="object"?{}:n??{}}function fs(n){if(!n)return!0;for(let e in n)return!1;return!0}function ps(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Vt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var ds=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${n} must be an integer`);if(e<0)throw new y(`${n} must be a positive integer`);return e};var hs=n=>{try{return JSON.parse(n)}catch{return}};a();var ee=n=>new Promise(e=>setTimeout(e,n));a();a();var _e="5.11.0";var bs=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function _o(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var bo=()=>{let n=_o();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":gs(Deno.build.os),"X-Stainless-Arch":ms(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":gs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ms(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Co();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Co(){if(typeof navigator>"u"||!navigator)return null;let n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of n){let r=t.exec(navigator.userAgent);if(r){let s=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var ms=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",gs=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),_s,Cs=()=>_s??(_s=bo());a();function ys(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function on(...n){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function wr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return on({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function an(n){if(n[Symbol.asyncIterator])return n;let e=n.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function ws(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}let e=n.getReader(),t=e.cancel();e.releaseLock(),await t}a();var As=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var Ar="RFC3986",ln=n=>String(n),xr={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:ln},cn="RFC1738";a();a();var Ir=(n,e)=>(Ir=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ir(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var un=1024,xs=(n,e,t,r,s)=>{if(n.length===0)return n;let o=n;if(typeof n=="symbol"?o=Symbol.prototype.toString.call(n):typeof n!="string"&&(o=String(n)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=un){let u=o.length>=un?o.slice(l,l+un):o,d=[];for(let g=0;g<u.length;++g){let p=u.charCodeAt(g);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===cn&&(p===40||p===41)){d[d.length]=u.charAt(g);continue}if(p<128){d[d.length]=te[p];continue}if(p<2048){d[d.length]=te[192|p>>6]+te[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=te[224|p>>12]+te[128|p>>6&63]+te[128|p&63];continue}g+=1,p=65536+((p&1023)<<10|u.charCodeAt(g)&1023),d[d.length]=te[240|p>>18]+te[128|p>>12&63]+te[128|p>>6&63]+te[128|p&63]}i+=d.join("")}return i};function Is(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function fn(n,e){if(W(n)){let t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}var Rs={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},Os=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},Ps,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:xs,encodeValuesOnly:!1,format:Ar,formatter:ln,indices:!1,serializeDate(n){return(Ps??(Ps=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function Ao(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var pn={};function Ss(n,e,t,r,s,o,i,l,u,d,g,p,b,f,x,C,P,O){let w=n,U=O,S=0,J=!1;for(;(U=U.get(pn))!==void 0&&!J;){let T=U.get(n);if(S+=1,typeof T<"u"){if(T===S)throw new RangeError("Cyclic object value");J=!0}typeof U.get(pn)>"u"&&(S=0)}if(typeof d=="function"?w=d(e,w):w instanceof Date?w=b?.(w):t==="comma"&&W(w)&&(w=fn(w,function(T){return T instanceof Date?b?.(T):T})),w===null){if(o)return u&&!C?u(e,N.encoder,P,"key",f):e;w=""}if(Ao(w)||Is(w)){if(u){let T=C?e:u(e,N.encoder,P,"key",f);return[x?.(T)+"="+x?.(u(w,N.encoder,P,"value",f))]}return[x?.(e)+"="+x?.(String(w))]}let H=[];if(typeof w>"u")return H;let E;if(t==="comma"&&W(w))C&&u&&(w=fn(w,u)),E=[{value:w.length>0?w.join(",")||null:void 0}];else if(W(d))E=d;else{let T=Object.keys(w);E=g?T.sort(g):T}let D=l?String(e).replace(/\./g,"%2E"):String(e),G=r&&W(w)&&w.length===1?D+"[]":D;if(s&&W(w)&&w.length===0)return G+"[]";for(let T=0;T<E.length;++T){let M=E[T],Wn=typeof M=="object"&&typeof M.value<"u"?M.value:w[M];if(i&&Wn===null)continue;let en=p&&l?M.replace(/\./g,"%2E"):M,ho=W(w)?typeof t=="function"?t(G,en):G:G+(p?"."+en:"["+en+"]");O.set(n,S);let Hn=new WeakMap;Hn.set(pn,O),Os(H,Ss(Wn,ho,t,r,s,o,i,l,t==="comma"&&C&&W(w)?null:u,d,g,p,b,f,x,C,P,Hn))}return H}function xo(n=N){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=n.charset||N.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Ar;if(typeof n.format<"u"){if(!Ir(xr,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=xr[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in Rs?o=n.arrayFormat:"indices"in n?o=n.indices?"indices":"repeat":o=N.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:N.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:N.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?N.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:N.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:N.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:N.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:N.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:N.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:N.strictNullHandling}}function dn(n,e={}){let t=n,r=xo(e),s,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):W(r.filter)&&(o=r.filter,s=o);let i=[];if(typeof t!="object"||t===null)return"";let l=Rs[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let d=new WeakMap;for(let b=0;b<s.length;++b){let f=s[b];r.skipNulls&&t[f]===null||Os(i,Ss(t[f],f,l,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,d))}let g=i.join(r.delimiter),p=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),g.length>0?p+g:""}a();a();a();a();a();function Ts(n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}var Es;function gt(n){let e;return(Es??(e=new globalThis.TextEncoder,Es=e.encode.bind(e)))(n)}var vs;function hn(n){let e;return(vs??(e=new globalThis.TextDecoder,vs=e.decode.bind(e)))(n)}var X,V,ke=class{constructor(){X.set(this,void 0),V.set(this,void 0),A(this,X,new Uint8Array,"f"),A(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gt(e):e;A(this,X,Ts([c(this,X,"f"),t]),"f");let r=[],s;for(;(s=Po(c(this,X,"f"),c(this,V,"f")))!=null;){if(s.carriage&&c(this,V,"f")==null){A(this,V,s.index,"f");continue}if(c(this,V,"f")!=null&&(s.index!==c(this,V,"f")+1||s.carriage)){r.push(hn(c(this,X,"f").subarray(0,c(this,V,"f")-1))),A(this,X,c(this,X,"f").subarray(c(this,V,"f")),"f"),A(this,V,null,"f");continue}let o=c(this,V,"f")!==null?s.preceding-1:s.preceding,i=hn(c(this,X,"f").subarray(0,o));r.push(i),A(this,X,c(this,X,"f").subarray(s.index),"f"),A(this,V,null,"f")}return r}flush(){return c(this,X,"f").length?this.decode(`
3
+ import{a as ls}from"./chunk-QCIDUZV6.js";import{c as yr,f as Te}from"./chunk-S4K76QPI.js";import{M as Zn,N as es,O as qt,Q as ts,R as Cr,S as rs,a as Vn,g as ve,h as Kn,la as as}from"./chunk-FU2PKCG5.js";import{a as is}from"./chunk-DC7LAFZZ.js";import{a as Xn,g as zn,k as Yn,l as mr,o as ns,t as ss,v as os}from"./chunk-QLEJOI4X.js";import{e as Jn}from"./chunk-4J6DC24J.js";import{b as gr,c as _r,f as Qn,n as br}from"./chunk-SDTWBD62.js";import{b as rn}from"./chunk-ESSYHTAZ.js";import{Y as he,b as qn,p as tn}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();a();a();a();a();a();a();function A(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t}function c(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}a();var nn=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return nn=n.randomUUID.bind(n),n.randomUUID();let e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};a();a();a();function Jt(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var Xt=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){let e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};var y=class extends Error{},$=class n extends y{constructor(e,t,r,s){super(`${n.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new me({message:r,cause:Xt(t)});let o=t?.error;return e===400?new it(e,o,r,s):e===401?new at(e,o,r,s):e===403?new lt(e,o,r,s):e===404?new ct(e,o,r,s):e===409?new ut(e,o,r,s):e===422?new ft(e,o,r,s):e===429?new pt(e,o,r,s):e>=500?new dt(e,o,r,s):new n(e,o,r,s)}},k=class extends ${constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},me=class extends ${constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends me{constructor({message:e}={}){super({message:e??"Request timed out."})}},it=class extends ${},at=class extends ${},lt=class extends ${},ct=class extends ${},ut=class extends ${},ft=class extends ${},pt=class extends ${},dt=class extends ${},ht=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},mt=class extends y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Z=class extends Error{constructor(e){super(e)}};var go=/^[a-z][a-z0-9+.-]*:/i,cs=n=>go.test(n),W=n=>(W=Array.isArray,W(n)),sn=W;function us(n){return typeof n!="object"?{}:n??{}}function fs(n){if(!n)return!0;for(let e in n)return!1;return!0}function ps(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Vt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var ds=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${n} must be an integer`);if(e<0)throw new y(`${n} must be a positive integer`);return e};var hs=n=>{try{return JSON.parse(n)}catch{return}};a();var ee=n=>new Promise(e=>setTimeout(e,n));a();a();var _e="5.11.0";var bs=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function _o(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var bo=()=>{let n=_o();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":gs(Deno.build.os),"X-Stainless-Arch":ms(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":gs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ms(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Co();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Co(){if(typeof navigator>"u"||!navigator)return null;let n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of n){let r=t.exec(navigator.userAgent);if(r){let s=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var ms=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",gs=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),_s,Cs=()=>_s??(_s=bo());a();function ys(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function on(...n){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function wr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return on({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function an(n){if(n[Symbol.asyncIterator])return n;let e=n.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function ws(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}let e=n.getReader(),t=e.cancel();e.releaseLock(),await t}a();var As=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var Ar="RFC3986",ln=n=>String(n),xr={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:ln},cn="RFC1738";a();a();var Ir=(n,e)=>(Ir=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ir(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var un=1024,xs=(n,e,t,r,s)=>{if(n.length===0)return n;let o=n;if(typeof n=="symbol"?o=Symbol.prototype.toString.call(n):typeof n!="string"&&(o=String(n)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=un){let u=o.length>=un?o.slice(l,l+un):o,d=[];for(let g=0;g<u.length;++g){let p=u.charCodeAt(g);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===cn&&(p===40||p===41)){d[d.length]=u.charAt(g);continue}if(p<128){d[d.length]=te[p];continue}if(p<2048){d[d.length]=te[192|p>>6]+te[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=te[224|p>>12]+te[128|p>>6&63]+te[128|p&63];continue}g+=1,p=65536+((p&1023)<<10|u.charCodeAt(g)&1023),d[d.length]=te[240|p>>18]+te[128|p>>12&63]+te[128|p>>6&63]+te[128|p&63]}i+=d.join("")}return i};function Is(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function fn(n,e){if(W(n)){let t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}var Rs={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},Os=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},Ps,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:xs,encodeValuesOnly:!1,format:Ar,formatter:ln,indices:!1,serializeDate(n){return(Ps??(Ps=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function Ao(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var pn={};function Ss(n,e,t,r,s,o,i,l,u,d,g,p,b,f,x,C,P,O){let w=n,U=O,S=0,J=!1;for(;(U=U.get(pn))!==void 0&&!J;){let T=U.get(n);if(S+=1,typeof T<"u"){if(T===S)throw new RangeError("Cyclic object value");J=!0}typeof U.get(pn)>"u"&&(S=0)}if(typeof d=="function"?w=d(e,w):w instanceof Date?w=b?.(w):t==="comma"&&W(w)&&(w=fn(w,function(T){return T instanceof Date?b?.(T):T})),w===null){if(o)return u&&!C?u(e,N.encoder,P,"key",f):e;w=""}if(Ao(w)||Is(w)){if(u){let T=C?e:u(e,N.encoder,P,"key",f);return[x?.(T)+"="+x?.(u(w,N.encoder,P,"value",f))]}return[x?.(e)+"="+x?.(String(w))]}let H=[];if(typeof w>"u")return H;let E;if(t==="comma"&&W(w))C&&u&&(w=fn(w,u)),E=[{value:w.length>0?w.join(",")||null:void 0}];else if(W(d))E=d;else{let T=Object.keys(w);E=g?T.sort(g):T}let D=l?String(e).replace(/\./g,"%2E"):String(e),G=r&&W(w)&&w.length===1?D+"[]":D;if(s&&W(w)&&w.length===0)return G+"[]";for(let T=0;T<E.length;++T){let M=E[T],Wn=typeof M=="object"&&typeof M.value<"u"?M.value:w[M];if(i&&Wn===null)continue;let en=p&&l?M.replace(/\./g,"%2E"):M,ho=W(w)?typeof t=="function"?t(G,en):G:G+(p?"."+en:"["+en+"]");O.set(n,S);let Hn=new WeakMap;Hn.set(pn,O),Os(H,Ss(Wn,ho,t,r,s,o,i,l,t==="comma"&&C&&W(w)?null:u,d,g,p,b,f,x,C,P,Hn))}return H}function xo(n=N){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=n.charset||N.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Ar;if(typeof n.format<"u"){if(!Ir(xr,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=xr[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in Rs?o=n.arrayFormat:"indices"in n?o=n.indices?"indices":"repeat":o=N.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:N.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:N.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?N.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:N.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:N.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:N.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:N.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:N.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:N.strictNullHandling}}function dn(n,e={}){let t=n,r=xo(e),s,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):W(r.filter)&&(o=r.filter,s=o);let i=[];if(typeof t!="object"||t===null)return"";let l=Rs[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let d=new WeakMap;for(let b=0;b<s.length;++b){let f=s[b];r.skipNulls&&t[f]===null||Os(i,Ss(t[f],f,l,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,d))}let g=i.join(r.delimiter),p=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),g.length>0?p+g:""}a();a();a();a();a();function Ts(n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}var Es;function gt(n){let e;return(Es??(e=new globalThis.TextEncoder,Es=e.encode.bind(e)))(n)}var vs;function hn(n){let e;return(vs??(e=new globalThis.TextDecoder,vs=e.decode.bind(e)))(n)}var X,V,ke=class{constructor(){X.set(this,void 0),V.set(this,void 0),A(this,X,new Uint8Array,"f"),A(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gt(e):e;A(this,X,Ts([c(this,X,"f"),t]),"f");let r=[],s;for(;(s=Po(c(this,X,"f"),c(this,V,"f")))!=null;){if(s.carriage&&c(this,V,"f")==null){A(this,V,s.index,"f");continue}if(c(this,V,"f")!=null&&(s.index!==c(this,V,"f")+1||s.carriage)){r.push(hn(c(this,X,"f").subarray(0,c(this,V,"f")-1))),A(this,X,c(this,X,"f").subarray(c(this,V,"f")),"f"),A(this,V,null,"f");continue}let o=c(this,V,"f")!==null?s.preceding-1:s.preceding,i=hn(c(this,X,"f").subarray(0,o));r.push(i),A(this,X,c(this,X,"f").subarray(s.index),"f"),A(this,V,null,"f")}return r}flush(){return c(this,X,"f").length?this.decode(`
4
4
  `):[]}};X=new WeakMap,V=new WeakMap;ke.NEWLINE_CHARS=new Set([`
5
5
  `,"\r"]);ke.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Po(n,e){for(let s=e??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function ks(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}a();var Rr={off:0,error:200,warn:300,info:400,debug:500},mn=(n,e,t)=>{if(n){if(ps(Rr,n))return n;v(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Rr))}`)}};function Kt(){}function Pr(n,e,t){return!e||Rr[n]>Rr[t]?Kt:e[n].bind(e)}var Ro={error:Kt,warn:Kt,info:Kt,debug:Kt},Ms=new WeakMap;function v(n){let e=n.logger,t=n.logLevel??"off";if(!e)return Ro;let r=Ms.get(e);if(r&&r[0]===t)return r[1];let s={error:Pr("error",e,t),warn:Pr("warn",e,t),info:Pr("info",e,t),debug:Pr("debug",e,t)};return Ms.set(e,[t,s]),s}var le=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var zt,re=class n{constructor(e,t,r){this.iterator=e,zt.set(this,void 0),this.controller=t,A(this,zt,r,"f")}static fromSSEResponse(e,t,r){let s=!1,o=r?v(r):console;async function*i(){if(s)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of Oo(e,t))if(!l){if(u.data.startsWith("[DONE]")){l=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let d;try{d=JSON.parse(u.data)}catch(g){throw o.error("Could not parse message into JSON:",u.data),o.error("From chunk:",u.raw),g}if(d&&d.error)throw new $(void 0,d.error,void 0,e.headers);yield d}else{let d;try{d=JSON.parse(u.data)}catch(g){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),g}if(u.event=="error")throw new $(void 0,d.error,d.message,void 0);yield{event:u.event,data:d}}}l=!0}catch(u){if(Jt(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*o(){let l=new ke,u=an(e);for await(let d of u)for(let g of l.decode(d))yield g;for(let d of l.flush())yield d}async function*i(){if(s)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of o())l||u&&(yield JSON.parse(u));l=!0}catch(u){if(Jt(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}[(zt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new n(()=>s(e),this.controller,c(this,zt,"f")),new n(()=>s(t),this.controller,c(this,zt,"f"))]}toReadableStream(){let e=this,t;return on({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:o}=await t.next();if(o)return r.close();let i=gt(JSON.stringify(s)+`
6
6
  `);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}};async function*Oo(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new y("Attempted to iterate over a response with no body");let t=new gn,r=new ke,s=an(n.body);for await(let o of So(s))for(let i of r.decode(o)){let l=t.decode(i);l&&(yield l)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*So(n){let e=new Uint8Array;for await(let t of n){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?gt(t):t,s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let o;for(;(o=ks(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var gn=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`