@maincode-ai/matilda-code 0.21.1 → 0.21.2-nightly.20260816.ddc368064
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.
- package/chunks/{agent-NKMZBTFX.js → agent-JXCEYIP2.js} +1 -1
- package/chunks/{agent-headless-QALB2VKF.js → agent-headless-C5K5VE7T.js} +1 -1
- package/chunks/{anthropicContentGenerator-GW3P6NLQ.js → anthropicContentGenerator-EFVV6ZTA.js} +1 -1
- package/chunks/{chunk-GIIMOLLN.js → chunk-C2ZWB2NT.js} +1 -1
- package/chunks/{chunk-SS5WUOSJ.js → chunk-FT76AZPN.js} +1 -1
- package/chunks/{chunk-G6ZP2JXV.js → chunk-HP723QLF.js} +1 -1
- package/chunks/chunk-HUDRFII2.js +22 -0
- package/chunks/{chunk-PPBGETQF.js → chunk-ICZ23IBB.js} +1 -1
- package/chunks/{chunk-ASBKKKEC.js → chunk-O6D4TQY2.js} +9 -9
- package/chunks/chunk-SDTWBD62.js +8 -0
- package/chunks/{chunk-UBLZ73EY.js → chunk-YC6H7FWM.js} +14 -14
- package/chunks/{chunk-UUTPLLCJ.js → chunk-ZF4YAQ46.js} +3 -3
- package/chunks/{computer-use-D5SWPUWU.js → computer-use-D2LV5NQR.js} +1 -1
- package/chunks/{contextCommand-Z577LUBV.js → contextCommand-LPBWF4WE.js} +1 -1
- package/chunks/{edit-PSPQYZEV.js → edit-LOFXKVLA.js} +1 -1
- package/chunks/{enter-worktree-HOQPTB4F.js → enter-worktree-QYUHZTXF.js} +1 -1
- package/chunks/{enterPlanMode-4KND327M.js → enterPlanMode-DDWK55DS.js} +1 -1
- package/chunks/{exit-worktree-2EUDTVQD.js → exit-worktree-MQP2RLY6.js} +1 -1
- package/chunks/{exitPlanMode-I5NUEMM2.js → exitPlanMode-XTULORO5.js} +1 -1
- package/chunks/{geminiContentGenerator-KE5W2HAZ.js → geminiContentGenerator-5DLG2IS7.js} +1 -1
- package/chunks/{glob-6LD5EXSG.js → glob-R5GS5CMT.js} +1 -1
- package/chunks/{grep-D7F7VOBQ.js → grep-CSRCDUZG.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-53Y6ZKNX.js → matildaAgentContentGenerator-QZULEJRI.js} +1 -1
- package/chunks/{matildaContentGenerator-XH7XBFUB.js → matildaContentGenerator-EBSJ2MDP.js} +1 -1
- package/chunks/{monitor-GH5LJV3O.js → monitor-PLV6SG2C.js} +1 -1
- package/chunks/{notebook-edit-VYMSF622.js → notebook-edit-UNZHADMZ.js} +1 -1
- package/chunks/{openaiContentGenerator-W7WJAAQ3.js → openaiContentGenerator-PF2IFB3R.js} +1 -1
- package/chunks/{ripGrep-AZQNLER7.js → ripGrep-UHJEIG4M.js} +1 -1
- package/chunks/{scheduler-2XZK4D6E.js → scheduler-XO7MKVUF.js} +1 -1
- package/chunks/{serve-VB2EI7T2.js → serve-C3MNFXMD.js} +1 -1
- package/chunks/{shell-QLCMTFUQ.js → shell-UVTCAPIT.js} +1 -1
- package/chunks/{skill-EGDTMPHB.js → skill-7JPUSZNQ.js} +1 -1
- package/chunks/{src-O4M6KMI4.js → src-DSDZFR7A.js} +1 -1
- package/chunks/{team-create-DAPGTPYR.js → team-create-W2UW53AU.js} +1 -1
- package/chunks/{update-goal-6WDBMJ2I.js → update-goal-EUJYH23K.js} +1 -1
- package/chunks/{web-fetch-QP42GV23.js → web-fetch-UGTFUOQN.js} +1 -1
- package/chunks/{workflow-PI6BBTXZ.js → workflow-HW32FTGV.js} +2 -2
- package/chunks/{write-file-4K4VALFS.js → write-file-IOPR5BQW.js} +1 -1
- package/cli.js +436 -445
- package/package.json +2 -2
- package/chunks/chunk-BZMRSSEE.js +0 -22
- package/chunks/chunk-XJDC3ZQZ.js +0 -8
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as B,d as Qt}from"./chunk-4F4DA5UI.js";import{a as en,b as yt,c as tn,d as nn}from"./chunk-DC7LAFZZ.js";import{b as zt,d as Wt,g as Tt,j as qt,k as Yt,s as Zt,v as ae}from"./chunk-QLEJOI4X.js";import{b as A,e as $}from"./chunk-4J6DC24J.js";import{a as Jt,d as Xt}from"./chunk-XJDC3ZQZ.js";import{Bb as se,Jc as mt,Kc as ht,Mb as pt,Mc as Ct,Pa as ho,Pb as ft,Ra as Co,Rb as gt,Sa as J,Wa as Re,Xa as ve,Ya as be,a as M,ab as ut,eb as ke,f as L,fb as H,na as ct,tb as xe,ub as Ie}from"./chunk-CFBZKYFB.js";import{b as on}from"./chunk-3YLXGE6T.js";import{L as Me,P as Vt,R as dt,Y as O,c as Bt,d as oe,e as re,j as st}from"./chunk-QWBNNEV2.js";import{b as at,c as R,f as lt,g as ie,h as _,i as _e,k as jt,l as v,n as Y}from"./chunk-FWDMPRKU.js";import{b as f}from"./chunk-GZPNIYVZ.js";import{f as mo}from"./chunk-OWGSC52X.js";f();function X(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function Oe(t){let e=t.candidates||0,n=t.thoughts||0;return n>e?e+n:Math.max(e,n)}function To(t){return t.total&&t.total>0?Math.max(t.total,(t.prompt||0)+Oe(t)):(t.prompt||0)+Oe(t)}function yo(t){let e=Math.max(0,t.thoughtsTokens||0),n=Oe({candidates:t.outputTokens||0,thoughts:e}),o=Math.max(t.totalTokens||0,(t.inputTokens||0)+n);return{...t,outputTokens:n,thoughtsTokens:e,totalTokens:o}}f();f();var Ao=/[A-Za-z\u00C0-\u024F]/g;function So(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 At(t){let e=t.codePointAt(0);return e!==void 0&&So(e)}function Eo(t){let e=t.match(Ao)?.length??0;if(e<24)return!1;let n=0;for(let o of t)At(o)&&n++;return n===0||e>=n*8}function we(t){if(!t||!Eo(t))return t;let e="",n=0,o=[...t];for(;n<o.length;){if(!At(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&&At(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," ")}f();var Q=O("TAGGED_THINKING_PARSER"),de=["<think>","<thinking>"],ce=["</think>","</thinking>"],Mo=Math.max(...de.map(t=>t.length),...ce.map(t=>t.length));function le(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function Pe(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 De(t,e,n){return n.find(o=>t.startsWith(o,e))}function Et(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 rn(t){let e=[];for(let n of t){if(n.thought===!0||typeof n.text!="string"){e.push(n);continue}let o=we(Et(n.text));(o.length>0||/^\s+$/.test(n.text))&&e.push({text:o.length>0?o:n.text})}return e}var St=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=De(o,s,de);if(a){Q.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),le(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=De(o,s,ce);if(l){Q.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),le(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(Pe(o,s,de)||Pe(o,s,ce)))break}else{let a=De(o,s,ce);if(a){Q.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),le(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=De(o,s,de);if(l){s+=l.length;continue}if(!n&&(Pe(o,s,ce)||Pe(o,s,de)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(le(r,i,this.mode),this.buffer=this.buffer.slice(s),Q.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),rn(r)):(this.buffer="",this.mode==="thought"&&i&&Q.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),le(r,i,this.mode),Q.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),rn(r))}};function sn(t){return new St().parse(t,!0)}var P=O("CONVERTER"),fn="(attached media from previous tool call)";function gn(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,d=Math.max(0,e.estimatedReasoningTokens??0),u=Math.max(0,e.estimatedContentTokens??0),p=l>0?l:d,c=o;p>0&&(o>=p?c=o:c=o+p),(u>0||d>0)&&(c=Math.max(c,u+(l>0?0:d),u+p)),r>n&&(n>0||o>0||p>0)&&(c=Math.max(c,r-n)),p===0&&d>0&&(p=d),p>c&&(p=c);let h=t.usage_is_incomplete===!0||o>0&&n===0||r>0&&n===0&&o===0,m=n,g=r;return(g===0&&(m>0||c>0)||g>0&&m>0&&g<m+c)&&(g=m+c),{promptTokenCount:m,candidatesTokenCount:c,totalTokenCount:g,cachedContentTokenCount:s,thoughtsTokenCount:p,...h?{usageIsIncomplete:!0}:{}}}var _o=64,an=1024;function ln(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>=an&&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>=_o?(e.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<an&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function mn(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 Ro(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=mn(i.parameters)),s&&(s=Wt(s,e)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function vo(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return ko(t,o),xo(t.contents,o,e),o=pn(o),n.cleanOrphanToolCalls&&(o=Go(o),o=pn(o)),o}function bo(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],r=[],i=[],s=[],a=0;for(let g of o)typeof g=="string"?i.push(g):"text"in g&&g.text?"thought"in g&&g.thought?r.push(g.text):i.push(g.text):"functionCall"in g&&g.functionCall&&(s.push({id:g.functionCall.id||`call_${a}`,type:"function",function:{name:g.functionCall.name||"",arguments:JSON.stringify(g.functionCall.args||{})}}),a+=1);let l={role:"assistant",content:i.join("")||null,refusal:null},d=r.join("");d&&(l.reasoning_content=d),s.length>0&&(l.tool_calls=s);let u=Fo(n?.finishReason),p=t.usageMetadata,c={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(c.prompt_tokens_details={cached_tokens:p.cachedContentTokenCount});let h=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:c}}function ko(t,e){if(!t.config?.systemInstruction)return;let n=Cn(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function xo(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(!Po(t))return;let o=t.parts||[],r=t.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,d=new Set,u=new Set,p=[];for(let c of o){if(typeof c=="string"){i.push({type:"text",text:c});continue}"text"in c&&"thought"in c&&c.thought&&r==="assistant"&&c.text&&s.push(c.text),"text"in c&&c.text&&!("thought"in c&&c.thought)&&i.push({type:"text",text:c.text});let h=hn(c,n);if(h&&r==="user"&&i.push(h),"functionCall"in c&&c.functionCall&&r==="assistant"){let m=c.functionCall.id;if(m){if(d.has(m)){P.debug(`Dropping duplicate functionCall id=${m} while converting content`);continue}d.add(m)}a.push({id:m||`call_${l}`,type:"function",function:{name:c.functionCall.name||"",arguments:JSON.stringify(c.functionCall.args||{})}}),l+=1}if(c.functionResponse&&r==="user"){let m=c.functionResponse.id;if(m){if(u.has(m))continue;u.add(m)}let g=Oo(c.functionResponse,n);if(g){if(n.splitToolMedia&&Array.isArray(g.content)){let C=[],T=[];for(let y of g.content)y&&(y.type==="image_url"||y.type==="input_audio"||y.type==="video_url"||y.type==="file")?C.push(y):y&&y.type==="text"&&T.push(y);if(C.length>0){let y=T.map(E=>E.text).join(`
|
|
4
|
-
`);g.content=y||"[media attached in following user message]",p.push(...C)}}e.push(g)}}}if(p.length>0&&e.push({role:"user",content:[{type:"text",text:fn},...p]}),r==="assistant"){if(i.length===0&&a.length===0&&s.length===0)return;let h={role:"assistant",content:i.filter(g=>g.type==="text").map(g=>g.text).join("")||(s.length>0?"":null)};a.length>0&&(h.tool_calls=a);let m=s.join("");m&&(h.reasoning_content=m),e.push(h);return}i.length>0&&e.push({role:"user",content:i})}function
|
|
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
|
|
3
|
+
import{a as B,d as Qt}from"./chunk-4F4DA5UI.js";import{a as en,b as yt,c as tn,d as nn}from"./chunk-DC7LAFZZ.js";import{b as zt,d as Wt,g as Tt,j as qt,k as Yt,s as Zt,v as ae}from"./chunk-QLEJOI4X.js";import{b as A,e as $}from"./chunk-4J6DC24J.js";import{a as Jt,d as Xt}from"./chunk-SDTWBD62.js";import{Bb as se,Jc as mt,Kc as ht,Mb as pt,Mc as Ct,Pa as mo,Pb as ft,Ra as ho,Rb as gt,Sa as J,Wa as ve,Xa as be,Ya as xe,a as M,ab as ut,eb as ke,f as L,fb as H,na as dt,tb as Ie,ub as Oe}from"./chunk-CFBZKYFB.js";import{b as on}from"./chunk-3YLXGE6T.js";import{L as _e,P as jt,R as ct,Y as O,c as Bt,d as oe,e as re,j as st}from"./chunk-QWBNNEV2.js";import{b as at,c as R,f as lt,g as ie,h as _,i as Re,k as Vt,l as v,n as Y}from"./chunk-FWDMPRKU.js";import{b as f}from"./chunk-GZPNIYVZ.js";import{f as go}from"./chunk-OWGSC52X.js";f();function X(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function we(t){let e=t.candidates||0,n=t.thoughts||0;return n>e?e+n:Math.max(e,n)}function Co(t){return t.total&&t.total>0?Math.max(t.total,(t.prompt||0)+we(t)):(t.prompt||0)+we(t)}function To(t){let e=Math.max(0,t.thoughtsTokens||0),n=we({candidates:t.outputTokens||0,thoughts:e}),o=Math.max(t.totalTokens||0,(t.inputTokens||0)+n);return{...t,outputTokens:n,thoughtsTokens:e,totalTokens:o}}f();f();var yo=/[A-Za-z\u00C0-\u024F]/g;function Ao(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 At(t){let e=t.codePointAt(0);return e!==void 0&&Ao(e)}function So(t){let e=t.match(yo)?.length??0;if(e<24)return!1;let n=0;for(let o of t)At(o)&&n++;return n===0||e>=n*8}function Pe(t){if(!t||!So(t))return t;let e="",n=0,o=[...t];for(;n<o.length;){if(!At(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&&At(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," ")}f();var Q=O("TAGGED_THINKING_PARSER"),ce=["<think>","<thinking>"],de=["</think>","</thinking>"],Eo=Math.max(...ce.map(t=>t.length),...de.map(t=>t.length));function le(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function De(t,e,n){let o=t.length-e;return o<=0||o>Eo?!1:n.some(r=>r.startsWith(t.slice(e,e+o)))}function Le(t,e,n){return n.find(o=>t.startsWith(o,e))}function Et(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 rn(t){let e=[];for(let n of t){if(n.thought===!0||typeof n.text!="string"){e.push(n);continue}let o=Pe(Et(n.text));(o.length>0||/^\s+$/.test(n.text))&&e.push({text:o.length>0?o:n.text})}return e}var St=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=Le(o,s,ce);if(a){Q.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),le(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=Le(o,s,de);if(l){Q.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),le(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(De(o,s,ce)||De(o,s,de)))break}else{let a=Le(o,s,de);if(a){Q.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),le(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=Le(o,s,ce);if(l){s+=l.length;continue}if(!n&&(De(o,s,de)||De(o,s,ce)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(le(r,i,this.mode),this.buffer=this.buffer.slice(s),Q.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),rn(r)):(this.buffer="",this.mode==="thought"&&i&&Q.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),le(r,i,this.mode),Q.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),rn(r))}};function sn(t){return new St().parse(t,!0)}var P=O("CONVERTER"),fn="(attached media from previous tool call)";function gn(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,g=r;return(g===0&&(m>0||d>0)||g>0&&m>0&&g<m+d)&&(g=m+d),{promptTokenCount:m,candidatesTokenCount:d,totalTokenCount:g,cachedContentTokenCount:s,thoughtsTokenCount:p,...h?{usageIsIncomplete:!0}:{}}}var Mo=64,an=1024;function ln(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>=an&&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>=Mo?(e.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<an&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function mn(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 _o(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=mn(i.parameters)),s&&(s=Wt(s,e)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function Ro(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return bo(t,o),xo(t.contents,o,e),o=pn(o),n.cleanOrphanToolCalls&&(o=Fo(o),o=pn(o)),o}function vo(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],r=[],i=[],s=[],a=0;for(let g of o)typeof g=="string"?i.push(g):"text"in g&&g.text?"thought"in g&&g.thought?r.push(g.text):i.push(g.text):"functionCall"in g&&g.functionCall&&(s.push({id:g.functionCall.id||`call_${a}`,type:"function",function:{name:g.functionCall.name||"",arguments:JSON.stringify(g.functionCall.args||{})}}),a+=1);let l={role:"assistant",content:i.join("")||null,refusal:null},c=r.join("");c&&(l.reasoning_content=c),s.length>0&&(l.tool_calls=s);let u=No(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 bo(t,e){if(!t.config?.systemInstruction)return;let n=Cn(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function xo(t,e,n){if(Array.isArray(t))for(let o of t)cn(o,e,n);else t&&cn(t,e,n)}function cn(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!wo(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=hn(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 g=Io(d.functionResponse,n);if(g){if(n.splitToolMedia&&Array.isArray(g.content)){let C=[],T=[];for(let y of g.content)y&&(y.type==="image_url"||y.type==="input_audio"||y.type==="video_url"||y.type==="file")?C.push(y):y&&y.type==="text"&&T.push(y);if(C.length>0){let y=T.map(E=>E.text).join(`
|
|
4
|
+
`);g.content=y||"[media attached in following user message]",p.push(...C)}}e.push(g)}}}if(p.length>0&&e.push({role:"user",content:[{type:"text",text:fn},...p]}),r==="assistant"){if(i.length===0&&a.length===0&&s.length===0)return;let h={role:"assistant",content:i.filter(g=>g.type==="text").map(g=>g.text).join("")||(s.length>0?"":null)};a.length>0&&(h.tool_calls=a);let m=s.join("");m&&(h.reasoning_content=m),e.push(h);return}i.length>0&&e.push({role:"user",content:i})}function ko(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 Io(t,e){let n=ko(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=hn(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 hn(t,e){let{modalities:n}=e;if(t.inlineData?.mimeType&&t.inlineData?.data){let o=t.inlineData.mimeType,r=dn(o),i=t.inlineData.displayName||o;if(r==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${t.inlineData.data}`}}:V("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}`}}:V("pdf",i,e);if(r==="audio"){if(!n.audio)return V("audio",i,e);let s=Oo(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}`}}:V("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=dn(i);if(s==="image")return n.image?{type:"image_url",image_url:{url:r}}:V("image",o,e);if(i==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:r}}:V("pdf",o,e);if(s==="video")return n.video?{type:"video_url",video_url:{url:r}}:V("video",o,e);let a=t.fileData.displayName?` (${t.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${i}${a}.`}}return null}function V(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
|
+
/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 dn(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function Oo(t){return t.includes("wav")?"wav":t.includes("mp3")||t.includes("mpeg")?"mp3":null}function wo(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&Array.isArray(t.parts)}function Cn(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>Cn(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(`
|
|
7
|
-
`)||""}function Le(t,e,n=!0){if(e.taggedThinkingParser)return e.taggedThinkingParser.parse(t,n);if(e.responseParsingOptions?.taggedThinkingTags)return sn(t);if(!t)return[];let o=we(Et(t));return o?[{text:o}]:[]}function Do(t,e){let n=t.choices?.[0],o=new $;if(n){let r=[];if(!e.responseParsingOptions?.taggedThinkingTags){let i=n.message.reasoning_content??n.message.reasoning;i&&r.push({text:i,thought:!0})}if(n.message.content&&r.push(...Le(n.message.content,e)),n.message.tool_calls){for(let i of n.message.tool_calls)if(i.function){let s=zt(i.function.arguments);if(s===null)continue;r.push({functionCall:{id:i.id,name:i.function.name,args:s}})}}o.candidates=[{content:{parts:r,role:"model"},finishReason:Tn(n.finish_reason||"stop"),index:0,safetyRatings:[]}]}else o.candidates=[];if(o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage){let r=t.choices?.[0]?.message,i=r?.reasoning_content??r?.reasoning??"",s=typeof r?.content=="string"?r.content:"";o.usageMetadata=gn(t.usage,{estimatedReasoningTokens:X(i.length),estimatedContentTokens:X(s.length)})}return o}function Lo(t,e){let n=t.choices?.[0],o=new $,r=e.toolCallParser;if(!r)throw new Error("convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start.");if(n){let i=[];if(!e.responseParsingOptions?.taggedThinkingTags){let d=n.delta?.reasoning_content??n.delta?.reasoning;if(d){let u=ln(d,e.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});u&&i.push({text:u,thought:!0})}}if(typeof n.delta?.content=="string"){let d=ln(n.delta.content,e.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(d||n.finish_reason)&&i.push(...Le(d,e,!!n.finish_reason))}else n.finish_reason&&i.push(...Le("",e,!0));if(n.delta?.tool_calls)for(let d of n.delta.tool_calls){let u=d.index??0;d.function?.arguments?r.addChunk(u,d.function.arguments,d.id,d.function.name):r.addChunk(u,"",d.id,d.function?.name)}let s=!1;if(n.finish_reason){s=r.hasIncompleteToolCalls();let d=r.getCompletedToolCalls();for(let u of d)u.name&&i.push({functionCall:{id:u.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:u.name,args:u.args}})}let a=s&&n.finish_reason!=="length"?"length":n.finish_reason,l={content:{parts:i,role:"model"},index:0,safetyRatings:[]};a&&(l.finishReason=Tn(a)),o.candidates=[l]}else o.candidates=[];return o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage&&(o.usageMetadata=gn(t.usage,No(e))),o}function Uo(t){let e=t.toolCallParser;if(!e)return null;let n=[],o=e.getStrictCompletedToolCalls(),r=e.hasIncompleteToolCalls();for(let s of o)s.name&&n.push({functionCall:{id:s.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:s.name,args:s.args}});if(n.push(...Le("",t,!0)),n.length===0&&!r)return null;let i=new $;return i.candidates=[{content:{parts:n,role:"model"},index:0,safetyRatings:[],finishReason:r?A.MAX_TOKENS:A.STOP}],i.responseId=`stream-flush-${Date.now()}`,i.createTime=new Date().getTime().toString(),i.modelVersion=t.model,i.promptFeedback={safetyRatings:[]},i}function No(t){return{estimatedReasoningTokens:X(t.reasoningDeltaState?.emittedLength??0),estimatedContentTokens:X(t.textDeltaState?.emittedLength??0)}}function Tn(t){return t?{stop:A.STOP,length:A.MAX_TOKENS,content_filter:A.SAFETY,function_call:A.STOP,tool_calls:A.STOP}[t]||A.FINISH_REASON_UNSPECIFIED:A.FINISH_REASON_UNSPECIFIED}function Fo(t){if(!t)return"stop";switch(t){case A.STOP:return"stop";case A.MAX_TOKENS:return"length";case A.SAFETY:case A.RECITATION:case A.BLOCKLIST:case A.PROHIBITED_CONTENT:case A.SPII:case A.IMAGE_SAFETY:case A.IMAGE_RECITATION:case A.IMAGE_PROHIBITED_CONTENT:case A.IMAGE_OTHER:return"content_filter";case A.NO_IMAGE:return"stop";default:return"stop"}}function Mt(t){return t.role==="assistant"&&"tool_calls"in t&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0}function un(t){if(t.role!=="user"||!("content"in t)||!Array.isArray(t.content))return!1;let e=t.content[0];return e?.type==="text"&&e.text===fn}function Go(t){let e=[],n=new Map,o=new Map,r=new Map,i=new Set,s=new Set;for(let a=0;a<t.length;a+=1){let l=t[a];if(Mt(l)){let d=[],u=new Set;for(let C of l.tool_calls){let T=C.id;!T||s.has(T)||u.has(T)||(u.add(T),d.push(C))}let p=new Set,c=[],h=[],m=!1;for(let C=a+1;C<t.length;C+=1){let T=t[C];if(T.role==="tool"&&"tool_call_id"in T){if(!T.tool_call_id){m=!1;continue}u.has(T.tool_call_id)&&!p.has(T.tool_call_id)?(p.add(T.tool_call_id),c.push(C),m=!0):m=!1;continue}if(un(T)){m&&h.push(C);continue}if(!(T.role==="assistant"&&!Mt(T)))break}let g=d.filter(C=>p.has(C.id));for(let C of g)s.add(C.id);n.set(a,g),o.set(a,c),r.set(a,h)}}for(let a=0;a<t.length;a+=1){if(i.has(a))continue;let l=t[a];if(Mt(l)){let d=l.reasoning_content,u=n.get(a)??[];if(u.length>0){let p={...l};p.tool_calls=u,e.push(p);for(let c of o.get(a)??[]){let h=t[c];h&&(e.push(h),i.add(c))}for(let c of r.get(a)??[]){let h=t[c];h&&(e.push(h),i.add(c))}}else if(typeof l.content=="string"&&l.content.trim()||d){let p={...l};delete p.tool_calls,e.push(p)}else P.debug(`cleanOrphanedToolCalls: dropping assistant with ${l.tool_calls.length} orphaned tool call(s) and no text/reasoning content`)}else l.role==="tool"&&"tool_call_id"in l?P.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):un(l)?P.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):e.push(l)}return e}function pn(t){let e=[];for(let n of t){if(n.role==="assistant"&&e.length>0){let o=e[e.length-1];if(o.role==="assistant"){let r="tool_calls"in o?o.tool_calls||[]:[],i="tool_calls"in n?n.tool_calls||[]:[],s=o.content,a=n.content,l=Array.isArray(s)||Array.isArray(a),d;if(l){let p=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[],c=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[];d=[...p,...c]}else d=[typeof s=="string"?s:"",typeof a=="string"?a:""].filter(Boolean).join("")||null;let u=[...r,...i];o.content=d||null,u.length>0&&(o.tool_calls=u);continue}}e.push(n)}return e}var Ue={convertGeminiToolParametersToOpenAI:mn,convertGeminiToolsToOpenAI:Ro,convertGeminiRequestToOpenAI:vo,convertGeminiResponseToOpenAI:bo,convertOpenAIResponseToGemini:Do,convertOpenAIChunkToGemini:Lo,flushOpenAIStreamToGemini:Uo};f();import*as x from"node:path";import{promises as Ge}from"node:fs";f();f();import Ko from"crypto";var Fe=new Uint8Array(256),Ne=Fe.length;function _t(){return Ne>Fe.length-16&&(Ko.randomFillSync(Fe),Ne=0),Fe.slice(Ne,Ne+=16)}f();var S=[];for(let t=0;t<256;++t)S.push((t+256).toString(16).slice(1));function yn(t,e=0){return S[t[e+0]]+S[t[e+1]]+S[t[e+2]]+S[t[e+3]]+"-"+S[t[e+4]]+S[t[e+5]]+"-"+S[t[e+6]]+S[t[e+7]]+"-"+S[t[e+8]]+S[t[e+9]]+"-"+S[t[e+10]]+S[t[e+11]]+S[t[e+12]]+S[t[e+13]]+S[t[e+14]]+S[t[e+15]]}f();f();import $o from"crypto";var Rt={randomUUID:$o.randomUUID};function Ho(t,e,n){if(Rt.randomUUID&&!e&&!t)return Rt.randomUUID();t=t||{};let o=t.random||(t.rng||_t)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){n=n||0;for(let r=0;r<16;++r)e[n+r]=o[r];return e}return yn(o)}var vt=Ho;import*as U from"os";var Ke=O("OPENAI_LOGGER"),Bo="########",jo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Vo(t,e){let n=e||process.cwd();if(!t)return x.join(n,"logs","openai");let o=t;return t==="~"||t.startsWith("~/")?o=x.join(U.homedir(),t.slice(1)):x.isAbsolute(t)||(o=x.resolve(n,t)),x.normalize(o)}function An(t){return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function zo(t){let e=t.split("#");if(e.length!==3)return;let[,n,o]=e;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function Wo(t){if(t)return J(t)?An(t):An(zo(t))}function qo(t){if(!t)return;let e=t.indexOf(Bo);if(e>0)return t.slice(0,e);if(jo.test(t))return t;let n=t.split("#");if(n.length>=3&&n[0])return n[0]}function Yo(t){let e=t?.trim(),n=qo(e);return!e&&!n?null:{...e?{promptId:e}:{},...n?{sessionId:n}:{}}}var ue=class{logDir;initialized=!1;constructor(e,n){this.logDir=Vo(e,n)}async initialize(){if(!this.initialized)try{await Ge.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(e){throw Ke.error("Failed to initialize OpenAI logger:",e),new Error(`Failed to initialize OpenAI logger: ${e}`)}}async logInteraction(e,n,o,r){this.initialized||await this.initialize();let i=new Date().toISOString().replace(/:/g,"-"),s=vt().slice(0,8),a=Wo(r),l=a?`openai-${i}-${s}-${a}.json`:`openai-${i}-${s}.json`,d=x.join(this.logDir,l),u={timestamp:new Date().toISOString(),request:e,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:Yo(r),system:{hostname:U.hostname(),platform:U.platform(),release:U.release(),nodeVersion:process.version}};try{return await Ge.writeFile(d,JSON.stringify(u,null,2),"utf-8"),d}catch(p){throw Ke.error("Failed to write OpenAI log file:",p),new Error(`Failed to write OpenAI log file: ${p}`)}}async getLogFiles(e){this.initialized||await this.initialize();try{let o=(await Ge.readdir(this.logDir)).filter(r=>r.startsWith("openai-")&&r.endsWith(".json")).map(r=>x.join(this.logDir,r)).sort().reverse();return e?o.slice(0,e):o}catch(n){return n.code==="ENOENT"?[]:(Ke.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(e){try{let n=await Ge.readFile(e,"utf-8");return JSON.parse(n)}catch(n){throw Ke.error(`Failed to read log file ${e}:`,n),new Error(`Failed to read log file: ${n}`)}}},Gs=new ue;f();f();Y();Co();f();Y();var Sn=mo(ho(),1);import{createHash as Jo}from"node:crypto";var Z="matilda.telemetry.traceparent",$e="matilda.telemetry.tracestate",Xo="matilda-code.daemon.request",En="matilda-code.daemon.bridge",Qo="matilda-code.daemon.error";function Zo(t){return t instanceof Error?t.message:String(t)}function er(t){return t instanceof Error?t.name||"Error":typeof t}var tr="0".repeat(32),nr="0".repeat(16);function or(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e=t;if(!(Z in e)&&!($e in e))return{...e};let n={...e};return delete n[Z],delete n[$e],n}function rr(t){return Jo("sha256").update(t).digest("hex").slice(0,16)}async function bt(t,e,n,o={}){if(!se())return await n(void 0);let r=o.autoOkOnSuccess??!0;return await v.getTracer(M).startActiveSpan(t,{kind:lt.INTERNAL,attributes:e},async s=>{try{let a=await n(s);return r&&s.setStatus({code:ie.OK}),a}catch(a){throw _n(s,a),a}finally{s.end()}})}async function ir(t,e){return await bt(Xo,{"http.request.method":t.method,"http.route":t.route,"matilda-code.daemon.operation":"http_request",...t.workspaceHash?{"matilda-code.workspace.hash":t.workspaceHash}:{},...t.sessionId?{"session.id":t.sessionId}:{},...t.clientId?{"matilda-code.client_id":t.clientId}:{},...t.permissionRequestId?{"matilda-code.daemon.permission.request_id":t.permissionRequestId}:{}},e,{autoOkOnSuccess:!1})}async function Mn(t,e,n){return await bt(En,{"matilda-code.daemon.operation":t,...e},async()=>await n())}function sr(t,e){try{t?.setAttribute("http.response.status_code",e)}catch{}}function ar(t,e){try{v.getSpan(_.active())?.setAttribute(t,e)}catch{}}function _n(t,e,n={}){let o=t??v.getSpan(_.active());if(o)try{let r=ut(Zo(e));o.recordException(e instanceof Error?e:new Error(r)),o.setAttributes({"error.type":er(e),"error.message":r,...n}),o.setStatus({code:ie.ERROR,message:r})}catch{}}function lr(t,e={},n){if(se())try{Sn.logs.getLogger(M).emit({body:t,timestamp:new Date,attributes:{"event.name":n?.eventName??Qo,...e},...n?.severityNumber!=null?{severityNumber:n.severityNumber}:{}})}catch{}}function Rn(){return{context:_.active()}}async function vn(t,e){let n=t&&typeof t=="object"&&"context"in t&&t.context?t.context:void 0;return n?await _.with(n,e):await e()}function bn(t){let e=t._meta,n=or(e);try{let o=Vt();o&&(n[Z]=dt(o))}catch{}return!e&&!n[Z]?t:{...t,_meta:n}}function dr(t){let e=t?._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,o=n[Z];if(typeof o!="string"||o.length===0)return;let r={traceparent:o},i=n[$e];typeof i=="string"&&i.length>0&&(r.tracestate=i);let s=jt.extract(at,r);if(v.getSpanContext(s))return s;let a=o.split("-"),l=a[1],d=a[2],u=a[3];if(!(a[0]!=="00"||!l?.match(/^[0-9a-f]{32}$/)||!d?.match(/^[0-9a-f]{16}$/)||!u?.match(/^[0-9a-f]{2}$/)||l===tr||d===nr))return v.setSpan(at,v.wrapSpanContext({traceId:l,spanId:d,traceFlags:Number.parseInt(u,16),isRemote:!0}))}function cr(){return{captureContext:Rn,runWithContext:vn,withSpan:Mn,event(t,e){if(se())try{let n=v.getSpan(_.active());if(n){n.addEvent(t,e);return}let o=v.getTracer(M).startSpan(En,{kind:lt.INTERNAL,attributes:{"event.name":t,"matilda-code.daemon.operation":`event.${t}`,...e}});o.addEvent(t,e),o.setStatus({code:ie.OK}),o.end()}catch{}},injectPromptContext:bn}}f();Y();var ur=`${M}.daemon.http.request.count`,pr=`${M}.daemon.http.request.duration`,fr=`${M}.daemon.session.active`,gr=`${M}.daemon.session.lifecycle`,mr=`${M}.daemon.channel.lifecycle`,hr=`${M}.daemon.prompt.queue_wait`,Cr=`${M}.daemon.prompt.duration`,Tr=`${M}.daemon.bridge.error.count`,yr=`${M}.daemon.cancel.count`,Ar=`${M}.daemon.sse.active`,Sr=`${M}.daemon.process.heap_used`,Er=new Set(["SessionNotFoundError","WorkspaceMismatchError","InvalidClientIdError","SessionLimitExceededError","RestoreInProgressError","InvalidSessionScopeError","TrustGateError","WorkspaceInitConflictError","WorkspaceInitPathEscapeError","WorkspaceInitSymlinkError","WorkspaceInitRaceError","McpServerNotFoundError","McpServerRestartFailedError","PromptDeadlineExceededError","InvalidSessionMetadataError","SubscriberLimitExceededError","BridgeChannelClosedError","BridgeTimeoutError","PermissionForbiddenError"]),D=!1,xn,In,On,wn,Pn,Dn,Ln,Un;function Mr(t){let e=t instanceof Error?t.name:typeof t;return Er.has(e)?e:"unknown"}function _r(){if(D)return;let t=ct();t&&(xn=t.createCounter(ur,{description:"Daemon HTTP request count by route and status class.",valueType:R.INT}),In=t.createHistogram(pr,{description:"Daemon HTTP request duration in milliseconds.",unit:"ms",valueType:R.DOUBLE,advice:{explicitBucketBoundaries:[1,2,5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4]}}),On=t.createCounter(gr,{description:"Daemon session lifecycle events (spawn, close, die).",valueType:R.INT}),wn=t.createCounter(mr,{description:"Daemon ACP channel lifecycle events (spawn, exit).",valueType:R.INT}),Pn=t.createHistogram(hr,{description:"Time a prompt waited in the per-session FIFO queue.",unit:"ms",valueType:R.DOUBLE,advice:{explicitBucketBoundaries:[1,5,10,50,100,500,1e3,5e3,1e4,3e4,6e4]}}),Dn=t.createHistogram(Cr,{description:"End-to-end prompt duration from dispatch to completion.",unit:"ms",valueType:R.DOUBLE,advice:{explicitBucketBoundaries:[100,500,1e3,2500,5e3,1e4,3e4,6e4,12e4,3e5,6e5]}}),Ln=t.createCounter(Tr,{description:"Daemon bridge error count by normalized error type.",valueType:R.INT}),Un=t.createCounter(yr,{description:"Daemon cancel request count.",valueType:R.INT}),D=!0)}var kn=!1;function Rr(t){if(kn)return;let e=ct();e&&(e.createObservableGauge(fr,{description:"Current number of active daemon sessions.",valueType:R.INT}).addCallback(n=>{try{n.observe(t.sessionCount())}catch{}}),e.createObservableGauge(Ar,{description:"Current number of active SSE connections.",valueType:R.INT}).addCallback(n=>{try{n.observe(t.sseCount())}catch{}}),e.createObservableGauge(Sr,{description:"Daemon process heap memory usage in bytes.",unit:"bytes",valueType:R.INT}).addCallback(n=>{try{n.observe(t.heapUsed())}catch{}}),kn=!0)}function vr(t,e,n){if(!D)return;let o=`${Math.floor(n/100)}xx`;xn?.add(1,{route:e,status_class:o}),In?.record(t,{route:e})}function br(t){D&&On?.add(1,{action:t})}function kr(t,e){D&&wn?.add(1,{action:t,...e!=null?{expected:e}:{}})}function xr(t){D&&Pn?.record(t)}function Ir(t){D&&Dn?.record(t)}function Or(t){D&&Ln?.add(1,{error_type:Mr(t)})}function wr(){D&&Un?.add(1)}f();Y();import*as G from"node:fs";import*as rt from"node:path";f();f();f();f();Y();f();import{AsyncLocalStorage as Pr}from"node:async_hooks";var Nn=new Pr;f();function Fn(t){let e=t.candidates?.[0]?.content?.parts;return!e||e.length===0?!1:e.some(Dr)}function Dr(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.text=="string"&&e.text.length>0||e.functionCall!==void 0||e.inlineData!==void 0||e.executableCode!==void 0||e.thought===!0}function Gn(){let t=Jt.getStore();return{attempt:t?.attempt??1,requestSetupMs:t?.requestSetupMs,retryTotalDelayMs:t?.retryTotalDelayMs}}var V=O("LOGGING_CONTENT_GENERATOR"),Lr=4096,Kn="...[truncated]",Ur=Lr-Kn.length,pe=class{constructor(e,n,o){this.wrapped=e;this.config=n;this.modalities=o.modalities,this.splitToolMedia=o.splitToolMedia,this.generatorAuthType=o.authType,o.enableOpenAILogging&&(this.openaiLogger=new ue(o.openAILoggingDir,n.getWorkingDir()),this.schemaCompliance=o.schemaCompliance)}openaiLogger;schemaCompliance;modalities;splitToolMedia;generatorAuthType;getWrapped(){return this.wrapped}logApiRequest(e,n,o){let r=JSON.stringify(e);pt(this.config,new mt(n,o,r,L.getStore()))}_logApiResponse(e,n,o,r,i,s){gt(this.config,new Ct(e,o,n,r,this.generatorAuthType,i,s,L.getStore()))}_logApiError(e,n,o,r,i){let s=Bt(o),a=re(o),l=o?.requestID||o?.request_id||e,d=oe(o);ft(this.config,new ht({responseId:l,model:r,durationMs:n,promptId:i,authType:this.generatorAuthType,errorMessage:s,errorType:a,statusCode:d,subagentName:L.getStore()}))}safelyLogApiError(e,n,o,r,i){try{this._logApiError(e,n,o,r,i)}catch(s){V.warn("Failed to log API error:",s)}}safelyLogApiResponse(e,n,o,r,i,s){try{this._logApiResponse(e,n,o,r,i,s)}catch(a){V.warn("Failed to log API response:",a)}}getClientVisibleModelId(e,n){return("isManagedMatildaModel"in this.config&&typeof this.config.isManagedMatildaModel=="function"?this.config.isManagedMatildaModel(e):!1)&&"getPublicModelId"in this.config&&typeof this.config.getPublicModelId=="function"?this.config.getPublicModelId(e):n||e}async generateContent(e,n){let o=Gn(),r=ke(e.model,n);try{r.setAttribute("llm_request.stream",!1)}catch{}let i=v.setSpan(_.active(),r),s=Date.now(),a=J(n),l=this.startCaptureSession();try{Tt.recordGenerateContentRequest(e,{stream:!1,source:"generateContent"}),a||(Re(this.config,r,e.config?.systemInstruction),ve(this.config,r,e.config?.tools));let d=await _.with(i,async()=>{a||this.logApiRequest(this.toContents(e.contents),e.model,n);let u=await l.wrap(()=>this.wrapped.generateContent(e,n)),p=Date.now()-s,c=a?void 0:this.extractResponseText(u);a||be(this.config,r,c),this.safelyLogApiResponse(u.responseId??"",p,this.getClientVisibleModelId(e.model,u.modelVersion),n,u.usageMetadata,c);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),u,void 0,n)}catch(h){V.warn("Failed to log OpenAI interaction:",h)}return u});return H(r,{success:!0,inputTokens:d.usageMetadata?.promptTokenCount,outputTokens:d.usageMetadata?.candidatesTokenCount,cachedInputTokens:d.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-s,responseId:d.responseId||void 0,finishReason:d.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:d.usageMetadata?.thoughtsTokenCount,subagentName:L.getStore()||void 0,...o}),d}catch(d){let u=Date.now()-s,p=e.config?.abortSignal?.aborted??!1;throw H(r,{success:!1,durationMs:u,error:p?Ie:xe,errorType:re(d),errorStatusCode:oe(d),subagentName:L.getStore()||void 0,...o}),await _.with(i,async()=>{this.safelyLogApiError("",u,d,this.getClientVisibleModelId(e.model),n);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,d,n)}catch(c){V.warn("Failed to log OpenAI interaction:",c)}}),d}}async generateContentStream(e,n){let o=Gn(),r=ke(e.model,n);try{r.setAttribute("llm_request.stream",!0)}catch{}let i=v.setSpan(_.active(),r),s=Date.now(),a=J(n),l=this.startCaptureSession(),d;try{Tt.recordGenerateContentRequest(e,{stream:!0,source:"generateContentStream"}),a||(Re(this.config,r,e.config?.systemInstruction),ve(this.config,r,e.config?.tools)),d=await _.with(i,async()=>(a||this.logApiRequest(this.toContents(e.contents),e.model,n),l.wrap(()=>this.wrapped.generateContentStream(e,n))))}catch(p){let c=Date.now()-s;_.with(i,()=>this.safelyLogApiError("",c,p,e.model,n));let h=e.config?.abortSignal?.aborted??!1;H(r,{success:!1,durationMs:c,error:h?Ie:xe,errorType:re(p),errorStatusCode:oe(p),subagentName:L.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,p,n)}catch(m){V.warn("Failed to log OpenAI interaction:",m)}throw p}let u;if(this.openaiLogger)try{u=await l.resolve(e)}catch(p){V.warn("Failed to resolve OpenAI request:",p)}return _.with(i,()=>this.loggingStreamWrapper(d,s,n,e.model,u,r,i,e.config?.abortSignal,o))}startCaptureSession(){let e,n=!this.openaiLogger;return{wrap:o=>n?o():Nn.run(r=>{e=r},o),resolve:async o=>this.openaiLogger?e??await this.buildOpenAIRequestForLogging(o):void 0}}async*loggingStreamWrapper(e,n,o,r,i,s,a,l,d){let u=J(o),p=!u||!!this.openaiLogger,c=[],h="",m="",g,C=!1,T,y,E=L.getStore(),b,K=!1,q=k=>a?_.with(a,k):k(),it=5*6e4,w,Kt=s?()=>{K||(w!==void 0&&clearTimeout(w),w=setTimeout(()=>{try{s.setAttribute("stream.timed_out",!0)}catch{}H(s,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:h||void 0,subagentName:E||void 0,...d}),K=!0},it),w.unref())}:void 0;Kt?.();try{for await(let I of e){!h&&I.responseId&&(h=I.responseId),!m&&I.modelVersion&&(m=I.modelVersion),p&&c.push(I),I.usageMetadata&&(g=I.usageMetadata);let Ht=I.candidates?.[0];Ht?.finishReason&&(T=Ht.finishReason),b===void 0&&Fn(I)&&(b=Date.now()-n),Kt?.(),yield I}w!==void 0&&(clearTimeout(w),w=void 0);let k=Date.now()-n,Ee=p?this.consolidateGeminiResponsesForLogging(c):void 0,$t=u?void 0:this.extractResponseText(Ee);K||(q(()=>this.safelyLogApiResponse(h,k,this.getClientVisibleModelId(r,m),o,g,$t)),!u&&s&&be(this.config,s,$t),await q(()=>this.safelyLogOpenAIInteraction(i,Ee,void 0,o)))}catch(k){if(C=!0,y=k,!K){let Ee=Date.now()-n;q(()=>this.safelyLogApiError(h,Ee,k,this.getClientVisibleModelId(r,m),o)),await q(()=>this.safelyLogOpenAIInteraction(i,void 0,k,o))}throw k}finally{if(w!==void 0&&clearTimeout(w),s&&!K){let k=l?.aborted??!1;H(s,{success:!C,inputTokens:g?.promptTokenCount,outputTokens:g?.candidatesTokenCount,cachedInputTokens:g?.cachedContentTokenCount,ttftMs:b,durationMs:Date.now()-n,error:C?k?Ie:xe:void 0,responseId:h||void 0,finishReason:T,thoughtsTokenCount:g?.thoughtsTokenCount,subagentName:E||void 0,errorType:y?re(y):void 0,errorStatusCode:y?oe(y):void 0,...d})}}}async buildOpenAIRequestForLogging(e){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(e.model),o=Ue.convertGeminiRequestToOpenAI(e,n,{cleanOrphanToolCalls:!1}),r={model:e.model,messages:o};return e.config?.tools&&(r.tools=await Ue.convertGeminiToolsToOpenAI(e.config.tools,this.schemaCompliance??"auto")),e.config?.temperature!==void 0&&(r.temperature=e.config.temperature),e.config?.topP!==void 0&&(r.top_p=e.config.topP),e.config?.maxOutputTokens!==void 0&&(r.max_tokens=e.config.maxOutputTokens),e.config?.presencePenalty!==void 0&&(r.presence_penalty=e.config.presencePenalty),e.config?.frequencyPenalty!==void 0&&(r.frequency_penalty=e.config.frequencyPenalty),r}createLoggingRequestContext(e){return{model:e,modalities:this.modalities??{},splitToolMedia:this.splitToolMedia??!0,startTime:0}}async logOpenAIInteraction(e,n,o,r){if(!this.openaiLogger||!e)return;let i=n?this.convertGeminiResponseToOpenAIForLogging(n,e):void 0;await this.openaiLogger.logInteraction(e,i,o instanceof Error?o:o?new Error(String(o)):void 0,r)}async safelyLogOpenAIInteraction(e,n,o,r){try{await this.logOpenAIInteraction(e,n,o,r)}catch(i){V.warn("Failed to log OpenAI interaction:",i)}}convertGeminiResponseToOpenAIForLogging(e,n){let o=new $;return Object.assign(o,e),o.modelVersion=this.getClientVisibleModelId(n.model,e.modelVersion),Ue.convertGeminiResponseToOpenAI(o,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(e){if(e.length===0)return;let n=new $,o=[],r=new Map,i,s;for(let d of e){d.usageMetadata&&(s=d.usageMetadata);let u=d.candidates?.[0];u?.finishReason&&(i=u.finishReason);let p=u?.content?.parts??[];for(let c of p){if(typeof c=="string"){o.push({text:c});continue}if("text"in c){c.text&&o.push({text:c.text,...c.thought?{thought:!0}:{},...c.thoughtSignature?{thoughtSignature:c.thoughtSignature}:{}});continue}if("functionCall"in c&&c.functionCall){let h=c.functionCall.id||c.functionCall.name||"tool_call",m=r.get(h),g={functionCall:c.functionCall};m!==void 0?o[m]=g:(r.set(h,o.length),o.push(g));continue}if("functionResponse"in c&&c.functionResponse){o.push({functionResponse:c.functionResponse});continue}o.push(c)}}let a=e[e.length-1],l=a.candidates?.[0];return n.responseId=a.responseId,n.createTime=a.createTime,n.modelVersion=a.modelVersion,n.promptFeedback=a.promptFeedback,n.usageMetadata=s,n.candidates=[{content:{role:l?.content?.role||"model",parts:o},...i?{finishReason:i}:{},index:0,safetyRatings:l?.safetyRatings||[]}],n}extractResponseText(e){let n=e?.candidates?.[0]?.content?.parts;if(!n?.length)return;let o="",r=!1,i=!1,s=a=>{if(r=!0,i)return;let l=Ur-o.length;if(a.length<=l){o+=a;return}o+=a.slice(0,Math.max(0,l)),i=!0};for(let a of n){if(typeof a=="string"){s(a);continue}"text"in a&&typeof a.text=="string"&&!("thought"in a&&a.thought)&&s(a.text)}if(r)return i?`${o}${Kn}`:o}async countTokens(e){return this.wrapped.countTokens(e)}async embedContent(e){return this.wrapped.embedContent(e)}useSummarizedThinking(){return this.wrapped.useSummarizedThinking()}toContents(e){return Array.isArray(e)?e.map(n=>this.toContent(n)):[this.toContent(e)]}toContent(e){return Array.isArray(e)?{role:"user",parts:this.toParts(e)}:typeof e=="string"?{role:"user",parts:[{text:e}]}:"parts"in e?{...e,parts:e.parts?this.toParts(e.parts.filter(n=>n!=null)):[]}:{role:"user",parts:[this.toPart(e)]}}toParts(e){return e.map(n=>this.toPart(n))}toPart(e){if(typeof e=="string")return{text:e};if("thought"in e&&e.thought){let n=`[Thought: ${e.thought}]`,o={...e};if(delete o.thought,"functionCall"in o||"functionResponse"in o||"inlineData"in o||"fileData"in o)return o;let i=o.text,s=i?String(i):"",a=s?`${s}
|
|
8
|
-
${n}`:n;return{...o,text:a}}return e}};f();function $n(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 Hn(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 N=class extends Error{constructor(e){super(e),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},He=class extends N{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.`))}},Be=class extends N{code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},je=class extends N{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}'.`)}},Ve=class extends N{code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}},ze=class extends N{code="MISSING_BASE_URL";constructor(e){super(`Missing baseUrl for modelProviders model '${e.model||"(unknown)"}'. Configure modelProviders.${e.authType||"(unknown)"}[].baseUrl.`)}},We=class extends N{code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};f();import Gr from"node:process";f();var Bn={image:!0,pdf:!0,audio:!0,video:!0},Nr=[[/^gemini-3/,Bn],[/^gemini-/,Bn],[/^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 fe(t){let e=Zt(t);for(let[n,o]of Nr)if(n.test(e))return{...o};return{}}f();var qe="$runtime|";function wa(t){let e=t;for(;e.startsWith(qe);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}f();f();f();var Ye=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],jn=["model","apiKey","apiKeyEnvKey","baseUrl"],Je=[...jn,...Ye],Na={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:[]}},Fa={openai:Qt,"matilda-oauth":B},Xe=[{id:"coder-model",name:"coder-model",description:"Matilda 3.6 Plus \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:!0}}],Ga=Xe.map(t=>t.id);var kt=O("MODEL_REGISTRY");function Vn(t){if(Object.values(F).includes(t))return t}function Fr(t){return/^minimax-m3/i.test(t.trim().toLowerCase())}function zn(t,e){return e?`${t}\0${e}`:t}var Qe=class{modelsByAuthType;getDefaultBaseUrl(e){switch(e){case"matilda-oauth":return"DYNAMIC_MATILDA_OAUTH_BASE_URL";case"openai":return qt;default:return""}}constructor(e){if(this.modelsByAuthType=new Map,this.registerAuthTypeModels("matilda-oauth",Xe),e)for(let[n,o]of Object.entries(e)){let r=Vn(n);if(!r){kt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(F).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}registerAuthTypeModels(e,n){let o=new Map;for(let r of n){let i=zn(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??ae(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(zn(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,B);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||Fr(e.id))&&(o.modalities=fe(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=Vn(n);if(!r){kt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(F).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}};var Wn=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 Qe(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||B}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(F),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===yt&&e?.envKey===en&&e?.baseUrl===nn&&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)?yt:e}getModelDisplayName(e){return this.isManagedMatildaModel(e)?tn:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,e)?.name??e:e}async setModel(e,n){if(this.currentAuthType==="matilda-oauth"&&e===B){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=fe(e),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=ae(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||"",d=!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&&d?.envKey===a.envKey&&d.baseUrl===a.baseUrl,p=u?i.generationConfig.apiKey:void 0,c=u?i.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(a),!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,c&&(this.generationConfigSources.apiKey=t.deepClone(c))),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`${qe}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(qe))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 Ye)!(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 Je)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=Gr.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 Ye)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=ae(e.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=fe(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,g=m?this._generationConfig.apiKey:void 0,C=m&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,T=this.generationConfigSources.baseUrl,y=m&&!!this._generationConfig.baseUrl&&(T?.kind==="cli"||T?.kind==="env"||T?.kind==="settings"),E=y?this._generationConfig.baseUrl:void 0,b=y&&T?{...T}:void 0;this.applyResolvedModelDefaults(i),m&&!this._generationConfig.apiKey&&g&&(this._generationConfig.apiKey=g,C&&(this.generationConfigSources.apiKey=C)),E&&(this._generationConfig.baseUrl=E,b&&(this.generationConfigSources.baseUrl=b)),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),d={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,d),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)}};f();import{readFileSync as ni}from"node:fs";import{join as oi}from"node:path";f();f();import{randomBytes as Kr,createHash as $r}from"node:crypto";function qn(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function xt(){let t=Kr(32).toString("base64url"),e=$r("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function ge(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 It(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!qn(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}}f();import{promises as Ze,openSync as Hr,closeSync as Br,unlinkSync as Yn,statSync as jr}from"node:fs";import{dirname as Vr}from"node:path";var zr=1e4,Wr=3e4,qr=50;function Ot(t){let e=async()=>{try{let r=await Ze.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 Ze.mkdir(Vr(t),{recursive:!0}),await Ze.writeFile(t,JSON.stringify(r,null,2),{mode:384}),await Ze.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:Yr(`${t}.lock`)}}function Yr(t){let e=Promise.resolve();return n=>{let o=e.then(async()=>{await Jr(t);try{return await n()}finally{Xr(t)}});return e=o.then(()=>{},()=>{}),o}}async function Jr(t){let e=Date.now()+zr;for(;;)try{Br(Hr(t,"wx"));return}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-jr(t).mtimeMs>Wr){Yn(t);continue}}catch{continue}if(Date.now()>e)throw new Error(`Timed out acquiring credential lock at ${t}`);await Qr(qr)}}function Xr(t){try{Yn(t)}catch{}}function Qr(t){return new Promise(e=>setTimeout(e,t))}f();var ee=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function wt(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 d=JSON.parse(l);return d.accessToken?d:null}catch{return null}},s=l=>l.expiresAt-Date.now()>o,a=l=>t.lock(async()=>{let d=await i()??l;if(d.accessToken!==l.accessToken&&s(d))return d.accessToken;if(!d.refreshToken)throw new ee("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:d.refreshToken})});if(!u.ok){let h=await u.text().catch(()=>"");throw u.status>=400&&u.status<500&&Zr(h)==="invalid_grant"?(await t.store.remove(e),new ee):new Error(`Token refresh failed (${u.status})`)}let p=await u.json(),c=ge(p,d);return await t.store.set(e,JSON.stringify(c)),c.accessToken});return{async getAccessToken(l){let d=await i();if(!d)throw new ee("Not signed in.");return!l?.forceRefresh&&s(d)?d.accessToken:(r||(r=a(d).finally(()=>{r=null})),r)}}}function Zr(t){try{return JSON.parse(t).error}catch{return}}f();import{createServer as ei}from"node:http";import{randomBytes as ti}from"node:crypto";async function Pt(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}=xt(),r=ti(16).toString("hex"),i=t.timeoutMs??5*60*1e3,s=t.transport.successRedirect;e({type:"state",status:"idle"});let a,l,d=new Promise((m,g)=>{a=m,l=g});d.catch(()=>{});let u=ei((m,g)=>{let C=new URL(m.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){g.writeHead(404).end();return}let T=C.searchParams.get("error"),y=C.searchParams.get("state"),E=C.searchParams.get("code");if(T){Jn(g,s,()=>l(new Error(`OAuth error: ${T}`)));return}if(y!==r){g.writeHead(400).end("State mismatch"),l(new Error("OAuth state mismatch"));return}if(!E){g.writeHead(400).end("Missing authorization code");return}Jn(g,s,()=>a(E))}),p=await new Promise((m,g)=>{u.once("error",g),u.listen(t.transport.port??0,"127.0.0.1",()=>{m(u.address().port)})}),c=setTimeout(()=>l(new Error("Login timed out \u2014 no callback received")),i),h=()=>l(new Error("Login aborted"));t.signal?.addEventListener("abort",h,{once:!0});try{let m=`http://127.0.0.1:${p}/callback`,g=new URL(t.metadata.authorization_endpoint);g.searchParams.set("client_id",t.clientId),g.searchParams.set("response_type","code"),g.searchParams.set("redirect_uri",m),g.searchParams.set("code_challenge",o),g.searchParams.set("code_challenge_method","S256"),g.searchParams.set("state",r),g.searchParams.set("scope",t.scope??"openid offline_access");let C=g.toString();e({type:"authorize_url",url:C}),e({type:"state",status:"awaiting_user"}),t.openBrowser&&await t.openBrowser(C);let T=await d;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 b=await y.text().catch(()=>"");throw new Error(`Token exchange failed (${y.status}): ${b}`)}let E=ge(await y.json());return e({type:"state",status:"authenticated"}),E}catch(m){throw e({type:"state",status:"error"}),m}finally{clearTimeout(c),t.signal?.removeEventListener("abort",h),u.close()}}function Jn(t,e,n){t.writeHead(302,{location:e}).end(n)}var me="matilda-code",Xn="matilda-desktop",he="MATILDA_API_KEY",ri="openid profile email offline_access matilda:code",ii="matilda";function Ce(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function Qn(){return oi(Me.getGlobalMatildaDir(),"matilda-auth.json")}function et(){return Ot(Qn())}function si(t){return t==="desktop"}function Te(t){return t?.clientId?t.clientId:si(t?.channel)?Xn:me}function ne(t){return`matilda:${t}`}function tt(t){return`${ne(t)}:refresh-rejected`}function ye(t){return t===me?[ne(t),ii]:[ne(t)]}function ai(){try{let t=ni(Qn(),"utf8");return JSON.parse(t)}catch{return{}}}function Dt(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 li(t,e){return Ce(t)===Ce(e)}function di(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 ci(t,e){let n=di(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 It(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 z(t){try{let e=ai(),n=Te(t);for(let o of ye(n)){let r=Dt(e[o]);if(r)return r}return null}catch{return null}}async function ui(t){let e=Te(t),n=et().store;for(let o of ye(e))await n.remove(o);await n.set(tt(e),"1"),delete process.env[he]}function pi(t){return t instanceof Error?t.code==="invalid_grant"||t.name==="InvalidGrantError"?!0:t.message==="Token refresh failed (401)":!1}function te(t){Lt({authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:t.occurrenceCount},{baseUrl:t.baseUrl,token:t.token}).catch(()=>{})}async function fi(t,e){let n=Te(e),o=et().store;await o.set(ne(n),JSON.stringify(t)),await o.remove(tt(n));for(let r of ye(n))r!==ne(n)&&await o.remove(r);process.env[he]=t.accessToken}async function gi(t){let e=Te(t),n=et().store;for(let o of ye(e))await n.remove(o);await n.remove(tt(e)),delete process.env[he]}function $l(t){let e=z(t);return e?{authenticated:!0,userId:e.userId,email:e.email,displayName:e.displayName,baseUrl:e.baseUrl,accessTokenExpiresAt:e.accessTokenExpiresAt}:{authenticated:!1}}async function Hl(t){let e={channel:t?.channel,clientId:t?.clientId},n=z(e);if(n?.accessToken){let o=Ce(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 gi(e)}async function Ut(t){let e=Te(t),n=ne(e),o=z({channel:t?.channel,clientId:e});if(!o||t?.baseUrl&&!li(o.baseUrl,t.baseUrl))return t?.fallbackAccessToken??process.env[he]??"";let r=Ce(o.baseUrl),i=await Zn(r),{store:s,lock:a}=et(),l=mi(s,a,i.token_endpoint,o.baseUrl,e,n,t?.signal),d=e===me&&(!!t?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=3e5),u;try{u=await l.getAccessToken({forceRefresh:t?.forceRefresh})}catch(p){throw d&&te({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"}),e===Xn&&pi(p)&&await ui({channel:t?.channel,clientId:e}),p}return d&&te({baseUrl:o.baseUrl,token:u,authStage:"refresh",authOutcome:"succeeded"}),process.env[he]=u,u}async function Bl(t){await Ut(t);let e=z(t);if(!e)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return e}function mi(t,e,n,o,r,i,s){let a=ye(r);return wt({tokenEndpoint:n,clientId:r,store:{get:async u=>{let p=u===i?a:[u],c=null;for(let m of p)if(c=Dt(await t.get(m)),c)break;if(!c?.accessToken)return null;let h={accessToken:c.accessToken,refreshToken:c.refreshToken,expiresAt:c.accessTokenExpiresAt};return JSON.stringify(h)},set:async(u,p)=>{let c=JSON.parse(p),h=u===i?a:[u],m={};for(let C of h){let T=Dt(await t.get(C));if(T){m=T;break}}let g={...m,accessToken:c.accessToken,accessTokenExpiresAt:c.expiresAt,refreshToken:c.refreshToken??m.refreshToken??"",baseUrl:m.baseUrl??o};await t.set(i,JSON.stringify(g)),await t.remove(tt(r));for(let C of a)C!==i&&await t.remove(C)},remove:async u=>{let p=u===i?a:[u];for(let c of p)await t.remove(c)}},storageKey:i,lock:e,fetchImpl:(u,p)=>fetch(u,{...p,signal:s}),expirySkewMs:3e5})}function hi(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&on()}async function jl(t){let e=Ce(t.baseUrl),n=await Zn(e),o="",r=0,i=0,s={},a=p=>{s[p]=(s[p]??0)+1},l=p=>(r+=1,Pt({metadata:n,clientId:me,scope:p,transport:{kind:"loopback",successRedirect:`${e}/api/auth/oauth/success?client_id=${encodeURIComponent(me)}`},signal:t.signal,onEvent:c=>{c.type==="authorize_url"&&(o=c.url,t.onAuthorizeUrl?.(c.url)),c.type==="state"&&c.status==="exchanging"&&(i+=1)},openBrowser:async c=>{if(t.openBrowser===!1||!hi()){a("skipped");return}try{let{default:h}=await import("./open-QQ7FWG4A.js");(await h(c)).once("error",()=>{}),a("succeeded")}catch{a("failed")}}})),d;try{d=await l(ri)}catch(p){if(p instanceof Error&&p.message.includes("invalid_scope"))d=await l("openid offline_access");else throw p}let u=ci(d,t.baseUrl);await fi(u),te({baseUrl:t.baseUrl,token:u.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:r});for(let[p,c]of Object.entries(s))te({baseUrl:t.baseUrl,token:u.accessToken,authStage:"browser_opened",authOutcome:p,occurrenceCount:c});return i>0&&te({baseUrl:t.baseUrl,token:u.accessToken,authStage:"callback_received",authOutcome:"succeeded",occurrenceCount:i}),te({baseUrl:t.baseUrl,token:u.accessToken,authStage:"token_persisted",authOutcome:"succeeded"}),{...u,authorizeUrl:o}}var F=(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))(F||{}),Ci="MATILDA_AGENT_SDK",nt="MATILDA_API_KEY";function Ti(t,e){if(t.apiKey||t.apiKeyEnvKey!==nt)return;let n=z({channel:e});n?.accessToken&&(t.apiKey=n.accessToken,process.env[nt]=n.accessToken)}async function yi(t,e){if(t.apiKeyEnvKey!==nt)return;let n=z({channel:e});if(!n?.accessToken)return;let o=await Ut({baseUrl:t.baseUrl,fallbackAccessToken:n.accessToken,channel:e});o&&(t.apiKey=o,process.env[nt]=o)}function Ai(t){return t.matildaAgentSdk===!0||process.env[Ci]==="1"}function Nt(t,e,n){t[e]=n}function Si(t,e){return t?.[e]}function Ei(t,e,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:e,proxy:t?.getProxy()};Nt(i,"authType",{kind:"computed",detail:"provided by caller"}),t?.getProxy()&&Nt(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=u=>Si(o,u)??{kind:"unknown"};for(let u of Je)n&&u in n&&!i[u]&&Nt(i,u,l(u));Ti(a,t.getChannel());let d=to(a,s);if(!d.valid)throw new Error(d.errors.map(u=>u.message).join(`
|
|
9
|
-
`));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
|
|
10
|
-
`));let r=t.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai")if(
|
|
11
|
-
Please exit and restart Matilda to use the '${r}' provider.`,{cause:a}):s}return new pe(i,e,t)}var
|
|
12
|
-
`,"utf8")}catch{}}function
|
|
7
|
+
`)||""}function Ue(t,e,n=!0){if(e.taggedThinkingParser)return e.taggedThinkingParser.parse(t,n);if(e.responseParsingOptions?.taggedThinkingTags)return sn(t);if(!t)return[];let o=Pe(Et(t));return o?[{text:o}]:[]}function Po(t,e){let n=t.choices?.[0],o=new $;if(n){let r=[];if(!e.responseParsingOptions?.taggedThinkingTags){let i=n.message.reasoning_content??n.message.reasoning;i&&r.push({text:i,thought:!0})}if(n.message.content&&r.push(...Ue(n.message.content,e)),n.message.tool_calls){for(let i of n.message.tool_calls)if(i.function){let s=zt(i.function.arguments);if(s===null)continue;r.push({functionCall:{id:i.id,name:i.function.name,args:s}})}}o.candidates=[{content:{parts:r,role:"model"},finishReason:Tn(n.finish_reason||"stop"),index:0,safetyRatings:[]}]}else o.candidates=[];if(o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage){let r=t.choices?.[0]?.message,i=r?.reasoning_content??r?.reasoning??"",s=typeof r?.content=="string"?r.content:"";o.usageMetadata=gn(t.usage,{estimatedReasoningTokens:X(i.length),estimatedContentTokens:X(s.length)})}return o}function Do(t,e){let n=t.choices?.[0],o=new $,r=e.toolCallParser;if(!r)throw new Error("convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start.");if(n){let i=[];if(!e.responseParsingOptions?.taggedThinkingTags){let c=n.delta?.reasoning_content??n.delta?.reasoning;if(c){let u=ln(c,e.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});u&&i.push({text:u,thought:!0})}}if(typeof n.delta?.content=="string"){let c=ln(n.delta.content,e.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(c||n.finish_reason)&&i.push(...Ue(c,e,!!n.finish_reason))}else n.finish_reason&&i.push(...Ue("",e,!0));if(n.delta?.tool_calls)for(let c of n.delta.tool_calls){let u=c.index??0;c.function?.arguments?r.addChunk(u,c.function.arguments,c.id,c.function.name):r.addChunk(u,"",c.id,c.function?.name)}let s=!1;if(n.finish_reason){s=r.hasIncompleteToolCalls();let c=r.getCompletedToolCalls();for(let u of c)u.name&&i.push({functionCall:{id:u.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:u.name,args:u.args}})}let a=s&&n.finish_reason!=="length"?"length":n.finish_reason,l={content:{parts:i,role:"model"},index:0,safetyRatings:[]};a&&(l.finishReason=Tn(a)),o.candidates=[l]}else o.candidates=[];return o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage&&(o.usageMetadata=gn(t.usage,Uo(e))),o}function Lo(t){let e=t.toolCallParser;if(!e)return null;let n=[],o=e.getStrictCompletedToolCalls(),r=e.hasIncompleteToolCalls();for(let s of o)s.name&&n.push({functionCall:{id:s.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:s.name,args:s.args}});if(n.push(...Ue("",t,!0)),n.length===0&&!r)return null;let i=new $;return i.candidates=[{content:{parts:n,role:"model"},index:0,safetyRatings:[],finishReason:r?A.MAX_TOKENS:A.STOP}],i.responseId=`stream-flush-${Date.now()}`,i.createTime=new Date().getTime().toString(),i.modelVersion=t.model,i.promptFeedback={safetyRatings:[]},i}function Uo(t){return{estimatedReasoningTokens:X(t.reasoningDeltaState?.emittedLength??0),estimatedContentTokens:X(t.textDeltaState?.emittedLength??0)}}function Tn(t){return t?{stop:A.STOP,length:A.MAX_TOKENS,content_filter:A.SAFETY,function_call:A.STOP,tool_calls:A.STOP}[t]||A.FINISH_REASON_UNSPECIFIED:A.FINISH_REASON_UNSPECIFIED}function No(t){if(!t)return"stop";switch(t){case A.STOP:return"stop";case A.MAX_TOKENS:return"length";case A.SAFETY:case A.RECITATION:case A.BLOCKLIST:case A.PROHIBITED_CONTENT:case A.SPII:case A.IMAGE_SAFETY:case A.IMAGE_RECITATION:case A.IMAGE_PROHIBITED_CONTENT:case A.IMAGE_OTHER:return"content_filter";case A.NO_IMAGE:return"stop";default:return"stop"}}function Mt(t){return t.role==="assistant"&&"tool_calls"in t&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0}function un(t){if(t.role!=="user"||!("content"in t)||!Array.isArray(t.content))return!1;let e=t.content[0];return e?.type==="text"&&e.text===fn}function Fo(t){let e=[],n=new Map,o=new Map,r=new Map,i=new Set,s=new Set;for(let a=0;a<t.length;a+=1){let l=t[a];if(Mt(l)){let c=[],u=new Set;for(let C of l.tool_calls){let T=C.id;!T||s.has(T)||u.has(T)||(u.add(T),c.push(C))}let p=new Set,d=[],h=[],m=!1;for(let C=a+1;C<t.length;C+=1){let T=t[C];if(T.role==="tool"&&"tool_call_id"in T){if(!T.tool_call_id){m=!1;continue}u.has(T.tool_call_id)&&!p.has(T.tool_call_id)?(p.add(T.tool_call_id),d.push(C),m=!0):m=!1;continue}if(un(T)){m&&h.push(C);continue}if(!(T.role==="assistant"&&!Mt(T)))break}let g=c.filter(C=>p.has(C.id));for(let C of g)s.add(C.id);n.set(a,g),o.set(a,d),r.set(a,h)}}for(let a=0;a<t.length;a+=1){if(i.has(a))continue;let l=t[a];if(Mt(l)){let c=l.reasoning_content,u=n.get(a)??[];if(u.length>0){let p={...l};p.tool_calls=u,e.push(p);for(let d of o.get(a)??[]){let h=t[d];h&&(e.push(h),i.add(d))}for(let d of r.get(a)??[]){let h=t[d];h&&(e.push(h),i.add(d))}}else if(typeof l.content=="string"&&l.content.trim()||c){let p={...l};delete p.tool_calls,e.push(p)}else P.debug(`cleanOrphanedToolCalls: dropping assistant with ${l.tool_calls.length} orphaned tool call(s) and no text/reasoning content`)}else l.role==="tool"&&"tool_call_id"in l?P.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):un(l)?P.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):e.push(l)}return e}function pn(t){let e=[];for(let n of t){if(n.role==="assistant"&&e.length>0){let o=e[e.length-1];if(o.role==="assistant"){let r="tool_calls"in o?o.tool_calls||[]:[],i="tool_calls"in n?n.tool_calls||[]:[],s=o.content,a=n.content,l=Array.isArray(s)||Array.isArray(a),c;if(l){let p=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[],d=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[];c=[...p,...d]}else c=[typeof s=="string"?s:"",typeof a=="string"?a:""].filter(Boolean).join("")||null;let u=[...r,...i];o.content=c||null,u.length>0&&(o.tool_calls=u);continue}}e.push(n)}return e}var Ne={convertGeminiToolParametersToOpenAI:mn,convertGeminiToolsToOpenAI:_o,convertGeminiRequestToOpenAI:Ro,convertGeminiResponseToOpenAI:vo,convertOpenAIResponseToGemini:Po,convertOpenAIChunkToGemini:Do,flushOpenAIStreamToGemini:Lo};f();import*as k from"node:path";import{promises as Ke}from"node:fs";f();f();import Go from"crypto";var Ge=new Uint8Array(256),Fe=Ge.length;function _t(){return Fe>Ge.length-16&&(Go.randomFillSync(Ge),Fe=0),Ge.slice(Fe,Fe+=16)}f();var S=[];for(let t=0;t<256;++t)S.push((t+256).toString(16).slice(1));function yn(t,e=0){return S[t[e+0]]+S[t[e+1]]+S[t[e+2]]+S[t[e+3]]+"-"+S[t[e+4]]+S[t[e+5]]+"-"+S[t[e+6]]+S[t[e+7]]+"-"+S[t[e+8]]+S[t[e+9]]+"-"+S[t[e+10]]+S[t[e+11]]+S[t[e+12]]+S[t[e+13]]+S[t[e+14]]+S[t[e+15]]}f();f();import Ko from"crypto";var Rt={randomUUID:Ko.randomUUID};function $o(t,e,n){if(Rt.randomUUID&&!e&&!t)return Rt.randomUUID();t=t||{};let o=t.random||(t.rng||_t)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){n=n||0;for(let r=0;r<16;++r)e[n+r]=o[r];return e}return yn(o)}var vt=$o;import*as U from"os";var $e=O("OPENAI_LOGGER"),Ho="########",Bo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Vo(t,e){let n=e||process.cwd();if(!t)return k.join(n,"logs","openai");let o=t;return t==="~"||t.startsWith("~/")?o=k.join(U.homedir(),t.slice(1)):k.isAbsolute(t)||(o=k.resolve(n,t)),k.normalize(o)}function An(t){return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function jo(t){let e=t.split("#");if(e.length!==3)return;let[,n,o]=e;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function zo(t){if(t)return J(t)?An(t):An(jo(t))}function Wo(t){if(!t)return;let e=t.indexOf(Ho);if(e>0)return t.slice(0,e);if(Bo.test(t))return t;let n=t.split("#");if(n.length>=3&&n[0])return n[0]}function qo(t){let e=t?.trim(),n=Wo(e);return!e&&!n?null:{...e?{promptId:e}:{},...n?{sessionId:n}:{}}}var ue=class{logDir;initialized=!1;constructor(e,n){this.logDir=Vo(e,n)}async initialize(){if(!this.initialized)try{await Ke.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(e){throw $e.error("Failed to initialize OpenAI logger:",e),new Error(`Failed to initialize OpenAI logger: ${e}`)}}async logInteraction(e,n,o,r){this.initialized||await this.initialize();let i=new Date().toISOString().replace(/:/g,"-"),s=vt().slice(0,8),a=zo(r),l=a?`openai-${i}-${s}-${a}.json`:`openai-${i}-${s}.json`,c=k.join(this.logDir,l),u={timestamp:new Date().toISOString(),request:e,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:qo(r),system:{hostname:U.hostname(),platform:U.platform(),release:U.release(),nodeVersion:process.version}};try{return await Ke.writeFile(c,JSON.stringify(u,null,2),"utf-8"),c}catch(p){throw $e.error("Failed to write OpenAI log file:",p),new Error(`Failed to write OpenAI log file: ${p}`)}}async getLogFiles(e){this.initialized||await this.initialize();try{let o=(await Ke.readdir(this.logDir)).filter(r=>r.startsWith("openai-")&&r.endsWith(".json")).map(r=>k.join(this.logDir,r)).sort().reverse();return e?o.slice(0,e):o}catch(n){return n.code==="ENOENT"?[]:($e.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(e){try{let n=await Ke.readFile(e,"utf-8");return JSON.parse(n)}catch(n){throw $e.error(`Failed to read log file ${e}:`,n),new Error(`Failed to read log file: ${n}`)}}},Gs=new ue;f();f();Y();ho();f();Y();var Sn=go(mo(),1);import{createHash as Yo}from"node:crypto";var Z="matilda.telemetry.traceparent",He="matilda.telemetry.tracestate",Jo="matilda-code.daemon.request",En="matilda-code.daemon.bridge",Xo="matilda-code.daemon.error";function Qo(t){return t instanceof Error?t.message:String(t)}function Zo(t){return t instanceof Error?t.name||"Error":typeof t}var er="0".repeat(32),tr="0".repeat(16);function nr(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e=t;if(!(Z in e)&&!(He in e))return{...e};let n={...e};return delete n[Z],delete n[He],n}function or(t){return Yo("sha256").update(t).digest("hex").slice(0,16)}async function bt(t,e,n,o={}){if(!se())return await n(void 0);let r=o.autoOkOnSuccess??!0;return await v.getTracer(M).startActiveSpan(t,{kind:lt.INTERNAL,attributes:e},async s=>{try{let a=await n(s);return r&&s.setStatus({code:ie.OK}),a}catch(a){throw _n(s,a),a}finally{s.end()}})}async function rr(t,e){return await bt(Jo,{"http.request.method":t.method,"http.route":t.route,"matilda-code.daemon.operation":"http_request",...t.workspaceHash?{"matilda-code.workspace.hash":t.workspaceHash}:{},...t.sessionId?{"session.id":t.sessionId}:{},...t.clientId?{"matilda-code.client_id":t.clientId}:{},...t.permissionRequestId?{"matilda-code.daemon.permission.request_id":t.permissionRequestId}:{}},e,{autoOkOnSuccess:!1})}async function Mn(t,e,n){return await bt(En,{"matilda-code.daemon.operation":t,...e},async()=>await n())}function ir(t,e){try{t?.setAttribute("http.response.status_code",e)}catch{}}function sr(t,e){try{v.getSpan(_.active())?.setAttribute(t,e)}catch{}}function _n(t,e,n={}){let o=t??v.getSpan(_.active());if(o)try{let r=ut(Qo(e));o.recordException(e instanceof Error?e:new Error(r)),o.setAttributes({"error.type":Zo(e),"error.message":r,...n}),o.setStatus({code:ie.ERROR,message:r})}catch{}}function ar(t,e={},n){if(se())try{Sn.logs.getLogger(M).emit({body:t,timestamp:new Date,attributes:{"event.name":n?.eventName??Xo,...e},...n?.severityNumber!=null?{severityNumber:n.severityNumber}:{}})}catch{}}function Rn(){return{context:_.active()}}async function vn(t,e){let n=t&&typeof t=="object"&&"context"in t&&t.context?t.context:void 0;return n?await _.with(n,e):await e()}function bn(t){let e=t._meta,n=nr(e);try{let o=jt();o&&(n[Z]=ct(o))}catch{}return!e&&!n[Z]?t:{...t,_meta:n}}function lr(t){let e=t?._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,o=n[Z];if(typeof o!="string"||o.length===0)return;let r={traceparent:o},i=n[He];typeof i=="string"&&i.length>0&&(r.tracestate=i);let s=Vt.extract(at,r);if(v.getSpanContext(s))return s;let a=o.split("-"),l=a[1],c=a[2],u=a[3];if(!(a[0]!=="00"||!l?.match(/^[0-9a-f]{32}$/)||!c?.match(/^[0-9a-f]{16}$/)||!u?.match(/^[0-9a-f]{2}$/)||l===er||c===tr))return v.setSpan(at,v.wrapSpanContext({traceId:l,spanId:c,traceFlags:Number.parseInt(u,16),isRemote:!0}))}function cr(){return{captureContext:Rn,runWithContext:vn,withSpan:Mn,event(t,e){if(se())try{let n=v.getSpan(_.active());if(n){n.addEvent(t,e);return}let o=v.getTracer(M).startSpan(En,{kind:lt.INTERNAL,attributes:{"event.name":t,"matilda-code.daemon.operation":`event.${t}`,...e}});o.addEvent(t,e),o.setStatus({code:ie.OK}),o.end()}catch{}},injectPromptContext:bn}}f();Y();var dr=`${M}.daemon.http.request.count`,ur=`${M}.daemon.http.request.duration`,pr=`${M}.daemon.session.active`,fr=`${M}.daemon.session.lifecycle`,gr=`${M}.daemon.channel.lifecycle`,mr=`${M}.daemon.prompt.queue_wait`,hr=`${M}.daemon.prompt.duration`,Cr=`${M}.daemon.bridge.error.count`,Tr=`${M}.daemon.cancel.count`,yr=`${M}.daemon.sse.active`,Ar=`${M}.daemon.process.heap_used`,Sr=new Set(["SessionNotFoundError","WorkspaceMismatchError","InvalidClientIdError","SessionLimitExceededError","RestoreInProgressError","InvalidSessionScopeError","TrustGateError","WorkspaceInitConflictError","WorkspaceInitPathEscapeError","WorkspaceInitSymlinkError","WorkspaceInitRaceError","McpServerNotFoundError","McpServerRestartFailedError","PromptDeadlineExceededError","InvalidSessionMetadataError","SubscriberLimitExceededError","BridgeChannelClosedError","BridgeTimeoutError","PermissionForbiddenError"]),D=!1,kn,In,On,wn,Pn,Dn,Ln,Un;function Er(t){let e=t instanceof Error?t.name:typeof t;return Sr.has(e)?e:"unknown"}function Mr(){if(D)return;let t=dt();t&&(kn=t.createCounter(dr,{description:"Daemon HTTP request count by route and status class.",valueType:R.INT}),In=t.createHistogram(ur,{description:"Daemon HTTP request duration in milliseconds.",unit:"ms",valueType:R.DOUBLE,advice:{explicitBucketBoundaries:[1,2,5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4]}}),On=t.createCounter(fr,{description:"Daemon session lifecycle events (spawn, close, die).",valueType:R.INT}),wn=t.createCounter(gr,{description:"Daemon ACP channel lifecycle events (spawn, exit).",valueType:R.INT}),Pn=t.createHistogram(mr,{description:"Time a prompt waited in the per-session FIFO queue.",unit:"ms",valueType:R.DOUBLE,advice:{explicitBucketBoundaries:[1,5,10,50,100,500,1e3,5e3,1e4,3e4,6e4]}}),Dn=t.createHistogram(hr,{description:"End-to-end prompt duration from dispatch to completion.",unit:"ms",valueType:R.DOUBLE,advice:{explicitBucketBoundaries:[100,500,1e3,2500,5e3,1e4,3e4,6e4,12e4,3e5,6e5]}}),Ln=t.createCounter(Cr,{description:"Daemon bridge error count by normalized error type.",valueType:R.INT}),Un=t.createCounter(Tr,{description:"Daemon cancel request count.",valueType:R.INT}),D=!0)}var xn=!1;function _r(t){if(xn)return;let e=dt();e&&(e.createObservableGauge(pr,{description:"Current number of active daemon sessions.",valueType:R.INT}).addCallback(n=>{try{n.observe(t.sessionCount())}catch{}}),e.createObservableGauge(yr,{description:"Current number of active SSE connections.",valueType:R.INT}).addCallback(n=>{try{n.observe(t.sseCount())}catch{}}),e.createObservableGauge(Ar,{description:"Daemon process heap memory usage in bytes.",unit:"bytes",valueType:R.INT}).addCallback(n=>{try{n.observe(t.heapUsed())}catch{}}),xn=!0)}function Rr(t,e,n){if(!D)return;let o=`${Math.floor(n/100)}xx`;kn?.add(1,{route:e,status_class:o}),In?.record(t,{route:e})}function vr(t){D&&On?.add(1,{action:t})}function br(t,e){D&&wn?.add(1,{action:t,...e!=null?{expected:e}:{}})}function xr(t){D&&Pn?.record(t)}function kr(t){D&&Dn?.record(t)}function Ir(t){D&&Ln?.add(1,{error_type:Er(t)})}function Or(){D&&Un?.add(1)}f();Y();import*as G from"node:fs";import*as rt from"node:path";f();f();f();f();Y();f();import{AsyncLocalStorage as wr}from"node:async_hooks";var Nn=new wr;f();function Fn(t){let e=t.candidates?.[0]?.content?.parts;return!e||e.length===0?!1:e.some(Pr)}function Pr(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.text=="string"&&e.text.length>0||e.functionCall!==void 0||e.inlineData!==void 0||e.executableCode!==void 0||e.thought===!0}function Gn(){let t=Jt.getStore();return{attempt:t?.attempt??1,requestSetupMs:t?.requestSetupMs,retryTotalDelayMs:t?.retryTotalDelayMs}}var j=O("LOGGING_CONTENT_GENERATOR"),Dr=4096,Kn="...[truncated]",Lr=Dr-Kn.length,pe=class{constructor(e,n,o){this.wrapped=e;this.config=n;this.modalities=o.modalities,this.splitToolMedia=o.splitToolMedia,this.generatorAuthType=o.authType,o.enableOpenAILogging&&(this.openaiLogger=new ue(o.openAILoggingDir,n.getWorkingDir()),this.schemaCompliance=o.schemaCompliance)}openaiLogger;schemaCompliance;modalities;splitToolMedia;generatorAuthType;getWrapped(){return this.wrapped}logApiRequest(e,n,o){let r=JSON.stringify(e);pt(this.config,new mt(n,o,r,L.getStore()))}_logApiResponse(e,n,o,r,i,s){gt(this.config,new Ct(e,o,n,r,this.generatorAuthType,i,s,L.getStore()))}_logApiError(e,n,o,r,i){let s=Bt(o),a=re(o),l=o?.requestID||o?.request_id||e,c=oe(o);ft(this.config,new ht({responseId:l,model:r,durationMs:n,promptId:i,authType:this.generatorAuthType,errorMessage:s,errorType:a,statusCode:c,subagentName:L.getStore()}))}safelyLogApiError(e,n,o,r,i){try{this._logApiError(e,n,o,r,i)}catch(s){j.warn("Failed to log API error:",s)}}safelyLogApiResponse(e,n,o,r,i,s){try{this._logApiResponse(e,n,o,r,i,s)}catch(a){j.warn("Failed to log API response:",a)}}getClientVisibleModelId(e,n){return("isManagedMatildaModel"in this.config&&typeof this.config.isManagedMatildaModel=="function"?this.config.isManagedMatildaModel(e):!1)&&"getPublicModelId"in this.config&&typeof this.config.getPublicModelId=="function"?this.config.getPublicModelId(e):n||e}async generateContent(e,n){let o=Gn(),r=ke(e.model,n);try{r.setAttribute("llm_request.stream",!1)}catch{}let i=v.setSpan(_.active(),r),s=Date.now(),a=J(n),l=this.startCaptureSession();try{Tt.recordGenerateContentRequest(e,{stream:!1,source:"generateContent"}),a||(ve(this.config,r,e.config?.systemInstruction),be(this.config,r,e.config?.tools));let c=await _.with(i,async()=>{a||this.logApiRequest(this.toContents(e.contents),e.model,n);let u=await l.wrap(()=>this.wrapped.generateContent(e,n)),p=Date.now()-s,d=a?void 0:this.extractResponseText(u);a||xe(this.config,r,d),this.safelyLogApiResponse(u.responseId??"",p,this.getClientVisibleModelId(e.model,u.modelVersion),n,u.usageMetadata,d);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),u,void 0,n)}catch(h){j.warn("Failed to log OpenAI interaction:",h)}return u});return H(r,{success:!0,inputTokens:c.usageMetadata?.promptTokenCount,outputTokens:c.usageMetadata?.candidatesTokenCount,cachedInputTokens:c.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-s,responseId:c.responseId||void 0,finishReason:c.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:c.usageMetadata?.thoughtsTokenCount,subagentName:L.getStore()||void 0,...o}),c}catch(c){let u=Date.now()-s,p=e.config?.abortSignal?.aborted??!1;throw H(r,{success:!1,durationMs:u,error:p?Oe:Ie,errorType:re(c),errorStatusCode:oe(c),subagentName:L.getStore()||void 0,...o}),await _.with(i,async()=>{this.safelyLogApiError("",u,c,this.getClientVisibleModelId(e.model),n);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,c,n)}catch(d){j.warn("Failed to log OpenAI interaction:",d)}}),c}}async generateContentStream(e,n){let o=Gn(),r=ke(e.model,n);try{r.setAttribute("llm_request.stream",!0)}catch{}let i=v.setSpan(_.active(),r),s=Date.now(),a=J(n),l=this.startCaptureSession(),c;try{Tt.recordGenerateContentRequest(e,{stream:!0,source:"generateContentStream"}),a||(ve(this.config,r,e.config?.systemInstruction),be(this.config,r,e.config?.tools)),c=await _.with(i,async()=>(a||this.logApiRequest(this.toContents(e.contents),e.model,n),l.wrap(()=>this.wrapped.generateContentStream(e,n))))}catch(p){let d=Date.now()-s;_.with(i,()=>this.safelyLogApiError("",d,p,e.model,n));let h=e.config?.abortSignal?.aborted??!1;H(r,{success:!1,durationMs:d,error:h?Oe:Ie,errorType:re(p),errorStatusCode:oe(p),subagentName:L.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,p,n)}catch(m){j.warn("Failed to log OpenAI interaction:",m)}throw p}let u;if(this.openaiLogger)try{u=await l.resolve(e)}catch(p){j.warn("Failed to resolve OpenAI request:",p)}return _.with(i,()=>this.loggingStreamWrapper(c,s,n,e.model,u,r,i,e.config?.abortSignal,o))}startCaptureSession(){let e,n=!this.openaiLogger;return{wrap:o=>n?o():Nn.run(r=>{e=r},o),resolve:async o=>this.openaiLogger?e??await this.buildOpenAIRequestForLogging(o):void 0}}async*loggingStreamWrapper(e,n,o,r,i,s,a,l,c){let u=J(o),p=!u||!!this.openaiLogger,d=[],h="",m="",g,C=!1,T,y,E=L.getStore(),b,K=!1,q=x=>a?_.with(a,x):x(),it=5*6e4,w,Kt=s?()=>{K||(w!==void 0&&clearTimeout(w),w=setTimeout(()=>{try{s.setAttribute("stream.timed_out",!0)}catch{}H(s,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:h||void 0,subagentName:E||void 0,...c}),K=!0},it),w.unref())}:void 0;Kt?.();try{for await(let I of e){!h&&I.responseId&&(h=I.responseId),!m&&I.modelVersion&&(m=I.modelVersion),p&&d.push(I),I.usageMetadata&&(g=I.usageMetadata);let Ht=I.candidates?.[0];Ht?.finishReason&&(T=Ht.finishReason),b===void 0&&Fn(I)&&(b=Date.now()-n),Kt?.(),yield I}w!==void 0&&(clearTimeout(w),w=void 0);let x=Date.now()-n,Me=p?this.consolidateGeminiResponsesForLogging(d):void 0,$t=u?void 0:this.extractResponseText(Me);K||(q(()=>this.safelyLogApiResponse(h,x,this.getClientVisibleModelId(r,m),o,g,$t)),!u&&s&&xe(this.config,s,$t),await q(()=>this.safelyLogOpenAIInteraction(i,Me,void 0,o)))}catch(x){if(C=!0,y=x,!K){let Me=Date.now()-n;q(()=>this.safelyLogApiError(h,Me,x,this.getClientVisibleModelId(r,m),o)),await q(()=>this.safelyLogOpenAIInteraction(i,void 0,x,o))}throw x}finally{if(w!==void 0&&clearTimeout(w),s&&!K){let x=l?.aborted??!1;H(s,{success:!C,inputTokens:g?.promptTokenCount,outputTokens:g?.candidatesTokenCount,cachedInputTokens:g?.cachedContentTokenCount,ttftMs:b,durationMs:Date.now()-n,error:C?x?Oe:Ie:void 0,responseId:h||void 0,finishReason:T,thoughtsTokenCount:g?.thoughtsTokenCount,subagentName:E||void 0,errorType:y?re(y):void 0,errorStatusCode:y?oe(y):void 0,...c})}}}async buildOpenAIRequestForLogging(e){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(e.model),o=Ne.convertGeminiRequestToOpenAI(e,n,{cleanOrphanToolCalls:!1}),r={model:e.model,messages:o};return e.config?.tools&&(r.tools=await Ne.convertGeminiToolsToOpenAI(e.config.tools,this.schemaCompliance??"auto")),e.config?.temperature!==void 0&&(r.temperature=e.config.temperature),e.config?.topP!==void 0&&(r.top_p=e.config.topP),e.config?.maxOutputTokens!==void 0&&(r.max_tokens=e.config.maxOutputTokens),e.config?.presencePenalty!==void 0&&(r.presence_penalty=e.config.presencePenalty),e.config?.frequencyPenalty!==void 0&&(r.frequency_penalty=e.config.frequencyPenalty),r}createLoggingRequestContext(e){return{model:e,modalities:this.modalities??{},splitToolMedia:this.splitToolMedia??!0,startTime:0}}async logOpenAIInteraction(e,n,o,r){if(!this.openaiLogger||!e)return;let i=n?this.convertGeminiResponseToOpenAIForLogging(n,e):void 0;await this.openaiLogger.logInteraction(e,i,o instanceof Error?o:o?new Error(String(o)):void 0,r)}async safelyLogOpenAIInteraction(e,n,o,r){try{await this.logOpenAIInteraction(e,n,o,r)}catch(i){j.warn("Failed to log OpenAI interaction:",i)}}convertGeminiResponseToOpenAIForLogging(e,n){let o=new $;return Object.assign(o,e),o.modelVersion=this.getClientVisibleModelId(n.model,e.modelVersion),Ne.convertGeminiResponseToOpenAI(o,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(e){if(e.length===0)return;let n=new $,o=[],r=new Map,i,s;for(let c of e){c.usageMetadata&&(s=c.usageMetadata);let u=c.candidates?.[0];u?.finishReason&&(i=u.finishReason);let p=u?.content?.parts??[];for(let d of p){if(typeof d=="string"){o.push({text:d});continue}if("text"in d){d.text&&o.push({text:d.text,...d.thought?{thought:!0}:{},...d.thoughtSignature?{thoughtSignature:d.thoughtSignature}:{}});continue}if("functionCall"in d&&d.functionCall){let h=d.functionCall.id||d.functionCall.name||"tool_call",m=r.get(h),g={functionCall:d.functionCall};m!==void 0?o[m]=g:(r.set(h,o.length),o.push(g));continue}if("functionResponse"in d&&d.functionResponse){o.push({functionResponse:d.functionResponse});continue}o.push(d)}}let a=e[e.length-1],l=a.candidates?.[0];return n.responseId=a.responseId,n.createTime=a.createTime,n.modelVersion=a.modelVersion,n.promptFeedback=a.promptFeedback,n.usageMetadata=s,n.candidates=[{content:{role:l?.content?.role||"model",parts:o},...i?{finishReason:i}:{},index:0,safetyRatings:l?.safetyRatings||[]}],n}extractResponseText(e){let n=e?.candidates?.[0]?.content?.parts;if(!n?.length)return;let o="",r=!1,i=!1,s=a=>{if(r=!0,i)return;let l=Lr-o.length;if(a.length<=l){o+=a;return}o+=a.slice(0,Math.max(0,l)),i=!0};for(let a of n){if(typeof a=="string"){s(a);continue}"text"in a&&typeof a.text=="string"&&!("thought"in a&&a.thought)&&s(a.text)}if(r)return i?`${o}${Kn}`:o}async countTokens(e){return this.wrapped.countTokens(e)}async embedContent(e){return this.wrapped.embedContent(e)}useSummarizedThinking(){return this.wrapped.useSummarizedThinking()}toContents(e){return Array.isArray(e)?e.map(n=>this.toContent(n)):[this.toContent(e)]}toContent(e){return Array.isArray(e)?{role:"user",parts:this.toParts(e)}:typeof e=="string"?{role:"user",parts:[{text:e}]}:"parts"in e?{...e,parts:e.parts?this.toParts(e.parts.filter(n=>n!=null)):[]}:{role:"user",parts:[this.toPart(e)]}}toParts(e){return e.map(n=>this.toPart(n))}toPart(e){if(typeof e=="string")return{text:e};if("thought"in e&&e.thought){let n=`[Thought: ${e.thought}]`,o={...e};if(delete o.thought,"functionCall"in o||"functionResponse"in o||"inlineData"in o||"fileData"in o)return o;let i=o.text,s=i?String(i):"",a=s?`${s}
|
|
8
|
+
${n}`:n;return{...o,text:a}}return e}};f();function $n(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 Hn(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 N=class extends Error{constructor(e){super(e),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},Be=class extends N{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.`))}},Ve=class extends N{code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},je=class extends N{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}'.`)}},ze=class extends N{code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}},We=class extends N{code="MISSING_BASE_URL";constructor(e){super(`Missing baseUrl for modelProviders model '${e.model||"(unknown)"}'. Configure modelProviders.${e.authType||"(unknown)"}[].baseUrl.`)}},qe=class extends N{code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};f();import Fr from"node:process";f();var Bn={image:!0,pdf:!0,audio:!0,video:!0},Ur=[[/^gemini-3/,Bn],[/^gemini-/,Bn],[/^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 fe(t){let e=Zt(t);for(let[n,o]of Ur)if(n.test(e))return{...o};return{}}f();var Ye="$runtime|";function wa(t){let e=t;for(;e.startsWith(Ye);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}f();f();f();var Je=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],Vn=["model","apiKey","apiKeyEnvKey","baseUrl"],Xe=[...Vn,...Je],Na={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:[]}},Fa={openai:Qt,"matilda-oauth":B},Qe=[{id:"coder-model",name:"coder-model",description:"Matilda 3.6 Plus \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:!0}}],Ga=Qe.map(t=>t.id);var xt=O("MODEL_REGISTRY");function jn(t){if(Object.values(F).includes(t))return t}function Nr(t){return/^minimax-m3/i.test(t.trim().toLowerCase())}function zn(t,e){return e?`${t}\0${e}`:t}var Ze=class{modelsByAuthType;getDefaultBaseUrl(e){switch(e){case"matilda-oauth":return"DYNAMIC_MATILDA_OAUTH_BASE_URL";case"openai":return qt;default:return""}}constructor(e){if(this.modelsByAuthType=new Map,this.registerAuthTypeModels("matilda-oauth",Qe),e)for(let[n,o]of Object.entries(e)){let r=jn(n);if(!r){xt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(F).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}registerAuthTypeModels(e,n){let o=new Map;for(let r of n){let i=zn(r.id,r.baseUrl);if(o.has(i)){xt.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??ae(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(zn(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,B);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||Nr(e.id))&&(o.modalities=fe(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=jn(n);if(!r){xt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(F).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}};var Wn=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 Ze(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||B}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(F),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===yt&&e?.envKey===en&&e?.baseUrl===nn&&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)?yt:e}getModelDisplayName(e){return this.isManagedMatildaModel(e)?tn:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,e)?.name??e:e}async setModel(e,n){if(this.currentAuthType==="matilda-oauth"&&e===B){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=fe(e),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=ae(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`${Ye}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(Ye))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 Je)!(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 Xe)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=Fr.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 Je)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=ae(e.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=fe(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,g=m?this._generationConfig.apiKey:void 0,C=m&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,T=this.generationConfigSources.baseUrl,y=m&&!!this._generationConfig.baseUrl&&(T?.kind==="cli"||T?.kind==="env"||T?.kind==="settings"),E=y?this._generationConfig.baseUrl:void 0,b=y&&T?{...T}:void 0;this.applyResolvedModelDefaults(i),m&&!this._generationConfig.apiKey&&g&&(this._generationConfig.apiKey=g,C&&(this.generationConfigSources.apiKey=C)),E&&(this._generationConfig.baseUrl=E,b&&(this.generationConfigSources.baseUrl=b)),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)}};f();import{readFileSync as ti}from"node:fs";import{join as ni}from"node:path";f();f();import{randomBytes as Gr,createHash as Kr}from"node:crypto";function qn(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function kt(){let t=Gr(32).toString("base64url"),e=Kr("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function ge(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 It(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!qn(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}}f();import{promises as et,openSync as $r,closeSync as Hr,unlinkSync as Yn,statSync as Br}from"node:fs";import{dirname as Vr}from"node:path";var jr=1e4,zr=3e4,Wr=50;function Ot(t){let e=async()=>{try{let r=await et.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 et.mkdir(Vr(t),{recursive:!0}),await et.writeFile(t,JSON.stringify(r,null,2),{mode:384}),await et.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:qr(`${t}.lock`)}}function qr(t){let e=Promise.resolve();return n=>{let o=e.then(async()=>{await Yr(t);try{return await n()}finally{Jr(t)}});return e=o.then(()=>{},()=>{}),o}}async function Yr(t){let e=Date.now()+jr;for(;;)try{Hr($r(t,"wx"));return}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Br(t).mtimeMs>zr){Yn(t);continue}}catch{continue}if(Date.now()>e)throw new Error(`Timed out acquiring credential lock at ${t}`);await Xr(Wr)}}function Jr(t){try{Yn(t)}catch{}}function Xr(t){return new Promise(e=>setTimeout(e,t))}f();var ee=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function wt(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 ee("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&&Qr(h)==="invalid_grant"?(await t.store.remove(e),new ee):new Error(`Token refresh failed (${u.status})`)}let p=await u.json(),d=ge(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 ee("Not signed in.");return!l?.forceRefresh&&s(c)?c.accessToken:(r||(r=a(c).finally(()=>{r=null})),r)}}}function Qr(t){try{return JSON.parse(t).error}catch{return}}f();import{createServer as Zr}from"node:http";import{randomBytes as ei}from"node:crypto";async function Pt(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}=kt(),r=ei(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,g)=>{a=m,l=g});c.catch(()=>{});let u=Zr((m,g)=>{let C=new URL(m.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){g.writeHead(404).end();return}let T=C.searchParams.get("error"),y=C.searchParams.get("state"),E=C.searchParams.get("code");if(T){Jn(g,s,()=>l(new Error(`OAuth error: ${T}`)));return}if(y!==r){g.writeHead(400).end("State mismatch"),l(new Error("OAuth state mismatch"));return}if(!E){g.writeHead(400).end("Missing authorization code");return}Jn(g,s,()=>a(E))}),p=await new Promise((m,g)=>{u.once("error",g),u.listen(t.transport.port??0,"127.0.0.1",()=>{m(u.address().port)})}),d=setTimeout(()=>l(new Error("Login timed out \u2014 no callback received")),i),h=()=>l(new Error("Login aborted"));t.signal?.addEventListener("abort",h,{once:!0});try{let m=`http://127.0.0.1:${p}/callback`,g=new URL(t.metadata.authorization_endpoint);g.searchParams.set("client_id",t.clientId),g.searchParams.set("response_type","code"),g.searchParams.set("redirect_uri",m),g.searchParams.set("code_challenge",o),g.searchParams.set("code_challenge_method","S256"),g.searchParams.set("state",r),g.searchParams.set("scope",t.scope??"openid offline_access");let C=g.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 b=await y.text().catch(()=>"");throw new Error(`Token exchange failed (${y.status}): ${b}`)}let E=ge(await y.json());return e({type:"state",status:"authenticated"}),E}catch(m){throw e({type:"state",status:"error"}),m}finally{clearTimeout(d),t.signal?.removeEventListener("abort",h),u.close()}}function Jn(t,e,n){t.writeHead(302,{location:e}).end(n)}var me="matilda-code",Xn="matilda-desktop",he="MATILDA_API_KEY",oi="openid profile email offline_access matilda:code",ri="matilda";function Ce(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function Qn(){return ni(_e.getGlobalMatildaDir(),"matilda-auth.json")}function tt(){return Ot(Qn())}function ii(t){return t==="desktop"}function Te(t){return t?.clientId?t.clientId:ii(t?.channel)?Xn:me}function ne(t){return`matilda:${t}`}function nt(t){return`${ne(t)}:refresh-rejected`}function ye(t){return t===me?[ne(t),ri]:[ne(t)]}function si(){try{let t=ti(Qn(),"utf8");return JSON.parse(t)}catch{return{}}}function Dt(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 ai(t,e){return Ce(t)===Ce(e)}function li(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 ci(t,e){let n=li(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 It(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 z(t){try{let e=si(),n=Te(t);for(let o of ye(n)){let r=Dt(e[o]);if(r)return r}return null}catch{return null}}async function di(t){let e=Te(t),n=tt().store;for(let o of ye(e))await n.remove(o);await n.set(nt(e),"1"),delete process.env[he]}function ui(t){return t instanceof Error?t.code==="invalid_grant"||t.name==="InvalidGrantError"?!0:t.message==="Token refresh failed (401)":!1}function te(t){Lt({authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:t.occurrenceCount},{baseUrl:t.baseUrl,token:t.token}).catch(()=>{})}async function pi(t,e){let n=Te(e),o=tt().store;await o.set(ne(n),JSON.stringify(t)),await o.remove(nt(n));for(let r of ye(n))r!==ne(n)&&await o.remove(r);process.env[he]=t.accessToken}async function fi(t){let e=Te(t),n=tt().store;for(let o of ye(e))await n.remove(o);await n.remove(nt(e)),delete process.env[he]}function $l(t){let e=z(t);return e?{authenticated:!0,userId:e.userId,email:e.email,displayName:e.displayName,baseUrl:e.baseUrl,accessTokenExpiresAt:e.accessTokenExpiresAt}:{authenticated:!1}}async function Hl(t){let e={channel:t?.channel,clientId:t?.clientId},n=z(e);if(n?.accessToken){let o=Ce(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 fi(e)}async function Ut(t){let e=Te(t),n=ne(e),o=z({channel:t?.channel,clientId:e});if(!o||t?.baseUrl&&!ai(o.baseUrl,t.baseUrl))return t?.fallbackAccessToken??process.env[he]??"";let r=Ce(o.baseUrl),i=await Zn(r),{store:s,lock:a}=tt(),l=gi(s,a,i.token_endpoint,o.baseUrl,e,n,t?.signal),c=e===me&&(!!t?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=3e5),u;try{u=await l.getAccessToken({forceRefresh:t?.forceRefresh})}catch(p){throw c&&te({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"}),e===Xn&&ui(p)&&await di({channel:t?.channel,clientId:e}),p}return c&&te({baseUrl:o.baseUrl,token:u,authStage:"refresh",authOutcome:"succeeded"}),process.env[he]=u,u}async function Bl(t){await Ut(t);let e=z(t);if(!e)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return e}function gi(t,e,n,o,r,i,s){let a=ye(r);return wt({tokenEndpoint:n,clientId:r,store:{get:async u=>{let p=u===i?a:[u],d=null;for(let m of p)if(d=Dt(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=Dt(await t.get(C));if(T){m=T;break}}let g={...m,accessToken:d.accessToken,accessTokenExpiresAt:d.expiresAt,refreshToken:d.refreshToken??m.refreshToken??"",baseUrl:m.baseUrl??o};await t.set(i,JSON.stringify(g)),await t.remove(nt(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 mi(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&on()}async function Vl(t){let e=Ce(t.baseUrl),n=await Zn(e),o="",r=0,i=0,s={},a=p=>{s[p]=(s[p]??0)+1},l=p=>(r+=1,Pt({metadata:n,clientId:me,scope:p,transport:{kind:"loopback",successRedirect:`${e}/api/auth/oauth/success?client_id=${encodeURIComponent(me)}`},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||!mi()){a("skipped");return}try{let{default:h}=await import("./open-QQ7FWG4A.js");(await h(d)).once("error",()=>{}),a("succeeded")}catch{a("failed")}}})),c;try{c=await l(oi)}catch(p){if(p instanceof Error&&p.message.includes("invalid_scope"))c=await l("openid offline_access");else throw p}let u=ci(c,t.baseUrl);await pi(u),te({baseUrl:t.baseUrl,token:u.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:r});for(let[p,d]of Object.entries(s))te({baseUrl:t.baseUrl,token:u.accessToken,authStage:"browser_opened",authOutcome:p,occurrenceCount:d});return i>0&&te({baseUrl:t.baseUrl,token:u.accessToken,authStage:"callback_received",authOutcome:"succeeded",occurrenceCount:i}),te({baseUrl:t.baseUrl,token:u.accessToken,authStage:"token_persisted",authOutcome:"succeeded"}),{...u,authorizeUrl:o}}var F=(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))(F||{}),hi="MATILDA_AGENT_SDK",ot="MATILDA_API_KEY";function Ci(t,e){if(t.apiKey||t.apiKeyEnvKey!==ot)return;let n=z({channel:e});n?.accessToken&&(t.apiKey=n.accessToken,process.env[ot]=n.accessToken)}async function Ti(t,e){if(t.apiKeyEnvKey!==ot)return;let n=z({channel:e});if(!n?.accessToken)return;let o=await Ut({baseUrl:t.baseUrl,fallbackAccessToken:n.accessToken,channel:e});o&&(t.apiKey=o,process.env[ot]=o)}function yi(t){return t.matildaAgentSdk===!0||process.env[hi]==="1"}function Nt(t,e,n){t[e]=n}function Ai(t,e){return t?.[e]}function Si(t,e,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:e,proxy:t?.getProxy()};Nt(i,"authType",{kind:"computed",detail:"provided by caller"}),t?.getProxy()&&Nt(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=u=>Ai(o,u)??{kind:"unknown"};for(let u of Xe)n&&u in n&&!i[u]&&Nt(i,u,l(u));Ci(a,t.getChannel());let c=to(a,s);if(!c.valid)throw new Error(c.errors.map(u=>u.message).join(`
|
|
9
|
+
`));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 Be(t.authType,t.model,t.apiKeyEnvKey));else{let o=t.apiKeyEnvKey||$n(t.authType);n.push(new je({authType:t.authType,model:t.model,baseUrl:t.baseUrl,envKey:o}))}if(!t.model)if(e)n.push(new Ve(t.authType));else{let o=Hn(t.authType);n.push(new ze({authType:t.authType,envKey:o}))}return t.authType==="anthropic"&&!t.baseUrl&&(e?n.push(new We({authType:t.authType,model:t.model})):t.authType==="anthropic"&&n.push(new qe)),{valid:n.length===0,errors:n}}function Xl(t,e,n){return Si(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 Ql(t,e,n){await Ti(t,e.getChannel());let o=to(t,!1);if(!o.valid)throw new Error(o.errors.map(s=>s.message).join(`
|
|
10
|
+
`));let r=t.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai")if(yi(t)){let{createMatildaAgentContentGenerator:s}=await import("./matildaAgentContentGenerator-QZULEJRI.js");i=s(t,e)}else{let{createOpenAIContentGenerator:s}=await import("./openaiContentGenerator-PF2IFB3R.js");i=s(t,e)}else if(r==="matilda-oauth"){let{getMatildaOAuthClient:s}=await import("./matildaOAuth2-LKOMJUC6.js"),{MatildaContentGenerator:a}=await import("./matildaContentGenerator-EBSJ2MDP.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-5DLG2IS7.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
|
+
Please exit and restart Matilda to use the '${r}' provider.`,{cause:a}):s}return new pe(i,e,t)}var Ei=["x-matilda-reported-surface","x-matilda-reported-os","x-matilda-reported-architecture","x-matilda-reported-process","x-matilda-reported-sdk","x-matilda-reported-version","x-matilda-reported-release-channel"],Mi=new Set([...Ei,...Xt]),_i=new Set(["VSCode","ACP","SDK","CI"]),Ae="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",Ri="[A-Za-z][0-9A-Za-z-]{0,23}",vi="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",bi=new RegExp(`^${Ae}(?:-${Ri}(?:\\.${vi})+)?$`),xi=63,ki=new RegExp(`^${Ae}$`),Ii=new RegExp(`^${Ae}-preview\\.(?:0|[1-9]\\d{0,11})$`),Oi=new RegExp(`^${Ae}-canary\\.(?:0|[1-9]\\d{0,11})$`),wi=new RegExp(`^${Ae}-nightly\\.(?:0|[1-9]\\d{0,11})\\.[0-9A-Fa-f]{7,12}$`);function Pi(t){return t==="desktop"?"desktop":t===void 0||_i.has(t)?"code_cli":"unknown"}function Di(t){return t==="android"?"android":t==="darwin"?"macos":t==="win32"?"windows":t==="linux"?"linux":"unknown"}function Li(t){return t==="x64"?"x64":t==="arm64"?"arm64":"unknown"}function Ui(t){if(typeof t=="string"&&!(t.length>xi||!bi.test(t)))return t}function Ni(t){return t===void 0?"unknown":ki.test(t)?"stable":Ii.test(t)?"preview":Oi.test(t)?"canary":wi.test(t)?"nightly":"unknown"}function no(t,e=process.platform,n=process.arch){let o=t.getChannel?.(),r=Pi(o),i=Ui(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:t.getCliVersion?.()),s=Ni(i);return{"x-matilda-reported-surface":r,"x-matilda-reported-os":Di(e),"x-matilda-reported-architecture":Li(n),"x-matilda-reported-process":r==="desktop"?"matilda-desktop":o==="VSCode"?"matilda-vscode":r==="code_cli"?"matilda-code":"unknown",...i?{"x-matilda-reported-version":i}:{},"x-matilda-reported-release-channel":s}}function rc(t){return Mi.has(t.toLowerCase())}function Fi(t){let e=t??Yt;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 ic(t,e=t.apiKey){return t.authType==="matilda-oauth"?!0:t.authType==="openai"&&!!e&&Fi(t.baseUrl)}var Gi=3e3,Se=1,Ki=24*60*60*1e3,oo=20,ro=999,$i=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"]),Hi=new Set(["ENOTFOUND","EAI_AGAIN"]),Bi=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),Vi=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 zi(t){return`${new URL(t).origin}/api/client-events`}function Wi(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 Ft(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??Gi);try{let a=await r(zi(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(Wi(t)),signal:i.signal});return a.ok?!0:(Re.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`),!1)}catch{return!1}finally{clearTimeout(s)}}async function Lt(t,e){let n=typeof t.occurrenceCount=="number"&&Number.isFinite(t.occurrenceCount)?Math.max(1,Math.min(Math.floor(t.occurrenceCount),ro)):1;return Ft({eventType:"auth_funnel",authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:n},e)}function io(){try{let t=G.readFileSync(lo(),"utf8"),e=JSON.parse(t);return e.schemaVersion!==Se||!Array.isArray(e.failures)?void 0:{schemaVersion:Se,failures:e.failures.filter(qi)}}catch{return}}function qi(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 so(t){let e=lo();if(t.failures.length===0){try{G.rmSync(e,{force:!0})}catch{}return}try{G.mkdirSync(rt.dirname(e),{recursive:!0}),G.writeFileSync(e,`${JSON.stringify(t)}
|
|
12
|
+
`,"utf8")}catch{}}function ao(t,e){return t.filter(n=>e-n.lastObservedAtMs<=Ki).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-oo)}function Yi(t){let e=no(t);return{reportedSurface:e["x-matilda-reported-surface"]??"unknown",reportedOs:e["x-matilda-reported-os"]??"unknown",reportedArchitecture:e["x-matilda-reported-architecture"]??"unknown",reportedProcess:e["x-matilda-reported-process"]??"unknown",reportedVersion:e["x-matilda-reported-version"],reportedReleaseChannel:e["x-matilda-reported-release-channel"]??"unknown"}}function Ji(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 Xi(t){if(!(!t||typeof t!="object"))for(let e of["status","statusCode"]){let n=t[e];if(typeof n=="number")return n}}function Qi(t,e){let n=Ji(t);if(n&&$i.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&Hi.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&Bi.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&Vi.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=Xi(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 Zi(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 uc(t,e){let n=Yi(e.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=Qi(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=io()??{schemaVersion:Se,failures:[]},a=ao(s.failures,r),l=Zi(a,i);if(l>=0){let c=a[l];a[l]={...c,occurrenceCount:Math.min(c.occurrenceCount+1,ro),lastObservedAtMs:r}}else a.push(i);return so({schemaVersion:Se,failures:a.slice(-oo)}),!0}async function pc(t){let e=io();if(!e)return;let n=ao(e.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await Ft({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}}so({schemaVersion:Se,failures:o})}function lo(){return rt.join(_e.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var uo=(n=>(n.GCP="gcp",n.LOCAL="local",n))(uo||{}),Eu="local",Mu="http://localhost:4317";f();Y();var ts=new Set(["service.version","service.instance.id","session.id"]);function W(t,e){Re.warn(t),e?.push(t)}function po(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){W(`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{W(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,e),l=s}let c;try{c=decodeURIComponent(a)}catch{W(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${l}", using raw value`,e),c=a}n[l]=c}return n}function Gt(t,e,n){for(let o of ts)o in t&&(W(`${e} cannot override reserved key "${o}"; ignoring`,n),delete t[o]);return t}function fo(t,e){if(t==null)return{};if(typeof t!="object"||Array.isArray(t))return W("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){W("settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",e);continue}typeof r=="string"?n[i]=r:W(`settings.telemetry.resourceAttributes value for "${i}" must be a string (got ${typeof r}); ignoring`,e)}return n}function Ee(t){if(t!==void 0)return t==="true"||t==="1"}function co(t){if(t!==void 0){if(t==="local"||t==="local")return"local";if(t==="gcp"||t==="gcp")return"gcp"}}async function es(t){let e=t.argv??{},n=t.env??{},o=t.settings??{},r=e.telemetry??Ee(n.MATILDA_TELEMETRY_ENABLED)??o.enabled,i=e.telemetryTarget??n.MATILDA_TELEMETRY_TARGET??o.target,s=co(i);if(i!==void 0&&s===void 0)throw new st(`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(it=>it===l);if(l!==void 0&&c===void 0)throw new st(`Invalid telemetry OTLP protocol: ${String(l)}. Valid values are: grpc, http`);let u=e.telemetryLogPrompts??Ee(n.MATILDA_TELEMETRY_LOG_PROMPTS)??o.logPrompts,p=Ee(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,g=n.MATILDA_TELEMETRY_OTLP_METRICS_ENDPOINT??n.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT??o.otlpMetricsEndpoint,C=[],T=Gt(po(n.OTEL_RESOURCE_ATTRIBUTES,C),"OTEL_RESOURCE_ATTRIBUTES",C),y=Gt(fo(o.resourceAttributes,C),"settings.telemetry.resourceAttributes",C),E={...T,...y},b=n.OTEL_SERVICE_NAME?.trim();b&&(E["service.name"]=b);let K=Object.keys(E).length?E:void 0,q=Ee(n.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??o.metrics?.includeSessionId??!1;return{enabled:r,target:s,otlpEndpoint:a,otlpProtocol:c,otlpTracesEndpoint:h,otlpLogsEndpoint:m,otlpMetricsEndpoint:g,logPrompts:u,includeSensitiveSpanAttributes:p,outfile:d,resourceAttributes:K,metrics:{includeSessionId:q},resourceAttributeWarnings:C.length?C:void 0}}export{St as a,X as b,we as c,Co as d,To as e,gn as f,Ne as g,Nn as h,Vo as i,ue as j,Gs as k,Ee as l,co as m,es as n,Z as o,He as p,or as q,bt as r,rr as s,Mn as t,ir as u,sr as v,_n as w,ar as x,Rn as y,vn as z,bn as A,lr as B,cr as C,Mr as D,_r as E,Rr as F,vr as G,br as H,xr as I,kr as J,Ir as K,Or as L,no as M,rc as N,ic as O,Ft as P,Lt as Q,uc as R,pc as S,uo as T,Eu as U,Mu as V,fe as W,Ye as X,wa as Y,Je as Z,Na as _,Fa as $,Qe as aa,Ga as ba,zn as ca,Ze as da,Wn as ea,Qn as fa,z as ga,pi as ha,fi as ia,$l as ja,Hl as ka,Ut as la,Bl as ma,mi as na,Vl as oa,F as pa,Si as qa,to as ra,Xl as sa,Ql as ta};
|
|
13
13
|
/**
|
|
14
14
|
* @license
|
|
15
15
|
* Copyright 2026 Matilda Team
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{b as i}from"./chunk-GZPNIYVZ.js";i();import{AsyncLocalStorage as P}from"node:async_hooks";import{randomUUID as f}from"node:crypto";i();import{AsyncLocalStorage as E}from"node:async_hooks";var c=new E;var x="x-matilda-reported-operation-id",m="x-matilda-reported-attempt-purpose",A=[x,m],y=new Set(A),l=["answer","tool_followup","continuation","retry","compaction","unknown"],_=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,C=new Set(l),u=new P,O=new WeakSet;function R(){return f()}function s(t,e){let o=Object.freeze({operationId:t,attemptPurpose:e});return O.add(o),o}function g(t){return y.has(t.toLowerCase())}function a(){let t=u.getStore();return t&&O.has(t)?t:void 0}var T=class{activeOperationId;begin(e){return this.activeOperationId=R(),s(this.activeOperationId,e)}continue(e){let o=a()?.operationId??this.activeOperationId??R();return this.activeOperationId=o,s(o,e)}};function n(t,e){return u.run(t,e)}function v(t){u.enterWith(t)}function M(t,e){let o=a();return o?n(s(o.operationId,t),e):e()}function I(t,e){let o={next:(...r)=>n(t,()=>e.next(...r)),return:r=>n(t,()=>e.return(r)),throw:r=>n(t,()=>e.throw(r)),[Symbol.asyncIterator]:()=>o},p=Symbol.asyncDispose,d=p&&e[p];return p&&typeof d=="function"&&(o[p]=()=>n(t,()=>d.call(e))),o}function k(t,e){let o=a();return o?I(s(o.operationId,t),e):e}function Y(){let t=a();if(!t||!_.test(t.operationId))return{};let e=c.getStore()?.attempt,o=e!==void 0&&e>1?"retry":t.attemptPurpose;return C.has(o)?{[x]:t.operationId,[m]:o}:{}}export{c as a,x as b,m as c,A as d,l as e,g as f,a as g,T as h,n as i,v as j,M as k,I as l,k as m,Y as n};
|
|
4
|
+
/**
|
|
5
|
+
* @license
|
|
6
|
+
* Copyright 2026 Matilda Team
|
|
7
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
+
*/
|