@maincode-ai/matilda-code 0.22.1 → 0.22.2-nightly.20261108.6294d1bfb
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/README.md +1 -1
- package/chunks/agent-57XAQHVM.js +3 -0
- package/chunks/agent-headless-HAPKRYIE.js +3 -0
- package/chunks/{askUserQuestion-A46IDHKS.js → askUserQuestion-2VKCJUZN.js} +1 -1
- package/chunks/ca-3NRDXS7D.js +23 -0
- package/chunks/chunk-2NTXP5AZ.js +8 -0
- package/chunks/chunk-3BBYMSRF.js +2582 -0
- package/chunks/chunk-3I3FFJWY.js +80 -0
- package/chunks/{chunk-FI2FSW7J.js → chunk-4PVHNEU3.js} +1 -1
- package/chunks/chunk-5PYAMBM2.js +8 -0
- package/chunks/chunk-BJUD4NXI.js +56 -0
- package/chunks/chunk-BQDEPKIG.js +46 -0
- package/chunks/chunk-DZKI2CAC.js +3 -0
- package/chunks/{chunk-TDFF4ZGY.js → chunk-E2KMVG7F.js} +1 -1
- package/chunks/chunk-GSJK7SGP.js +121 -0
- package/chunks/chunk-HJK3NKAR.js +8 -0
- package/chunks/{chunk-ZABAV4XA.js → chunk-HRD7WD3P.js} +3 -3
- package/chunks/{chunk-CI5CVVGI.js → chunk-IXILJSRE.js} +56 -56
- package/chunks/chunk-LXLLH53T.js +10 -0
- package/chunks/chunk-MZ73LBEY.js +9 -0
- package/chunks/{chunk-UICLGQTV.js → chunk-OWEBLTAN.js} +1 -1
- package/chunks/chunk-OWVBDJ7E.js +9 -0
- package/chunks/chunk-PFXCFIHY.js +8 -0
- package/chunks/chunk-T4674TNM.js +12 -0
- package/chunks/{chunk-LONWTJOE.js → chunk-W45FOPLA.js} +8 -8
- package/chunks/chunk-WL27X35X.js +44 -0
- package/chunks/chunk-WUMI5YVV.js +13 -0
- package/chunks/chunk-XZJ4RV46.js +8 -0
- package/chunks/{chunk-GCMUSGTT.js → chunk-YN2SAMUR.js} +1 -1
- package/chunks/{chunk-KYNP66YS.js → chunk-ZT36XNDG.js} +10 -10
- package/chunks/{computer-use-V2DT2IKO.js → computer-use-UOCOK6SQ.js} +7 -7
- package/chunks/{cron-create-JINCFLKY.js → cron-create-62PNWR2P.js} +1 -1
- package/chunks/{cron-delete-RF6JLUAV.js → cron-delete-IYE6E33N.js} +1 -1
- package/chunks/{cron-list-VXLBAXZ3.js → cron-list-L2SVZRPY.js} +1 -1
- package/chunks/de-MINTIKBC.js +23 -0
- package/chunks/{edit-ZB4SONLT.js → edit-QLBVLVHY.js} +17 -17
- package/chunks/en-UXQJBGFG.js +23 -0
- package/chunks/{enter-worktree-CAFTW46C.js → enter-worktree-YAQ6HDVT.js} +1 -1
- package/chunks/{enterPlanMode-XSNXJJMC.js → enterPlanMode-EGI24N3P.js} +1 -1
- package/chunks/{exit-worktree-U37YLKJC.js → exit-worktree-3OPW3OAW.js} +1 -1
- package/chunks/{exitPlanMode-XKAZCVAV.js → exitPlanMode-RTFHVTCT.js} +4 -4
- package/chunks/fr-XRDTBTRU.js +23 -0
- package/chunks/{glob-LPIFPVGX.js → glob-JJXYCPDP.js} +1 -1
- package/chunks/{goal-tools-VAH424PW.js → goal-tools-NJF2SBXC.js} +1 -1
- package/chunks/grep-PQRV7OZR.js +22 -0
- package/chunks/ja-OYFHC7MP.js +23 -0
- package/chunks/keychain-token-storage-M4SAHQOZ.js +3 -0
- package/chunks/ls-OYI6LAAH.js +15 -0
- package/chunks/{lsp-H4EXPHFD.js → lsp-U52XKS3X.js} +1 -1
- package/chunks/mcp-client-6MW2KO57.js +3 -0
- package/chunks/monitor-TPB66N7V.js +32 -0
- package/chunks/notebook-edit-O45G2OS2.js +17 -0
- package/chunks/openaiContentGenerator-T2E7ARNR.js +52 -0
- package/chunks/pt-6DJAKXHE.js +23 -0
- package/chunks/read-file-2XDCTNU6.js +3 -0
- package/chunks/ripGrep-WB4PIZYI.js +3 -0
- package/chunks/ru-4UMYCMY6.js +23 -0
- package/chunks/scheduler-YG2LUC5E.js +8 -0
- package/chunks/{send-message-5XHDGHSN.js → send-message-EWM35CIV.js} +1 -1
- package/chunks/shell-UEHJRUPV.js +3 -0
- package/chunks/{skill-FCVSGCSN.js → skill-MGFDUWWX.js} +4 -4
- package/chunks/symbol-search-PFI76DKS.js +19 -0
- package/chunks/syntheticOutput-J7B556VM.js +3 -0
- package/chunks/task-create-DUMMTB5V.js +3 -0
- package/chunks/{task-detach-AUTU6C4G.js → task-detach-QYMWZUO6.js} +1 -1
- package/chunks/{task-list-U2WAGMM7.js → task-list-OXXHFYZR.js} +1 -1
- package/chunks/{task-stop-GN5WZ3IA.js → task-stop-IN4YP24W.js} +1 -1
- package/chunks/{task-update-26N2AUQT.js → task-update-CXGD6VP2.js} +1 -1
- package/chunks/{team-create-TN2KN27J.js → team-create-YEPFGLCA.js} +1 -1
- package/chunks/team-delete-C4XRGL2J.js +8 -0
- package/chunks/{todoWrite-JN3ZV5O2.js → todoWrite-DGBA6PPS.js} +1 -1
- package/chunks/tool-call-HNUF467C.js +3 -0
- package/chunks/tool-search-DN3B6IMF.js +26 -0
- package/chunks/{web-fetch-CVAOVOZM.js → web-fetch-YFXYV2CO.js} +1 -1
- package/chunks/{web-search-77CUPTFY.js → web-search-HUQRJF44.js} +3 -5
- package/chunks/{workflow-JNZRGHJ4.js → workflow-HJ5O2E7S.js} +2 -2
- package/chunks/write-file-RDLXOLHP.js +15 -0
- package/cli.js +477 -453
- package/locales/ca.js +6 -3
- package/locales/de.js +6 -3
- package/locales/en.js +36 -3
- package/locales/fr.js +6 -3
- package/locales/ja.js +6 -3
- package/locales/pt.js +6 -3
- package/locales/ru.js +6 -3
- package/npm-postinstall.js +2 -2
- package/package.json +2 -2
- package/chunks/agent-JDATO222.js +0 -3
- package/chunks/agent-headless-ZOFNY4CF.js +0 -3
- package/chunks/ca-JKEHLTNL.js +0 -23
- package/chunks/chunk-2LVAK6TV.js +0 -80
- package/chunks/chunk-5JCW6FH6.js +0 -8
- package/chunks/chunk-6RK6IJY5.js +0 -12
- package/chunks/chunk-7AEOFDY3.js +0 -8
- package/chunks/chunk-AEYNMLMW.js +0 -36
- package/chunks/chunk-DEN6RR3B.js +0 -3
- package/chunks/chunk-DUB7JMQV.js +0 -13
- package/chunks/chunk-HRCRNKY2.js +0 -8
- package/chunks/chunk-IV6PS6DB.js +0 -8
- package/chunks/chunk-QNXNECWR.js +0 -2602
- package/chunks/chunk-RH3AEZWO.js +0 -9
- package/chunks/chunk-SMTY6M3W.js +0 -10
- package/chunks/chunk-TKEFJ3O3.js +0 -9
- package/chunks/chunk-V2V3OF76.js +0 -56
- package/chunks/chunk-Y3SZK63U.js +0 -120
- package/chunks/chunk-ZSGBDQXU.js +0 -11
- package/chunks/de-GMGNR5CZ.js +0 -23
- package/chunks/en-3NQMLVKW.js +0 -23
- package/chunks/fr-WS3EBB36.js +0 -23
- package/chunks/grep-IF4GTD5A.js +0 -22
- package/chunks/ja-GBCDQ43R.js +0 -23
- package/chunks/keychain-token-storage-UTWIIKCK.js +0 -3
- package/chunks/ls-3EEHZY4W.js +0 -15
- package/chunks/mcp-client-EUPXG3VF.js +0 -3
- package/chunks/monitor-KBWRPPZ5.js +0 -32
- package/chunks/notebook-edit-K3KNR6DI.js +0 -17
- package/chunks/openaiContentGenerator-2NF5JGUC.js +0 -47
- package/chunks/pt-VID6J2CM.js +0 -23
- package/chunks/read-file-SRDZKBNS.js +0 -3
- package/chunks/ripGrep-675JNT4W.js +0 -3
- package/chunks/ru-EB6V6EAN.js +0 -23
- package/chunks/scheduler-O36AJTWS.js +0 -8
- package/chunks/shell-A7NRVDCY.js +0 -3
- package/chunks/symbol-search-ZM3HFCUV.js +0 -19
- package/chunks/syntheticOutput-OIPRFBVD.js +0 -3
- package/chunks/task-create-QP44DKH4.js +0 -3
- package/chunks/team-delete-XCKD5FBZ.js +0 -8
- package/chunks/tool-search-VPMEQKAS.js +0 -28
- package/chunks/write-file-FJCU2PYT.js +0 -15
package/chunks/chunk-Y3SZK63U.js
DELETED
|
@@ -1,120 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as _,d as ne}from"./chunk-225CZWD7.js";import{a as Wn,d as Hn,n as rt,o as Xt,p as Yn,q as _e,s as it}from"./chunk-DUB7JMQV.js";import{Aa as Wt,Ca as Ht,I as le,K as Qe,L as Ze,M as et,U as tt,V as oe,ha as nt,ia as ot,qa as q,qb as qt,rb as Jt,tb as Yt,ya as zt}from"./chunk-CI5CVVGI.js";import{O as Ye,Y as L,d as qn,e as Jn,f as $,g as Me,k as He,r as qe,v as Je}from"./chunk-AEYNMLMW.js";import{h as V,i as Xe,k as jt,m as Vt}from"./chunk-HEJO7OBH.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();p();p();p();p();var z=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};p();function Xn(t){return/^[0-9A-Fa-f]$/.test(t)}function Y(t){return t>="0"&&t<="9"}function Qn(t){return t>=" "}function ke(t){return`,:[]/{}()
|
|
4
|
-
+`.includes(t)}function Qt(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function Zt(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var en=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,tn=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function nn(t){return`,[]/{}
|
|
5
|
-
+`.includes(t)}function on(t){return we(t)||Kr.test(t)}var Kr=/^[[{\w-]$/;function Zn(t){return t===`
|
|
6
|
-
`||t==="\r"||t===" "||t==="\b"||t==="\f"}function J(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function eo(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function to(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function we(t){return rn(t)||st(t)}function rn(t){return t==='"'||t==="\u201C"||t==="\u201D"}function sn(t){return t==='"'}function st(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function an(t){return t==="'"}function ue(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=t.lastIndexOf(e);return o!==-1?t.substring(0,o)+(n?"":t.substring(o+1)):t}function F(t,e){let n=t.length;if(!J(t,n-1))return t+e;for(;J(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function no(t,e,n){return t.substring(0,e)+t.substring(e+n)}function oo(t){return/[,\n][ \t\r]*$/.test(t)}var Gr={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},$r={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
7
|
-
`,r:"\r",t:" "};function at(t){let e=0,n="";c(["```","[```","{```"]),i()||ee(),c(["```","```]","```}"]);let r=f(",");for(r&&s(),on(t[e])&&oo(n)?(r||(n=F(n,",")),T()):r&&(n=ue(n,","));t[e]==="}"||t[e]==="]";)e++,s();if(e>=t.length)return n;ze();function i(){s();let y=g()||C()||S()||w()||b()||j(!1)||$t();return s(),y}function s(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,E=e,A=a(y);do A=l(),A&&(A=a(y));while(A);return e>E}function a(y){let E=y?J:eo,A="";for(;;)if(E(t,e))A+=t[e],e++;else if(to(t,e))A+=" ",e++;else break;return A.length>0?(n+=A,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!Br(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
|
|
8
|
-
`;)e++;return!0}return!1}function c(y){if(u(y)){if(Qt(t[e]))for(;e<t.length&&Zt(t[e]);)e++;return s(),!0}return!1}function u(y){a(!0);for(let E of y){let A=e+E.length;if(t.slice(e,A)===E)return e=A,!0}return!1}function f(y){return t[e]===y?(n+=t[e],e++,!0):!1}function d(y){return t[e]===y?(e++,!0):!1}function m(){return d("\\")}function h(){return s(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,s(),d(","),!0):!1}function g(){if(t[e]==="{"){n+="{",e++,s(),d(",")&&s();let y=!0;for(;e<t.length&&t[e]!=="}";){let E;if(y?(E=!0,y=!1):(E=f(","),E||(n=F(n,",")),s()),h(),!(S()||j(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?n=ue(n,","):U();break}s();let We=f(":"),te=e>=t.length;We||(on(t[e])||te?n=F(n,":"):ve()),i()||(We||te?n+="null":ve())}return t[e]==="}"?(n+="}",e++):n=F(n,"}"),!0}return!1}function C(){if(t[e]==="["){n+="[",e++,s(),d(",")&&s();let y=!0;for(;e<t.length&&t[e]!=="]";)if(y?y=!1:f(",")||(n=F(n,",")),h(),!i()){n=ue(n,",");break}return t[e]==="]"?(n+="]",e++):n=F(n,"]"),!0}return!1}function T(){let y=!0,E=!0;for(;E;)y?y=!1:f(",")||(n=F(n,",")),E=i();E||(n=ue(n,",")),n=`[
|
|
9
|
-
${n}
|
|
10
|
-
]`}function S(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,E=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,A=t[e]==="\\";if(A&&(e++,A=!0),we(t[e])){let We=sn(t[e])?sn:an(t[e])?an:st(t[e])?st:rn,te=e,be=n.length,M='"';for(e++;;){if(e>=t.length){let O=P(e-1);return!y&&ke(t.charAt(O))?(e=te,n=n.substring(0,be),S(!0)):(M=F(M,'"'),n+=M,!0)}if(e===E)return M=F(M,'"'),n+=M,!0;if(We(t[e])){let O=e,Bt=M.length;if(M+='"',e++,n+=M,s(!1),y||e>=t.length||ke(t[e])||we(t[e])||Y(t[e]))return R(),!0;let H=P(O-1),zn=t.charAt(H);if(zn===",")return e=te,n=n.substring(0,be),S(!1,H);if(ke(zn))return e=te,n=n.substring(0,be),S(!0);n=n.substring(0,be),e=O+1,M=`${M.substring(0,Bt)}\\${M.substring(Bt)}`}else if(y&&nn(t[e])){if(t[e-1]===":"&&en.test(t.substring(te+1,e+2)))for(;e<t.length&&tn.test(t[e]);)M+=t[e],e++;return M=F(M,'"'),n+=M,R(),!0}else if(t[e]==="\\"){let O=t.charAt(e+1);if($r[O]!==void 0)M+=t.slice(e,e+2),e+=2;else if(O==="u"){let H=2;for(;H<6&&Xn(t[e+H]);)H++;H===6?(M+=t.slice(e,e+6),e+=6):e+H>=t.length?e=t.length:Fr()}else M+=O,e+=2}else{let O=t.charAt(e);O==='"'&&t[e-1]!=="\\"?(M+=`\\${O}`,e++):Zn(O)?(M+=Gr[O],e++):(Qn(O)||Z(O),M+=O,e++)}A&&m()}}return!1}function R(){let y=!1;for(s();t[e]==="+";){y=!0,e++,s(),n=ue(n,'"',!0);let E=n.length;S()?n=no(n,E,1):n=F(n,'"')}return y}function w(){let y=e;if(t[e]==="-"){if(e++,ae())return I(y),!0;if(!Y(t[e]))return e=y,!1}for(;Y(t[e]);)e++;if(t[e]==="."){if(e++,ae())return I(y),!0;if(!Y(t[e]))return e=y,!1;for(;Y(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,ae())return I(y),!0;if(!Y(t[e]))return e=y,!1;for(;Y(t[e]);)e++}if(!ae())return e=y,!1;if(e>y){let E=t.slice(y,e),A=/^0\d/.test(E);return n+=A?`"${E}"`:E,!0}return!1}function b(){return x("true","true")||x("false","false")||x("null","null")||x("True","true")||x("False","false")||x("None","null")}function x(y,E){return t.slice(e,e+y.length)===y?(n+=E,e+=y.length,!0):!1}function j(y){let E=e;if(Qt(t[e])){for(;e<t.length&&Zt(t[e]);)e++;let A=e;for(;J(t,A);)A++;if(t[A]==="(")return e=A+1,i(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!nn(t[e])&&!we(t[e])&&(!y||t[e]!==":");)e++;if(t[e-1]===":"&&en.test(t.substring(E,e+2)))for(;e<t.length&&tn.test(t[e]);)e++;if(e>E){for(;J(t,e-1)&&e>0;)e--;let A=t.slice(E,e);return n+=A==="undefined"?"null":JSON.stringify(A),t[e]==='"'&&e++,!0}}function $t(){if(t[e]==="/"){let y=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=`"${t.substring(y,e)}"`,!0}}function P(y){let E=y;for(;E>0&&J(t,E);)E--;return E}function ae(){return e>=t.length||ke(t[e])||J(t,e)}function I(y){n+=`${t.slice(y,e)}0`}function Z(y){throw new z(`Invalid character ${JSON.stringify(y)}`,e)}function ze(){throw new z(`Unexpected character ${JSON.stringify(t[e])}`,e)}function ee(){throw new z("Unexpected end of json string",t.length)}function U(){throw new z("Object key expected",e)}function ve(){throw new z("Colon expected",e)}function Fr(){let y=t.slice(e,e+6);throw new z(`Invalid unicode character "${y}"`,e)}}function Br(t,e){return t[e]==="*"&&t[e+1]==="/"}var jr=L("JSON_PARSE");function Vr(t,e={}){if(!t||typeof t!="string")return e;try{return JSON.parse(t)}catch(n){let o=zr(t);if(o!==void 0)return o;try{let r=at(t);return JSON.parse(r)}catch(r){let i=so(t);if(i&&i!==t)try{return JSON.parse(at(i))}catch{}return jr.error("Failed to parse JSON even with jsonrepair:",{originalError:n,repairError:r,jsonString:t}),e}}}var ro=Symbol("tool-args-parse-failed");function io(t){if(t==null)return{};let e=typeof t=="string"?t.trim():"";if(!e)return{};let n=Vr(e,ro);return n===ro?null:n&&typeof n=="object"&&!Array.isArray(n)?n:null}function zr(t){let e=so(t);if(e&&e!==t.trim())try{return JSON.parse(e)}catch{return}}function so(t){let e=t.trimStart();if(!e)return null;let n=e[0];if(n!=="{"&&n!=="[")return null;let o=0,r=!1,i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(r){i?i=!1:a==="\\"?i=!0:a==='"'&&(r=!1);continue}if(a==='"'){r=!0;continue}if(a==="{"||a==="[")o++;else if(a==="}"||a==="]"){if(o--,o===0)return e.slice(0,s+1);if(o<0)return null}}return null}p();var Wr=/[A-Za-z\u00C0-\u024F]/g;function Hr(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 ln(t){let e=t.codePointAt(0);return e!==void 0&&Hr(e)}function qr(t){let e=t.match(Wr)?.length??0;if(e<24)return!1;let n=0;for(let o of t)ln(o)&&n++;return n===0||e>=n*8}function lt(t){if(!t||!qr(t))return t;let e="",n=0,o=[...t];for(;n<o.length;){if(!ln(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&&ln(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," ")}p();var ce=L("TAGGED_THINKING_PARSER"),Ie=["<think>","<thinking>"],Oe=["</think>","</thinking>"],Jr=Math.max(...Ie.map(t=>t.length),...Oe.map(t=>t.length));function xe(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function ut(t,e,n){let o=t.length-e;return o<=0||o>Jr?!1:n.some(r=>r.startsWith(t.slice(e,e+o)))}function ct(t,e,n){return n.find(o=>t.startsWith(o,e))}function cn(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 ao(t){let e=[];for(let n of t){if(n.thought===!0||typeof n.text!="string"){e.push(n);continue}let o=lt(cn(n.text));(o.length>0||/^\s+$/.test(n.text))&&e.push({text:o.length>0?o:n.text})}return e}var un=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=ct(o,s,Ie);if(a){ce.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),xe(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=ct(o,s,Oe);if(l){ce.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),xe(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(ut(o,s,Ie)||ut(o,s,Oe)))break}else{let a=ct(o,s,Oe);if(a){ce.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),xe(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=ct(o,s,Ie);if(l){s+=l.length;continue}if(!n&&(ut(o,s,Oe)||ut(o,s,Ie)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(xe(r,i,this.mode),this.buffer=this.buffer.slice(s),ce.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),ao(r)):(this.buffer="",this.mode==="thought"&&i&&ce.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),xe(r,i,this.mode),ce.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),ao(r))}};function lo(t){return new un().parse(t,!0)}p();function uo(t,e="auto"){return e==="openapi_30"?Yr(t):t}function Yr(t){let e=n=>{if(typeof n!="object"||n===null)return n;if(Array.isArray(n))return n.map(e);let o=n,r={};if(Array.isArray(o.type)){let i=o.type;i.length===2&&i.includes("null")?(r.type=i.find(s=>s!=="null"),r.nullable=!0):r.type=i[0]}else o.type!==void 0&&(r.type=o.type);o.const!==void 0&&(r.enum=[o.const],delete r.const),typeof o.exclusiveMinimum=="number"&&(r.minimum=o.exclusiveMinimum,r.exclusiveMinimum=!0),typeof o.exclusiveMaximum=="number"&&(r.maximum=o.exclusiveMaximum,r.exclusiveMaximum=!0),Array.isArray(o.items)?delete r.items:typeof o.items=="object"&&o.items!==null&&(r.items=e(o.items)),Array.isArray(o.enum)&&(r.enum=o.enum.map(String));for(let[i,s]of Object.entries(o))i==="type"||i==="const"||i==="exclusiveMinimum"||i==="exclusiveMaximum"||i==="items"||i==="enum"||i==="$schema"||i==="$id"||i==="default"||i==="dependencies"||i==="patternProperties"||(r[i]=e(s));return r};return e(t)}p();function de(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function dt(t){let e=t.candidates||0,n=t.thoughts||0;return n>e?e+n:Math.max(e,n)}function Xr(t){return t.total&&t.total>0?Math.max(t.total,(t.prompt||0)+dt(t)):(t.prompt||0)+dt(t)}function Qr(t){let e=Math.max(0,t.thoughtsTokens||0),n=dt({candidates:t.outputTokens||0,thoughts:e}),o=Math.max(t.totalTokens||0,(t.inputTokens||0)+n);return{...t,outputTokens:n,thoughtsTokens:e,totalTokens:o}}var W=L("CONVERTER"),Co="(attached media from previous tool call)";function yo(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),f=l>0?l:c,d=o;f>0&&(o>=f?d=o:d=o+f),(u>0||c>0)&&(d=Math.max(d,u+(l>0?0:c),u+f)),r>n&&(n>0||o>0||f>0)&&(d=Math.max(d,r-n)),f===0&&c>0&&(f=c),f>d&&(f=d);let m=t.usage_is_incomplete===!0||o>0&&n===0||r>0&&n===0&&o===0,h=n,g=r;return(g===0&&(h>0||d>0)||g>0&&h>0&&g<h+d)&&(g=h+d),{promptTokenCount:h,candidatesTokenCount:d,totalTokenCount:g,cachedContentTokenCount:s,thoughtsTokenCount:f,...m?{usageIsIncomplete:!0}:{}}}var Zr=64,co=1024;function po(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)?(W.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(W.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>=co&&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,W.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${t.length}b)`),i}}return t===e.emittedText?t.length>=Zr?(e.cumulativeMode=!0,W.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<co&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function To(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 ei(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=To(i.parameters)),s&&(s=uo(s,e)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function ti(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return oi(t,o),ri(t.contents,o,e),o=ho(o),n.cleanOrphanToolCalls&&(o=gi(o),o=ho(o)),o}function ni(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=fi(n?.finishReason),f=t.usageMetadata,d={prompt_tokens:f?.promptTokenCount||0,completion_tokens:f?.candidatesTokenCount||0,total_tokens:f?.totalTokenCount||0};f?.cachedContentTokenCount!==void 0&&(d.prompt_tokens_details={cached_tokens:f.cachedContentTokenCount});let m=t.createTime?Number(t.createTime):Date.now(),h=Number.isFinite(m)?Math.floor(m/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:h,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:u,logprobs:null}],usage:d}}function oi(t,e){if(!t.config?.systemInstruction)return;let n=Eo(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function ri(t,e,n){if(Array.isArray(t))for(let o of t)fo(o,e,n);else t&&fo(t,e,n)}function fo(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!li(t))return;let o=t.parts||[],r=t.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,c=new Set,u=new Set,f=[];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 m=So(d,n);if(m&&r==="user"&&i.push(m),"functionCall"in d&&d.functionCall&&r==="assistant"){let h=d.functionCall.id;if(h){if(c.has(h)){W.debug(`Dropping duplicate functionCall id=${h} while converting content`);continue}c.add(h)}a.push({id:h||`call_${l}`,type:"function",function:{name:d.functionCall.name||"",arguments:JSON.stringify(d.functionCall.args||{})}}),l+=1}if(d.functionResponse&&r==="user"){let h=d.functionResponse.id;if(h){if(u.has(h))continue;u.add(h)}let g=si(d.functionResponse,n);if(g){if(n.splitToolMedia&&Array.isArray(g.content)){let C=[],T=[];for(let S of g.content)S&&(S.type==="image_url"||S.type==="input_audio"||S.type==="video_url"||S.type==="file")?C.push(S):S&&S.type==="text"&&T.push(S);if(C.length>0){let S=T.map(R=>R.text).join(`
|
|
11
|
-
`);g.content=S||"[media attached in following user message]",f.push(...C)}}e.push(g)}}}if(f.length>0&&e.push({role:"user",content:[{type:"text",text:Co},...f]}),r==="assistant"){if(i.length===0&&a.length===0&&s.length===0)return;let m={role:"assistant",content:i.filter(g=>g.type==="text").map(g=>g.text).join("")||(s.length>0?"":null)};a.length>0&&(m.tool_calls=a);let h=s.join("");h&&(m.reasoning_content=h),e.push(m);return}i.length>0&&e.push({role:"user",content:i})}function ii(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 si(t,e){let n=ii(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=So(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 So(t,e){let{modalities:n}=e;if(t.inlineData?.mimeType&&t.inlineData?.data){let o=t.inlineData.mimeType,r=go(o),i=t.inlineData.displayName||o;if(r==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${t.inlineData.data}`}}:re("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}`}}:re("pdf",i,e);if(r==="audio"){if(!n.audio)return re("audio",i,e);let s=ai(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}`}}:re("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=go(i);if(s==="image")return n.image?{type:"image_url",image_url:{url:r}}:re("image",o,e);if(i==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:r}}:re("pdf",o,e);if(s==="video")return n.video?{type:"video_url",video_url:{url:r}}:re("video",o,e);let a=t.fileData.displayName?` (${t.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${i}${a}.`}}return null}function re(t,e,n){W.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:
|
|
12
|
-
/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 go(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function ai(t){return t.includes("wav")?"wav":t.includes("mp3")||t.includes("mpeg")?"mp3":null}function li(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&Array.isArray(t.parts)}function Eo(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>Eo(e)).filter(Boolean).join(`
|
|
13
|
-
`):typeof t=="object"&&t!==null&&"parts"in t&&t.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
|
|
14
|
-
`)||""}function pt(t,e,n=!0){if(e.taggedThinkingParser)return e.taggedThinkingParser.parse(t,n);if(e.responseParsingOptions?.taggedThinkingTags)return lo(t);if(!t)return[];let o=lt(cn(t));return o?[{text:o}]:[]}function ui(t,e){let n=t.choices?.[0],o=new ne;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(...pt(n.message.content,e)),n.message.tool_calls){for(let i of n.message.tool_calls)if(i.function){let s=io(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:Ao(n.finish_reason),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=yo(t.usage,{estimatedReasoningTokens:de(i.length),estimatedContentTokens:de(s.length)})}return o}function ci(t,e){let n=t.choices?.[0],o=new ne,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=po(c,e.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});u&&i.push({text:u,thought:!0})}}if(typeof n.delta?.content=="string"){let c=po(n.delta.content,e.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(c||n.finish_reason)&&i.push(...pt(c,e,!!n.finish_reason))}else n.finish_reason&&i.push(...pt("",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=Ao(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=yo(t.usage,pi(e))),o}function di(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(...pt("",t,!0)),n.length===0&&!r)return null;let i=new ne;return i.candidates=[{content:{parts:n,role:"model"},index:0,safetyRatings:[],finishReason:r?_.MAX_TOKENS:_.STOP}],i.responseId=`stream-flush-${Date.now()}`,i.createTime=new Date().getTime().toString(),i.modelVersion=t.model,i.promptFeedback={safetyRatings:[]},i}function pi(t){return{estimatedReasoningTokens:de(t.reasoningDeltaState?.emittedLength??0),estimatedContentTokens:de(t.textDeltaState?.emittedLength??0)}}function Ao(t){return t?{stop:_.STOP,length:_.MAX_TOKENS,content_filter:_.SAFETY,function_call:_.STOP,tool_calls:_.STOP}[t]||_.FINISH_REASON_UNSPECIFIED:_.FINISH_REASON_UNSPECIFIED}function fi(t){if(!t)return"stop";switch(t){case _.STOP:return"stop";case _.MAX_TOKENS:return"length";case _.SAFETY:case _.RECITATION:case _.BLOCKLIST:case _.PROHIBITED_CONTENT:case _.SPII:case _.IMAGE_SAFETY:case _.IMAGE_RECITATION:case _.IMAGE_PROHIBITED_CONTENT:case _.IMAGE_OTHER:return"content_filter";case _.NO_IMAGE:return"stop";default:return"stop"}}function dn(t){return t.role==="assistant"&&"tool_calls"in t&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0}function mo(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===Co}function gi(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(dn(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 f=new Set,d=[],m=[],h=!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){h=!1;continue}u.has(T.tool_call_id)&&!f.has(T.tool_call_id)?(f.add(T.tool_call_id),d.push(C),h=!0):h=!1;continue}if(mo(T)){h&&m.push(C);continue}if(!(T.role==="assistant"&&!dn(T)))break}let g=c.filter(C=>f.has(C.id));for(let C of g)s.add(C.id);n.set(a,g),o.set(a,d),r.set(a,m)}}for(let a=0;a<t.length;a+=1){if(i.has(a))continue;let l=t[a];if(dn(l)){let c=l.reasoning_content,u=n.get(a)??[];if(u.length>0){let f={...l};f.tool_calls=u,e.push(f);for(let d of o.get(a)??[]){let m=t[d];m&&(e.push(m),i.add(d))}for(let d of r.get(a)??[]){let m=t[d];m&&(e.push(m),i.add(d))}}else if(typeof l.content=="string"&&l.content.trim()||c){let f={...l};delete f.tool_calls,e.push(f)}else W.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?W.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):mo(l)?W.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):e.push(l)}return e}function ho(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 f=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=[...f,...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 ft={convertGeminiToolParametersToOpenAI:To,convertGeminiToolsToOpenAI:ei,convertGeminiRequestToOpenAI:ti,convertGeminiResponseToOpenAI:ni,convertOpenAIResponseToGemini:ui,convertOpenAIChunkToGemini:ci,flushOpenAIStreamToGemini:di};p();p();var Tl=new Set(["ECONNRESET","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET","ConnectionClosed","ConnectionReset","ConnectionTimedOut"]),Ro=new Set(["EAI_AGAIN","ECONNREFUSED","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","UND_ERR_CONNECT_TIMEOUT","ConnectionRefused","FailedToOpenSocket","HostUnreachable","NetworkUnreachable"]);var pn="MATILDA_BASE_URL",mi=new Set(["localhost","127.0.0.1","[::1]"]);function mt(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function bl(t){try{let{host:e}=new URL(mt(t));return e===new URL(_e).host?"Matilda":e}catch{return t}}function Mo(t){let e;try{e=new URL(mt(t))}catch{return}if(!(!(e.protocol==="https:"||e.protocol==="http:"&&mi.has(e.hostname))||e.username||e.password||e.search||e.hash))return`${e.origin}${e.pathname.replace(/\/+$/,"")}/api/v1/code`}function _o(t=process.env){let e=t[pn]?.trim();return e?Mo(e):void 0}function Pe(t,e=process.env){let n=_o(e);if(!n||!t)return!1;try{return new URL(t).origin===new URL(n).origin}catch{return!1}}function fn(t){return t.apiKeyEnvKey===rt||hi(t.baseUrl)}function hi(t){if(!t)return!0;let e=t.endsWith("/")?t.slice(0,-1):t,n=null;try{n=new URL(e).hostname.toLowerCase()}catch{n=null}return n!==null&&(n==="matilda.maincode.com"||n.endsWith(".matilda.maincode.com")||n==="localhost"||n==="127.0.0.1"||n.endsWith(".matilda")||n==="core-api.matilda")||Pe(e)}var gt="its certificate is not from an authority this computer trusts. If it uses a private certificate authority, or your network inspects secure connections, set NODE_EXTRA_CA_CERTS to that authority's certificate file.",Ci=new Map([["UNABLE_TO_GET_ISSUER_CERT_LOCALLY",gt],["UNABLE_TO_VERIFY_LEAF_SIGNATURE",gt],["SELF_SIGNED_CERT_IN_CHAIN",gt],["DEPTH_ZERO_SELF_SIGNED_CERT",gt],["CERT_HAS_EXPIRED","its certificate has expired."],["ERR_TLS_CERT_ALTNAME_INVALID","its certificate is for another name. Check the address."]]),vo="its name does not resolve. Check the address and your network.",bo="it refused the connection. Check the address, and that the server is running.",yi=new Map([["ENOTFOUND",vo],["EAI_AGAIN",vo],["ECONNREFUSED",bo],["ConnectionRefused",bo],["UND_ERR_CONNECT_TIMEOUT","it did not answer. Check your network, VPN and proxy."]]),ko=5;function De(t,e){if($(t)!==void 0)return;let n=t;for(let o=0;o<=ko;o++){if(typeof n!="object"||n===null)return;let{code:r,cause:i}=n;if(typeof r=="string"){let s=mt(e),a=Ci.get(r);if(a)return new qe(`Could not connect securely to ${s}: ${a}`,r);if(Ro.has(r))return new qe(`Could not reach ${s}: ${yi.get(r)??"the network cannot reach it. Check your network, VPN and proxy."}`,r)}n=i}}function gn(t,e){let n=t;for(let o=0;o<=ko;o++){if(typeof n!="object"||n===null)return;let{name:r,cause:i}=n;if(r==="TimeoutError")return new qe(`${mt(e)} did not answer in time. Check your network, VPN and proxy.`,"ETIMEDOUT");n=i}}function Ti(t=process.env){let e=t[pn]?.trim();if(e&&!Mo(e))throw new He(`${pn} must be the HTTPS address of your Matilda deployment, such as https://matilda.example.com. HTTP is accepted only for localhost.`)}function K(t=process.env){return Ti(t),_o(t)??_e}p();p();p();Vt();var Si=new Set(["service.version","service.instance.id","session.id"]);function ie(t,e){Xe.warn(t),e?.push(t)}function wo(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){ie(`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{ie(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,e),l=s}let c;try{c=decodeURIComponent(a)}catch{ie(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${l}", using raw value`,e),c=a}n[l]=c}return n}function mn(t,e,n){for(let o of Si)o in t&&(ie(`${e} cannot override reserved key "${o}"; ignoring`,n),delete t[o]);return t}function xo(t,e){if(t==null)return{};if(typeof t!="object"||Array.isArray(t))return ie("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){ie("settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",e);continue}typeof r=="string"?n[i]=r:ie(`settings.telemetry.resourceAttributes value for "${i}" must be a string (got ${typeof r}); ignoring`,e)}return n}function Ue(t){if(t!==void 0)return t==="true"||t==="1"}async function Ei(t){let e=t.argv??{},n=t.env??{},o=t.settings??{},r=e.telemetry??Ue(n.MATILDA_TELEMETRY_ENABLED)??o.enabled,i=e.telemetryOtlpEndpoint??n.MATILDA_TELEMETRY_OTLP_ENDPOINT??n.OTEL_EXPORTER_OTLP_ENDPOINT??o.otlpEndpoint,s=e.telemetryOtlpProtocol??n.MATILDA_TELEMETRY_OTLP_PROTOCOL??o.otlpProtocol,a=["grpc","http"].find(b=>b===s);if(s!==void 0&&a===void 0)throw new He(`Invalid telemetry OTLP protocol: ${String(s)}. Valid values are: grpc, http`);let l=e.telemetryLogPrompts??Ue(n.MATILDA_TELEMETRY_LOG_PROMPTS)??o.logPrompts,c=Ue(n.MATILDA_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES)??o.includeSensitiveSpanAttributes??!1,u=e.telemetryOutfile??n.MATILDA_TELEMETRY_OUTFILE??o.outfile,f=n.MATILDA_TELEMETRY_OTLP_TRACES_ENDPOINT??n.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT??o.otlpTracesEndpoint,d=n.MATILDA_TELEMETRY_OTLP_LOGS_ENDPOINT??n.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT??o.otlpLogsEndpoint,m=n.MATILDA_TELEMETRY_OTLP_METRICS_ENDPOINT??n.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT??o.otlpMetricsEndpoint,h=[],g=mn(wo(n.OTEL_RESOURCE_ATTRIBUTES,h),"OTEL_RESOURCE_ATTRIBUTES",h),C=mn(xo(o.resourceAttributes,h),"settings.telemetry.resourceAttributes",h),T={...g,...C},S=n.OTEL_SERVICE_NAME?.trim();S&&(T["service.name"]=S);let R=Object.keys(T).length?T:void 0,w=Ue(n.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??o.metrics?.includeSessionId??!1;return{enabled:r,otlpEndpoint:i,otlpProtocol:a,otlpTracesEndpoint:f,otlpLogsEndpoint:d,otlpMetricsEndpoint:m,logPrompts:l,includeSensitiveSpanAttributes:c,outfile:u,resourceAttributes:R,metrics:{includeSessionId:w},resourceAttributeWarnings:h.length?h:void 0}}p();Vt();import*as Q from"node:fs";import*as Gt from"node:path";p();p();p();p();Vt();p();import{AsyncLocalStorage as Ai}from"node:async_hooks";var Io=new Ai;p();import*as G from"node:path";import{promises as yt}from"node:fs";p();p();import Ri from"crypto";var Ct=new Uint8Array(256),ht=Ct.length;function hn(){return ht>Ct.length-16&&(Ri.randomFillSync(Ct),ht=0),Ct.slice(ht,ht+=16)}p();var k=[];for(let t=0;t<256;++t)k.push((t+256).toString(16).slice(1));function Oo(t,e=0){return k[t[e+0]]+k[t[e+1]]+k[t[e+2]]+k[t[e+3]]+"-"+k[t[e+4]]+k[t[e+5]]+"-"+k[t[e+6]]+k[t[e+7]]+"-"+k[t[e+8]]+k[t[e+9]]+"-"+k[t[e+10]]+k[t[e+11]]+k[t[e+12]]+k[t[e+13]]+k[t[e+14]]+k[t[e+15]]}p();p();import vi from"crypto";var Cn={randomUUID:vi.randomUUID};function bi(t,e,n){if(Cn.randomUUID&&!e&&!t)return Cn.randomUUID();t=t||{};let o=t.random||(t.rng||hn)();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 Oo(o)}var yn=bi;import*as X from"os";var Tt=L("OPENAI_LOGGER"),Mi="########",_i=/^[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 ki(t,e){let n=e||process.cwd();if(!t)return G.join(n,"logs","openai");let o=t;return t==="~"||t.startsWith("~/")?o=G.join(X.homedir(),t.slice(1)):G.isAbsolute(t)||(o=G.resolve(n,t)),G.normalize(o)}function Po(t){return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function wi(t){let e=t.split("#");if(e.length!==3)return;let[,n,o]=e;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function xi(t){if(t)return le(t)?Po(t):Po(wi(t))}function Ii(t){if(!t)return;let e=t.indexOf(Mi);if(e>0)return t.slice(0,e);if(_i.test(t))return t;let n=t.split("#");if(n.length>=3&&n[0])return n[0]}function Oi(t){let e=t?.trim(),n=Ii(e);return!e&&!n?null:{...e?{promptId:e}:{},...n?{sessionId:n}:{}}}var Ne=class{logDir;initialized=!1;constructor(e,n){this.logDir=ki(e,n)}async initialize(){if(!this.initialized)try{await yt.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(e){throw Tt.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=yn().slice(0,8),a=xi(r),l=a?`openai-${i}-${s}-${a}.json`:`openai-${i}-${s}.json`,c=G.join(this.logDir,l),u={timestamp:new Date().toISOString(),request:e,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:Oi(r),system:{hostname:X.hostname(),platform:X.platform(),release:X.release(),nodeVersion:process.version}};try{return await yt.writeFile(c,JSON.stringify(u,null,2),"utf-8"),c}catch(f){throw Tt.error("Failed to write OpenAI log file:",f),new Error(`Failed to write OpenAI log file: ${f}`)}}async getLogFiles(e){this.initialized||await this.initialize();try{let o=(await yt.readdir(this.logDir)).filter(r=>r.startsWith("openai-")&&r.endsWith(".json")).map(r=>G.join(this.logDir,r)).sort().reverse();return e?o.slice(0,e):o}catch(n){return n.code==="ENOENT"?[]:(Tt.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(e){try{let n=await yt.readFile(e,"utf-8");return JSON.parse(n)}catch(n){throw Tt.error(`Failed to read log file ${e}:`,n),new Error(`Failed to read log file: ${n}`)}}},ru=new Ne;p();var Pi="MATILDA_CODE_PROFILE_RUNTIME";function Do(t=process.env){return t[Pi]==="1"}var Sn=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;requests=[];openaiWireRequests=[];tools=Uo();constructor(e={}){this.enabled=e.enabled??Do(),this.now=e.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(e={}){this.enabled=e.enabled??Do(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.tools=Uo()}isEnabled(){return this.enabled}recordGenerateContentRequest(e,n){this.enabled&&(this.requestIndex+=1,this.requests.push({index:this.requestIndex,timestamp:this.now(),source:n.source,model:e.model,stream:n.stream,serializedBytes:D(Ki(e)),contents:No(e.contents),systemInstructionBytes:Ni(e.config?.systemInstruction),generationConfigBytes:D(Lo(e.config)),tools:Fi(e.config?.tools)}))}recordOpenAIWireRequest(e){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...Di(e)}))}recordToolUse(e,n){if(!this.enabled)return;let o=D(n),r=this.getToolNameDiagnostics(e);r.uses+=1,r.argBytes+=o,r.maxArgBytes=Math.max(r.maxArgBytes,o),this.tools.toolUseCount+=1,this.tools.totalToolUseArgBytes+=o,this.tools.maxToolUseArgBytes=Math.max(this.tools.maxToolUseArgBytes,o)}recordToolResult(e){if(!this.enabled)return;let n=this.getToolNameDiagnostics(e.name);n.results+=1,n.resultBytes+=e.resultBytes,n.maxResultBytes=Math.max(n.maxResultBytes,e.resultBytes),e.isError&&(n.errors+=1,this.tools.toolResultErrorCount+=1),this.tools.toolResultCount+=1,this.tools.totalToolResultBytes+=e.resultBytes,this.tools.maxToolResultBytes=Math.max(this.tools.maxToolResultBytes,e.resultBytes)}snapshot(){return{enabled:this.enabled,startedAt:this.startedAt,requests:this.requests.map(e=>({...e,contents:{...e.contents,roleCounts:{...e.contents.roleCounts}},tools:{...e.tools}})),openaiWireRequests:this.openaiWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),tools:{...this.tools,byName:Object.fromEntries(Object.entries(this.tools.byName).map(([e,n])=>[e,{...n}]))}}}getToolNameDiagnostics(e){let n=this.tools.byName[e];if(n)return n;let o=Ui();return this.tools.byName[e]=o,o}},En=new Sn;function Di(t){let e=pe(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let i of n){let s=pe(i),a=typeof s.role=="string"?s.role:"unknown";r[a]=(r[a]??0)+D(s.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:D(t),messageCount:n.length,messageBytesByRole:r,toolsCount:o.length,toolSchemaBytes:D(o),topLevelKeys:Object.keys(e).sort()}}function Uo(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function Ui(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function No(t){let e={count:0,roleCounts:{},partCount:0,textBytes:0,functionCallCount:0,functionCallArgBytes:0,functionResponseCount:0,functionResponseBytes:0,inlineDataCount:0,inlineDataBytes:0,fileDataCount:0},n=Array.isArray(t)?t:t==null?[]:[t];for(let o of n){if(e.count+=1,typeof o=="string"){e.roleCounts.user=(e.roleCounts.user??0)+1,e.partCount+=1,e.textBytes+=D(o);continue}let r=pe(o),i=typeof r.role=="string"?r.role:"unknown";e.roleCounts[i]=(e.roleCounts[i]??0)+1;let s=Array.isArray(r.parts)?r.parts:[];Li(s,e)}return e}function Ni(t){return No(t).textBytes}function Li(t,e){for(let n of t){if(e.partCount+=1,typeof n=="string"){e.textBytes+=D(n);continue}let o=pe(n);typeof o.text=="string"&&(e.textBytes+=D(o.text));let r=Tn(o.functionCall);r&&(e.functionCallCount+=1,e.functionCallArgBytes+=D(r.args));let i=Tn(o.functionResponse);i&&(e.functionResponseCount+=1,e.functionResponseBytes+=D(i.response)+D(i.parts));let s=Tn(o.inlineData);s&&(e.inlineDataCount+=1,e.inlineDataBytes+=D(s.data)),o.fileData&&(e.fileDataCount+=1)}}function Fi(t){let e=Array.isArray(t)?t:[],n=0;for(let o of e){let r=pe(o),i=Array.isArray(r.functionDeclarations)?r.functionDeclarations:[];n+=i.length}return{count:e.length,functionDeclarationCount:n,schemaBytes:D(e)}}function Ki(t){return{model:t.model,contents:t.contents,config:Lo(t.config)}}function Lo(t){if(!t)return;let e=pe(t),n={};for(let[o,r]of Object.entries(e))o!=="abortSignal"&&(n[o]=r);return n}function D(t){return t==null?0:typeof t=="string"?Buffer.byteLength(t,"utf8"):Buffer.byteLength(Gi(t),"utf8")}function Gi(t){try{return JSON.stringify(t)??""}catch{return"[unserializable]"}}function pe(t){return typeof t=="object"&&t!==null?t:{}}function Tn(t){return typeof t=="object"&&t!==null?t:null}p();function Fo(t){let e=t.candidates?.[0]?.content?.parts;return!e||e.length===0?!1:e.some($i)}function $i(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 Ko(){let t=Wn.getStore();return{attempt:t?.attempt??1,requestSetupMs:t?.requestSetupMs,retryTotalDelayMs:t?.retryTotalDelayMs}}var se=L("LOGGING_CONTENT_GENERATOR"),Bi=4096,Go="...[truncated]",ji=Bi-Go.length,Le=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 Ne(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);zt(this.config,new qt(n,o,r,q.getStore()))}_logApiResponse(e,n,o,r,i,s){Ht(this.config,new Yt(e,o,n,r,this.generatorAuthType,i,s,q.getStore()))}_logApiError(e,n,o,r,i){let s=Jn(o),a=Me(o),l=o?.requestID||o?.request_id||e,c=$(o);Wt(this.config,new Jt({responseId:l,model:r,durationMs:n,promptId:i,authType:this.generatorAuthType,errorMessage:s,errorType:a,statusCode:c,subagentName:q.getStore()}))}safelyLogApiError(e,n,o,r,i){try{this._logApiError(e,n,o,r,i)}catch(s){se.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){se.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=Ko(),r=tt(e.model,n);try{r.setAttribute("llm_request.stream",!1)}catch{}let i=jt.setSpan(V.active(),r),s=Date.now(),a=le(n),l=this.startCaptureSession();try{En.recordGenerateContentRequest(e,{stream:!1,source:"generateContent"}),a||(Qe(this.config,r,e.config?.systemInstruction),Ze(this.config,r,e.config?.tools));let c=await V.with(i,async()=>{a||this.logApiRequest(this.toContents(e.contents),e.model,n);let u=await l.wrap(()=>this.wrapped.generateContent(e,n)),f=Date.now()-s,d=a?void 0:this.extractResponseText(u);a||et(this.config,r,d),this.safelyLogApiResponse(u.responseId??"",f,this.getClientVisibleModelId(e.model,u.modelVersion),n,u.usageMetadata,d);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),u,void 0,n)}catch(m){se.warn("Failed to log OpenAI interaction:",m)}return u});return oe(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:q.getStore()||void 0,...o}),c}catch(c){let u=Date.now()-s,f=e.config?.abortSignal?.aborted??!1;throw oe(r,{success:!1,durationMs:u,error:f?ot:nt,errorType:Me(c),errorStatusCode:$(c),subagentName:q.getStore()||void 0,...o}),await V.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){se.warn("Failed to log OpenAI interaction:",d)}}),c}}async generateContentStream(e,n){let o=Ko(),r=tt(e.model,n);try{r.setAttribute("llm_request.stream",!0)}catch{}let i=jt.setSpan(V.active(),r),s=Date.now(),a=le(n),l=this.startCaptureSession(),c;try{En.recordGenerateContentRequest(e,{stream:!0,source:"generateContentStream"}),a||(Qe(this.config,r,e.config?.systemInstruction),Ze(this.config,r,e.config?.tools)),c=await V.with(i,async()=>(a||this.logApiRequest(this.toContents(e.contents),e.model,n),l.wrap(()=>this.wrapped.generateContentStream(e,n))))}catch(f){let d=Date.now()-s;V.with(i,()=>this.safelyLogApiError("",d,f,e.model,n));let m=e.config?.abortSignal?.aborted??!1;oe(r,{success:!1,durationMs:d,error:m?ot:nt,errorType:Me(f),errorStatusCode:$(f),subagentName:q.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,f,n)}catch(h){se.warn("Failed to log OpenAI interaction:",h)}throw f}let u;if(this.openaiLogger)try{u=await l.resolve(e)}catch(f){se.warn("Failed to resolve OpenAI request:",f)}return V.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():Io.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=le(o),f=!u||!!this.openaiLogger,d=[],m="",h="",g,C=!1,T,S=!1,R,w=q.getStore(),b,x=!1,j=I=>a?V.with(a,I):I(),$t=5*6e4,P,ae=s?()=>{x||(P!==void 0&&clearTimeout(P),P=setTimeout(()=>{try{s.setAttribute("stream.timed_out",!0)}catch{}oe(s,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:m||void 0,subagentName:w||void 0,...c}),x=!0},$t),P.unref())}:void 0;try{for await(let U of e){!m&&U.responseId&&(m=U.responseId),!h&&U.modelVersion&&(h=U.modelVersion),f&&d.push(U),U.usageMetadata&&(g=U.usageMetadata);let ve=U.candidates?.[0];ve?.finishReason&&(T=ve.finishReason),U.functionCalls?.length&&(S=!0),b===void 0&&Fo(U)&&(b=Date.now()-n),ae?.(),yield U,P!==void 0&&(clearTimeout(P),P=void 0)}P!==void 0&&(clearTimeout(P),P=void 0);let I=Date.now()-n,Z=f?this.consolidateGeminiResponsesForLogging(d):void 0,ze=u?void 0:this.extractResponseText(Z),ee=!T&&!S?new Error("Model stream ended without a finish reason"):void 0;ee&&(C=!0,R=ee),x||(ee?(j(()=>this.safelyLogApiError(m,I,ee,this.getClientVisibleModelId(r,h),o)),await j(()=>this.safelyLogOpenAIInteraction(i,Z,ee,o))):(j(()=>this.safelyLogApiResponse(m,I,this.getClientVisibleModelId(r,h),o,g,ze)),!u&&s&&et(this.config,s,ze),await j(()=>this.safelyLogOpenAIInteraction(i,Z,void 0,o))))}catch(I){if(C=!0,R=I,!x){let Z=Date.now()-n;j(()=>this.safelyLogApiError(m,Z,I,this.getClientVisibleModelId(r,h),o)),await j(()=>this.safelyLogOpenAIInteraction(i,void 0,I,o))}throw I}finally{if(P!==void 0&&clearTimeout(P),s&&!x){let I=l?.aborted??!1;oe(s,{success:!C,inputTokens:g?.promptTokenCount,outputTokens:g?.candidatesTokenCount,cachedInputTokens:g?.cachedContentTokenCount,ttftMs:b,durationMs:Date.now()-n,error:C?I?ot:nt:void 0,responseId:m||void 0,finishReason:T,thoughtsTokenCount:g?.thoughtsTokenCount,subagentName:w||void 0,errorType:R?Me(R):void 0,errorStatusCode:R?$(R):void 0,...c})}}}async buildOpenAIRequestForLogging(e){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(e.model),o=ft.convertGeminiRequestToOpenAI(e,n,{cleanOrphanToolCalls:!1}),r={model:e.model,messages:o};return e.config?.tools&&(r.tools=await ft.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){se.warn("Failed to log OpenAI interaction:",i)}}convertGeminiResponseToOpenAIForLogging(e,n){let o=new ne;return Object.assign(o,e),o.modelVersion=this.getClientVisibleModelId(n.model,e.modelVersion),ft.convertGeminiResponseToOpenAI(o,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(e){if(e.length===0)return;let n=new ne,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 f=u?.content?.parts??[];for(let d of f){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 m=d.functionCall.id||d.functionCall.name||"tool_call",h=r.get(m),g={functionCall:d.functionCall};h!==void 0?o[h]=g:(r.set(m,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=ji-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}${Go}`: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}
|
|
15
|
-
${n}`:n;return{...o,text:a}}return e}};p();var An="x-matilda-organization-id",Vi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Pu(t){if(t!==void 0){if(typeof t!="string"||t.length!==36||!Vi.test(t))throw new Error("--organization-id must be a single UUID.");return t.toLowerCase()}}function Rn(t){if(t)try{let e=new URL(t);if((e.hostname==="matilda.maincode.com"&&e.protocol==="https:"&&!e.port||e.hostname==="core-api.matilda"&&(e.protocol==="http:"||e.protocol==="https:"))&&!e.username&&!e.password&&!e.search&&!e.hash)return e}catch{}}function vn(t,e,n){if(e===void 0&&n===void 0)return;let o=Rn(t.baseUrl);if(!o||o.pathname.replace(/\/$/,"")!=="/api/v1/code"||t.authType!=="openai")throw new Error("Organization selection and credit spending require the first-party Matilda Core Code endpoint.")}function $o(t){for(let e of Object.keys(t??{})){let n=e.toLowerCase();if(n===An)throw new Error("Select the organization with --organization-id, not customHeaders.");if(n.startsWith("x-matilda-usage-credit-"))throw new Error("Code credit spending through customHeaders is not supported.")}}function Du(t,e,n,o,r){vn(n,o,r);let i=Rn(n.baseUrl),s=Rn(t instanceof Request?t.url:String(t));if(!s||s.origin!==i.origin||s.pathname!=="/api/v1/code/chat/completions")throw new Error("The selected organization cannot be sent to this endpoint.");let a=e.get(An);if(a!==null&&a!==o)throw new Error("The request organization conflicts with --organization-id.");o!==void 0&&e.set(An,o)}p();function Bo(t){switch(t){case"openai":return"OPENAI_API_KEY";default:return"API_KEY"}}function jo(t){switch(t){case"openai":return"OPENAI_MODEL";default:return"MODEL"}}var fe=class extends Error{constructor(e){super(e),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},St=class extends fe{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.`))}},Et=class extends fe{code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},At=class extends fe{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}'.`)}},Rt=class extends fe{code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}};p();import wn from"node:process";p();function Ku(t,e,n,o=2048){let r=e-n-o;return!Number.isFinite(r)||r<=0?0:Math.min(t,r)}var v={"32k":32768,"64k":65536,"128k":131072,"200k":2e5,"256k":262144,"272k":272e3,"400k":4e5,"512k":524288,"1m":1e6,"4k":4096,"8k":8192,"16k":16384};function vt(t){let e=(t??"").toLowerCase().trim();return e=e.replace(/^.*\//,""),e=e.split("|").pop()??e,e=e.split(":").pop()??e,e=e.replace(/\s+/g,"-"),e=e.replace(/-preview/g,""),e.match(/^kimi-k2-\d{4}$/)||(e=e.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g,"")),e=e.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g,""),e}var zi=[[/^gemini-3/,v["1m"]],[/^gemini-/,v["1m"]],[/^gpt-5/,v["272k"]],[/^gpt-/,v["128k"]],[/^o\d/,v["200k"]],[/^claude-/,v["200k"]],[/^glm-5(\.[01])?(-|$)/,202752],[/^glm-(?:[5-9]|\d{2,})/,v["1m"]],[/^glm-/,202752],[/^matilda-code$/,v["1m"]],[/^matilda/,v["256k"]],[/^ornith/,v["64k"]],[/^kimi-/,v["256k"]],[/^seed-oss/,v["512k"]]],Vo=[[/^gemini-3/,v["64k"]],[/^gemini-/,v["8k"]],[/^gpt-5/,v["128k"]],[/^gpt-/,v["16k"]],[/^o\d/,v["128k"]],[/^claude-opus-4-6/,v["128k"]],[/^claude-sonnet-4-6/,v["64k"]],[/^claude-/,v["64k"]],[/^glm-5\.2/,v["64k"]],[/^glm-5/,v["64k"]],[/^glm-4\.7/,v["16k"]],[/^matilda-code$/,v["64k"]],[/^matilda$/,v["64k"]],[/^matilda-core$/,v["64k"]],[/^ornith/,v["32k"]],[/^kimi-k2\.5/,v["32k"]]];function Wi(t,e="input"){let n=vt(t),o=e==="output"?Vo:zi;for(let[r,i]of o)if(r.test(n))return i}function Gu(t){let e=vt(t);return Vo.some(([n])=>n.test(e))}function Hi(t,e="input"){return Wi(t,e)}function bt(t,e="input"){return Hi(t,e)??(e==="output"?32e3:131072)}p();p();var zo={image:!0,pdf:!0,audio:!0,video:!0},qi=[[/^gemini-3/,zo],[/^gemini-/,zo],[/^gpt-5/,{image:!0}],[/^gpt-/,{image:!0}],[/^o\d/,{image:!0}],[/^claude-/,{image:!0,pdf:!0}],[/^glm-4\.5v/,{image:!0}],[/^glm-5(?:-|$)/,{}],[/^glm-/,{}],[/^kimi-k2\.5/,{image:!0,video:!0}],[/^kimi-/,{}],[/^doubao-seed(ance|ream)/,{}],[/^doubao-seed/,{image:!0}],[/^doubao-.*(vision|vl)/,{image:!0}],[/^doubao/,{}]];function Mt(t){let e=vt(t);for(let[n,o]of qi)if(n.test(e))return{...o};return{}}p();function Wo(t,e,n={kind:"default"}){for(let o of t)if(Ho(o.value))return{value:o.value,source:o.source};return{value:e,source:n}}function bn(t){for(let e of t)if(Ho(e.value))return{value:e.value,source:e.source}}function Ho(t){return!(t==null||typeof t=="string"&&t.trim()==="")}function _t(t){return{kind:"cli",detail:t}}function Ji(t){return{kind:"env",envKey:t}}function Fe(t){return{kind:"settings",settingsPath:t}}function ge(t,e,n){return{kind:"modelProviders",authType:t,modelId:e,detail:n}}function Mn(t){return{kind:"default",detail:t}}function kt(t){return{kind:"computed",detail:t}}function wt(t,e,n){let o=t[e];return{value:o!==void 0?n?n(o):o:void 0,source:Ji(e)}}function N(t,e){return{value:t,source:e}}p();var me=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","openAIRequestProfile"],qo=["model","apiKey","apiKeyEnvKey","baseUrl"],xt=[...qo,...me],Jo={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","MATILDA_MODEL"]}},Yo={openai:it};var he="MATILDA_API_KEY",Yi="matilda-code-1.0";function Xi(t,e){if(!t)return!0;try{let{hostname:n}=new URL(t);return n==="matilda.maincode.com"||n.endsWith(".matilda.maincode.com")||Pe(t,e)}catch{return!1}}function Qi(t,e,n,o){if(o?.timeout!==void 0)return;let r=t.MATILDA_CODE_API_TIMEOUT_MS;if(r===void 0)return;let i=Number(r);Number.isFinite(i)&&i>0&&(e.timeout=Math.floor(i),n.timeout={kind:"env",envKey:"MATILDA_CODE_API_TIMEOUT_MS"})}function nc(t){let{authType:e,cli:n,settings:o,env:r,modelProvider:i,proxy:s}=t,a=[],l={},c=e?Jo[e]:{model:[],apiKey:[],baseUrl:[]},u=[];e&&i&&u.push(N(i.id,ge(e,i.id,"model.id"))),n?.model&&u.push(N(n.model,_t("--model"))),e==="openai"&&r[he]&&!r.OPENAI_MODEL&&!r.MATILDA_MODEL&&u.push(N(Yi,{kind:"env",envKey:he}));for(let b of c.model)u.push(wt(r,b));o?.model&&u.push(N(o.model,Fe("model.name")));let f=e?Yo[e]:"",d=Wo(u,f,Mn(f));l.model=d.source;let m=[];if(e&&i?.envKey){let b=r[i.envKey];b&&m.push(N(b,{kind:"env",envKey:i.envKey,via:ge(e,i.id,"envKey")}))}if(n?.apiKey&&m.push(N(n.apiKey,_t("--openaiApiKey"))),!i?.envKey){let b=r[he];e==="openai"&&b&&Xi(r.OPENAI_BASE_URL,r)&&m.push(N(b,{kind:"env",envKey:he}));for(let x of c.apiKey)m.push(wt(r,x))}o?.apiKey&&m.push(N(o.apiKey,Fe("security.auth.apiKey")));let h=bn(m);h&&(l.apiKey=h.source);let g=[];e&&i?.baseUrl&&g.push(N(i.baseUrl,ge(e,i.id,"baseUrl"))),n?.baseUrl&&g.push(N(n.baseUrl,_t("--openaiBaseUrl"))),e==="openai"&&r[he]&&!r.OPENAI_BASE_URL&&g.push(N(K(r),{kind:"env",envKey:he}));for(let b of c.baseUrl)g.push(wt(r,b));o?.baseUrl&&g.push(N(o.baseUrl,Fe("security.auth.baseUrl")));let C=bn(g)??(e==="openai"?{value:K(r),source:Mn("the configured Matilda endpoint")}:void 0);C&&(l.baseUrl=C.source);let T;e&&i?.envKey&&(T=i.envKey,l.apiKeyEnvKey={...ge(e,i.id,"envKey"),envKey:i.envKey});let S=It(o?.generationConfig,i?.generationConfig,e,i?.id??d.value,r),R=S.config;Object.assign(l,S.sources);let w={authType:e,model:d.value||"",apiKey:h?.value,apiKeyEnvKey:T,baseUrl:C?.value,proxy:s,...R};return s&&(l.proxy=kt("Config.getProxy()")),l.authType=kt("provided by caller"),{config:w,sources:l,warnings:a}}function It(t,e,n,o,r){let i={},s=Zi(t,e,n,o,i);return Qi(r,s,i,e),{config:s,sources:i}}function Zi(t,e,n,o,r){let i={};for(let s of me)n&&e&&s in e?(i[s]=e[s],r[s]=ge(n,o||"",`generationConfig.${s}`)):t&&s in t&&(i[s]=t[s],r[s]=Fe(`model.generationConfig.${s}`));return i.modalities===void 0&&o&&(i.modalities=Mt(o),r.modalities=kt("auto-detected from model")),i}p();var Ot="$runtime|";function sc(t){let e=t;for(;e.startsWith(Ot);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}p();p();var kn=L("MODEL_REGISTRY");function Xo(t){if(Object.values(B).includes(t))return t}function Qo(t,e){return e?`${t}\0${e}`:t}var Pt=class{modelsByAuthType;constructor(e){if(this.modelsByAuthType=new Map,e)for(let[n,o]of Object.entries(e)){let r=Xo(n);if(!r){kn.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(B).join(", ")}. Skipping.`);continue}this.registerAuthTypeModels(r,o)}}registerAuthTypeModels(e,n){let o=new Map;for(let r of n){let i=Qo(r.id,r.baseUrl);if(o.has(i)){kn.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??bt(o.id),modalities:o.generationConfig.modalities??Mt(o.id),baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(e,n,o){let r=this.modelsByAuthType.get(e);if(!r)return;if(o)return r.get(Qo(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){let n=this.modelsByAuthType.get(e);if(!(!n||n.size===0))return Array.from(n.values())[0]}resolveModelConfig(e,n){return this.validateModelConfig(e,n),{...e,authType:n,name:e.name||e.id,baseUrl:e.baseUrl||K(),generationConfig:{...e.generationConfig??{}},capabilities:e.capabilities||{}}}validateModelConfig(e,n){if(!e.id)throw new Error(`Model config in authType '${n}' missing required field: id`)}reloadModels(e){if(this.modelsByAuthType.clear(),e)for(let[n,o]of Object.entries(e)){let r=Xo(n);if(!r){kn.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(B).join(", ")}. Skipping.`);continue}this.registerAuthTypeModels(r,o)}}};var Zo=class t{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;hasManualCredentials=!1;onModelChange;authTypeWasExplicitlyProvided;settingsGenerationConfig;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 Pt(e.modelProvidersConfig),this.onModelChange=e.onModelChange,this._generationConfig={...e.generationConfig||{}},this.generationConfigSources=e.generationConfigSources||{},this.settingsGenerationConfig=t.deepClone(e.settingsGenerationConfig),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,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.hasManualCredentials=e.hasManualCredentials,this.activeRuntimeModelSnapshotId=e.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||it}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(B),o=new Set,r=[];for(let a of n)o.has(a)||(o.add(a),r.push(a));let i=this.getRuntimeModelOption(),s=[];for(let a of r)i&&i.authType===a&&s.push(i),s.push(...this.modelRegistry.getModelsForAuthType(a));return s}hasModel(e,n){return this.modelRegistry.hasModel(e,n)}getResolvedModel(e,n){let o=this.modelRegistry.getModel(e,n);if(o)return{...o,generationConfig:this.resolveEntryGenerationConfig(o).config}}resolveEntryGenerationConfig(e){return It(this.settingsGenerationConfig,e.generationConfig,e.authType,e.id,wn.env)}isManagedMatildaResolvedModel(e){return e?.id===Xt&&e?.envKey===rt&&e?.baseUrl===_e&&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)?Xt:e}getModelDisplayName(e){return this.isManagedMatildaModel(e)?Yn:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,e)?.name??e:e}async setModel(e,n){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)}catch(r){throw this.rollbackToStateSnapshot(o),r}}applyRawModelDerivedDefaults(e){let n=It(this.settingsGenerationConfig,void 0,this.currentAuthType,e,wn.env);this.shouldUpdateModelDerivedDefault("modalities")&&this.applyResolvedField("modalities",n),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this.applyResolvedField("contextWindowSize",n),this.fillContextWindowSize(e))}applyResolvedField(e,n){this._generationConfig[e]=t.deepClone(n.config[e]);let o=n.sources[e];o?this.generationConfigSources[e]=o:delete this.generationConfigSources[e]}fillContextWindowSize(e){this._generationConfig.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=bt(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();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=!s&&!!i.generationConfig.apiKey&&!!a.envKey&&c?.envKey===a.envKey&&c.baseUrl===a.baseUrl,f=u?i.generationConfig.apiKey:void 0,d=u?i.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(a),!this._generationConfig.apiKey&&f&&(this._generationConfig.apiKey=f,d&&(this.generationConfigSources.apiKey=t.deepClone(d))),this.activeRuntimeModelSnapshotId=void 0,this.onModelChange&&await this.onModelChange(e)}catch(s){throw this.rollbackToStateSnapshot(i),s}}buildRuntimeModelSnapshotId(e,n){return`${Ot}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(Ot))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 me)!(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 xt)this.generationConfigSources[e]?.kind==="modelProviders"&&(delete this._generationConfig[e],delete this.generationConfigSources[e])}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=!1}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._generationConfig.apiKey=void 0,this._generationConfig.apiKeyEnvKey=void 0,e.envKey!==void 0){let o=wn.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=this.resolveEntryGenerationConfig(e);for(let o of me)this.applyResolvedField(o,n);this.fillContextWindowSize(e.id)}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 m=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==i.envKey||this._generationConfig.baseUrl!==i.baseUrl),h=o===e&&this._generationConfig.model===n&&!m,g=h?this._generationConfig.apiKey:void 0,C=h&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,T=this.generationConfigSources.baseUrl,S=h&&!!this._generationConfig.baseUrl&&(T?.kind==="cli"||T?.kind==="env"||T?.kind==="settings"),R=S?this._generationConfig.baseUrl:void 0,w=S&&T?{...T}:void 0;this.applyResolvedModelDefaults(i),h&&!this._generationConfig.apiKey&&g&&(this._generationConfig.apiKey=g,C&&(this.generationConfigSources.apiKey=C)),R&&(this._generationConfig.baseUrl=R,w&&(this.generationConfigSources.baseUrl=w)),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 f=this.modelRegistry.getDefaultModelForAuthType(e);if(f){this.applyResolvedModelDefaults(f),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{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),this.onModelChange&&await this.onModelChange(n.authType)}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)}};p();import{randomUUID as bs}from"node:crypto";import{mkdirSync as Ms,readFileSync as _s}from"node:fs";import{dirname as ks,join as ws}from"node:path";p();p();import{randomBytes as es,createHash as ts}from"node:crypto";import{setTimeout as ns}from"node:timers/promises";var os="urn:ietf:params:oauth:grant-type:device_code";function er(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function In(){let t=es(32).toString("base64url"),e=ts("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function Ce(t,e){let n=typeof t=="object"&&t!==null?t:{};if(typeof n.access_token!="string"||n.access_token==="")throw new Error("The token response has no access token");return{accessToken:n.access_token,refreshToken:n.refresh_token??e?.refreshToken,expiresAt:Date.now()+(n.expires_in??3600)*1e3,idToken:n.id_token??e?.idToken}}var rs=15e3;async function On(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!er(n.hostname))throw new Error(`Refusing OAuth discovery over insecure transport: ${n.origin}`);let o=await fetch(n,{headers:{accept:"application/json"},signal:AbortSignal.timeout(rs)});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}}var is=15e3,xn="Device code expired: restart the sign-in";async function Pn(t,e,n={}){let o;try{o=await fetch(t,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,scope:e.scope??"openid offline_access"}),signal:or(AbortSignal.timeout(is),n.signal)})}catch(i){throw rr(i,n.signal)?new Error("The device code request timed out"):i}if(!o.ok)throw new Error(`Device code request failed (${o.status})`);let r=await o.json();return{deviceCode:r.device_code,userCode:r.user_code,verificationUri:r.verification_uri,verificationUriComplete:r.verification_uri_complete,expiresAt:Date.now()+r.expires_in*1e3,interval:r.interval??5}}async function tr(t,e,n={}){let o=await fetch(t,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:os,client_id:e.clientId,device_code:e.deviceCode}),signal:n.signal});if(o.ok)return{kind:"authorized",tokens:Ce(await o.json())};let r=await o.json().catch(()=>({})),i=typeof r.error=="string"?r.error:"unknown";switch(i){case"authorization_pending":return{kind:"pending"};case"slow_down":return{kind:"slow_down"};default:return{kind:"error",error:i}}}async function nr(t,e,n={}){let o=e.interval*1e3;try{for(;Date.now()<e.expiresAt;){await ns(Math.min(o,e.expiresAt-Date.now()),void 0,{signal:n.signal});let r=e.expiresAt-Date.now();if(r<=0)break;let i=await tr(t,e,{signal:or(AbortSignal.timeout(r),n.signal)});if(i.kind==="authorized")return i.tokens;if(i.kind!=="pending"){if(i.kind==="slow_down"){o+=5e3;continue}switch(i.error){case"expired_token":throw new Error(xn);case"access_denied":throw new Error("User denied the authorization request");default:throw new Error(`Device flow error: ${i.error}`)}}}}catch(r){throw rr(r,n.signal)?new Error(xn):r}throw new Error(xn)}function or(t,e){return e?AbortSignal.any([t,e]):t}function rr(t,e){return!e?.aborted&&t instanceof Error&&t.name==="TimeoutError"}p();import{randomBytes as ss}from"node:crypto";import{promises as ye,openSync as as,closeSync as ls,unlinkSync as sr,statSync as us}from"node:fs";import{dirname as cs}from"node:path";var ir=new Map,ds=2e4,ps=3e4,fs=50;function Dn(t,e={}){let n=async()=>{try{let s=await ye.readFile(t,"utf8"),a=JSON.parse(s);return a&&typeof a=="object"?a:{}}catch(s){if(s.code==="ENOENT")return{};throw s}},o=async(s,a)=>{await ye.mkdir(cs(t),{recursive:!0});let l=`${t}.${process.pid}.${ss(4).toString("hex")}.tmp`;try{await ye.writeFile(l,JSON.stringify(s,null,2),{mode:384}),a?.throwIfAborted(),await ye.rename(l,t)}catch(c){throw await ye.rm(l,{force:!0}).catch(()=>{}),c}await ye.chmod(t,384).catch(()=>{})},r=(s,a={})=>{let c=(ir.get(t)??Promise.resolve()).then(async()=>{a.signal?.throwIfAborted();let u=await n(),f=!1;for(let[d,m]of Object.entries(s)){if(m===null){if(!(d in u))continue;delete u[d]}else{if(u[d]===m)continue;u[d]=m}f=!0}f&&await o(u,a.signal),a.onCommit?.()});return ir.set(t,c.catch(()=>{})),c};return{store:{async get(s){return(await n())[s]??null},set:(s,a,l)=>r({[s]:a},l),remove:(s,a)=>r({[s]:null},a)},lock:gs(`${t}.lock`,e.lockTimeoutMs??ds),update:r}}function gs(t,e){let n=Promise.resolve();return o=>{let r=n.then(async()=>{await ms(t,e);try{return await o()}finally{hs(t)}});return n=r.then(()=>{},()=>{}),r}}async function ms(t,e){let n=Date.now()+e;for(;;)try{ls(as(t,"wx"));return}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-us(t).mtimeMs>ps){sr(t);continue}}catch{continue}if(Date.now()>n)throw Object.assign(new Error(`Timed out acquiring credential lock at ${t}`),{code:"ETIMEDOUT"});await Cs(fs)}}function hs(t){try{sr(t)}catch{}}function Cs(t){return new Promise(e=>setTimeout(e,t))}p();var Te=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function Un(t){let e=t.storageKey??"default",n=t.fetchImpl??fetch,o=t.expirySkewMs??6e4,r=t.refreshTimeoutMs??15e3,i=null,s=async()=>{let c=await t.store.get(e);if(!c)return null;try{let u=JSON.parse(c);return u.accessToken?u:null}catch{return null}},a=c=>c.expiresAt-Date.now()>o,l=c=>t.lock(async()=>{let u=await s()??c;if(u.accessToken!==c.accessToken&&a(u))return u.accessToken;if(!u.refreshToken)throw new Te("No refresh token available \u2014 sign in again.");let f;try{let m=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:u.refreshToken}),signal:AbortSignal.timeout(r)});if(!m.ok){let h=await m.text().catch(()=>"");throw m.status>=400&&m.status<500&&ys(h)==="invalid_grant"?(await t.store.remove(e),new Te):Object.assign(new Error(`Token refresh failed (${m.status})`),{status:m.status})}f=await m.json()}catch(m){throw m?.name==="TimeoutError"?Object.assign(new Error(`Token refresh timed out after ${r} ms`),{code:"ETIMEDOUT",cause:m}):m}let d=Ce(f,u);return await t.store.set(e,JSON.stringify(d)),d.accessToken});return{async getAccessToken(c){let u=await s();if(!u)throw new Te("Not signed in.");return!c?.forceRefresh&&a(u)?u.accessToken:(i||(i=l(u).finally(()=>{i=null})),i)}}}function ys(t){try{return JSON.parse(t).error}catch{return}}p();import{createServer as Ts}from"node:http";import{randomBytes as Ss}from"node:crypto";async function Dt(t){if(t.transport.kind==="device")return Es(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=g=>t.onEvent?.(g),{codeVerifier:n,codeChallenge:o}=In(),r=Ss(16).toString("hex"),i=t.timeoutMs??5*60*1e3,s=t.transport.successRedirect,a=t.transport.port;e({type:"state",status:"idle"});let l,c,u=new Promise((g,C)=>{l=g,c=C});u.catch(()=>{});let f=Ts((g,C)=>{let T=new URL(g.url??"/","http://127.0.0.1");if(T.pathname!=="/callback"){C.writeHead(404).end();return}let S=T.searchParams.get("error"),R=T.searchParams.get("state"),w=T.searchParams.get("code");if(S){let b=T.searchParams.get("error_description"),x=b?`OAuth error: ${S} (${b})`:`OAuth error: ${S}`;C.writeHead(400,{"content-type":"text/plain; charset=utf-8"}).end(`Sign-in failed: ${S}
|
|
16
|
-
`,()=>c(new Error(x)));return}if(R!==r){C.writeHead(400).end("State mismatch"),c(new Error("OAuth state mismatch"));return}if(!w){C.writeHead(400).end("Missing authorization code");return}As(C,s,()=>l(w))}),d=await new Promise((g,C)=>{f.once("error",C),f.listen(a??0,"127.0.0.1",()=>{g(f.address().port)})}),m=setTimeout(()=>c(new Error("Login timed out \u2014 the browser never reached the local callback. The hosted success page is not a completed sign-in.")),i),h=()=>c(new Error("Login aborted"));t.signal?.addEventListener("abort",h,{once:!0}),t.signal?.aborted&&h();try{t.signal?.throwIfAborted();let g=`http://127.0.0.1:${d}/callback`,C=new URL(t.metadata.authorization_endpoint);C.searchParams.set("client_id",t.clientId),C.searchParams.set("response_type","code"),C.searchParams.set("redirect_uri",g),C.searchParams.set("code_challenge",o),C.searchParams.set("code_challenge_method","S256"),C.searchParams.set("state",r),C.searchParams.set("prompt","select_account"),C.searchParams.set("scope",t.scope??"openid offline_access");let T=C.toString();e({type:"authorize_url",url:T}),e({type:"state",status:"awaiting_user"}),t.openBrowser&&await t.openBrowser(T);let S=await u;await ar(f),e({type:"state",status:"exchanging"});let R=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:S,code_verifier:n,redirect_uri:g}),signal:t.signal});if(!R.ok){let b=await R.text().catch(()=>"");throw new Error(`Token exchange failed (${R.status}): ${b}`)}let w=Ce(await R.json());return e({type:"state",status:"authenticated"}),w}catch(g){throw e({type:"state",status:"error"}),t.signal?.aborted?new Error("Login aborted"):g}finally{clearTimeout(m),t.signal?.removeEventListener("abort",h),await ar(f)}}async function Es(t){let e=t.metadata.device_authorization_endpoint;if(!e)throw new Error("The authorization server does not offer device sign-in");if(t.signal?.aborted)throw new Error("Login aborted");let n=o=>t.onEvent?.(o);n({type:"state",status:"idle"});try{let o=await Pn(e,{clientId:t.clientId,scope:t.scope},{signal:t.signal});n({type:"user_code",userCode:o.userCode,verificationUri:o.verificationUri,verificationUriComplete:o.verificationUriComplete}),n({type:"state",status:"awaiting_user"});let r=await nr(t.metadata.token_endpoint,{clientId:t.clientId,deviceCode:o.deviceCode,interval:o.interval,expiresAt:o.expiresAt},{signal:t.signal});return n({type:"state",status:"authenticated"}),r}catch(o){throw n({type:"state",status:"error"}),t.signal?.aborted?new Error("Login aborted"):o}}function ar(t){return t.listening?new Promise(e=>{t.close(()=>e()),t.closeAllConnections()}):Promise.resolve()}function As(t,e,n){t.writeHead(302,{location:e}).end(n)}p();var Rs=["www-browser"];function vs(t){let e=t.replace(/\\/g,"/").split("/").pop();return!!e&&Rs.includes(e)}function lr(t={}){let n=process.env.BROWSER?.trim()?.match(/^\S+/)?.[0];if(!t.ignoreBrowserBlocklist&&process.platform!=="win32"&&n&&vs(n)||process.env.CI||process.env.DEBIAN_FRONTEND==="noninteractive")return!1;let o=!!process.env.SSH_CONNECTION;return!(process.platform==="linux"&&!["DISPLAY","WAYLAND_DISPLAY","MIR_SOCKET"].some(s=>!!process.env[s])||o&&process.platform!=="linux")}var Ee="matilda-code",cr="matilda-desktop",dr="openid profile email offline_access",Ut="MATILDA_API_KEY",xs="matilda";function Ae(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function pr(){return ws(Ye.getGlobalMatildaDir(),"matilda-auth.json")}function $e(){let t=pr();return Ms(ks(t),{recursive:!0}),Dn(t)}function Is(t){return t==="desktop"}function Be(t){return t?.clientId?t.clientId:Is(t?.channel)?cr:Ee}function Ge(t){return`matilda:${t}`}function Lt(t){return`${Ge(t)}:refresh-rejected`}function je(t){return t===Ee?[Ge(t),xs]:[Ge(t)]}function fr(){try{let t=_s(pr(),"utf8");return JSON.parse(t)}catch{return{}}}function Nt(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 Ln(t,e){return Ae(t)===Ae(e)}function Os(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 gr(t,e){let n=Os(t.idToken);return{accessToken:t.accessToken,accessTokenExpiresAt:t.expiresAt,refreshToken:t.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:e}}var ur=new Map;async function Fn(t,e={}){let n=ur.get(t);if(n)return n;try{let o=await On(t);return ur.set(t,o),o}catch(o){let r=e.requireReachable&&(De(o,t)??gn(o,t));if(r)throw r;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 Kn(t){try{let e=fr(),n=Be(t);for(let o of je(n)){let r=Nt(e[o]);if(r)return r}return null}catch{return null}}function mr(t){let e=Kn(t);return!e||t?.baseUrl&&!Ln(e.baseUrl,t.baseUrl)?null:e}function Gn(t){return mr(t)!==null}async function hr(t,e){for(let n of e){let o=await t.get(n);if(Nt(o))return o}return null}async function Ps(t,e){let n=Be(t),o=je(n),{store:r,lock:i}=$e();await i(async()=>{let s=await hr(r,o);if(!(s!==null&&s!==e)){for(let a of o)await r.remove(a);await r.set(Lt(n),"1")}})}function Ds(t){return t instanceof Error?t.code==="invalid_grant"||t.name==="InvalidGrantError"?!0:t.message==="Token refresh failed (401)":!1}function Se(t){Nn({authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:t.occurrenceCount},{baseUrl:t.baseUrl,token:t.token}).catch(()=>{})}async function Cr(t,e,n={}){let o=Be(e),r=Ge(o),i={[r]:JSON.stringify(t),[Lt(o)]:null};for(let l of je(o))l!==r&&(i[l]=null);let{lock:s,update:a}=$e();await s(()=>a(i,{signal:n.signal}))}async function Us(t,e){for(let n of je(e))await t.remove(n);await t.remove(Lt(e))}var Ke="matilda:api-key";function yr(){let t=fr()[Ke];if(!t)return null;try{let{apiKey:e,baseUrl:n}=JSON.parse(t);return typeof e=="string"&&e.length>0&&typeof n=="string"?{apiKey:e,baseUrl:n}:null}catch{return null}}function Ft(t){let e=yr();return e&&Ln(e.baseUrl,t)?e.apiKey:void 0}async function Ns(t){let e=bs(),n=JSON.stringify(t?{...t,saveId:e}:{saveId:e}),{store:o,lock:r,update:i}=$e(),s=await r(async()=>{let a=await o.get(Ke);return(t||a!==null)&&await i({[Ke]:n}),a});return()=>r(async()=>{await o.get(Ke)===n&&await i({[Ke]:s})})}function Ls(t){let e=Kn(t);return e?{authenticated:!0,userId:e.userId,email:e.email,displayName:e.displayName,baseUrl:e.baseUrl,accessTokenExpiresAt:e.accessTokenExpiresAt}:{authenticated:!1}}async function fd(t){let e={channel:t?.channel,clientId:t?.clientId},{store:n,lock:o}=$e(),r=await o(async()=>{let s=Kn(e);return await Us(n,Be(e)),s}),i=yr()!==null;if(await Ns(null),r?.accessToken){let s=Ae(r.baseUrl);await fetch(`${s}/api/auth/logout`,{method:"POST",headers:{authorization:`Bearer ${r.accessToken}`,"content-type":"application/json"},body:JSON.stringify(r.refreshToken?{refreshToken:r.refreshToken}:{}),signal:t?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}return!!r||i}function Tr(t){return!t||t===Ut}function Sr(t){let{baseUrl:e,channel:n,apiKey:o,apiKeyEnvKey:r}=t;if(Gn({baseUrl:e,channel:n})){let i=Ls({channel:n});return{kind:"sign-in",account:i.authenticated?i.email??i.displayName??i.userId:void 0}}return o?.value?{kind:"api-key",from:o.from}:Tr(r)&&process.env[Ut]?{kind:"api-key",from:Ut}:Ft(e)!==void 0?{kind:"api-key",from:"saved"}:{kind:"none"}}async function Er(t){let e=Be(t),n=Ge(e),o=mr({baseUrl:t?.baseUrl,channel:t?.channel,clientId:e});if(!o)return t?.fallbackAccessToken||(Tr(t?.apiKeyEnvKey)?process.env[Ut]:void 0)||t?.baseUrl&&Ft(t.baseUrl)||"";let r=Ae(o.baseUrl),i=await Fn(r),{store:s,lock:a}=$e(),{manager:l,startedFrom:c}=Fs(s,a,i.token_endpoint,o.baseUrl,e,n,t?.signal),u=e===Ee&&(!!t?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=3e5),f;try{f=await l.getAccessToken({forceRefresh:t?.forceRefresh})}catch(d){throw u&&Se({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"}),Ds(d)?d instanceof Je?d:(e===cr&&await Ps({channel:t?.channel,clientId:e},c()),new Je({cause:d})):De(d,r)??gn(d,r)??d}return u&&Se({baseUrl:o.baseUrl,token:f,authStage:"refresh",authOutcome:"succeeded"}),f}function Fs(t,e,n,o,r,i,s){let a=je(r),l=(m,h)=>{let g=[h?.signal,s].filter(C=>C instanceof AbortSignal);return fetch(m,{...h,signal:g.length>1?AbortSignal.any(g):g[0]})},c=m=>hr(t,m===i?a:[m]),u=null;return{manager:Un({tokenEndpoint:n,clientId:r,store:{get:async m=>{let h=await c(m),g=Nt(h);if(u=g&&Ln(g.baseUrl,o)?h:null,!u||!g?.accessToken)return null;let C={accessToken:g.accessToken,refreshToken:g.refreshToken,expiresAt:g.accessTokenExpiresAt};return JSON.stringify(C)},set:async(m,h)=>{let g=await c(m);if(g===null||g!==u)throw new Je;let C=JSON.parse(h),T=Nt(g)??{},S={...T,accessToken:C.accessToken,accessTokenExpiresAt:C.expiresAt,refreshToken:C.refreshToken??T.refreshToken??"",baseUrl:T.baseUrl??o};await t.set(i,JSON.stringify(S)),await t.remove(Lt(r));for(let R of a)R!==i&&await t.remove(R)},remove:async m=>{if(await c(m)!==u)return;let h=m===i?a:[m];for(let g of h)await t.remove(g)}},storageKey:i,lock:e,fetchImpl:l,expirySkewMs:3e5}),startedFrom:()=>u}}function Ks(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&lr()}async function gd(t){let e=Ae(t.baseUrl),n=await Fn(e,{requireReachable:!0}),o="",r=0,i=0,s={},a=f=>{s[f]=(s[f]??0)+1},c=await(f=>(r+=1,Dt({metadata:n,clientId:Ee,scope:f,transport:{kind:"loopback",successRedirect:`${e}/api/auth/oauth/success?client_id=${encodeURIComponent(Ee)}`},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||!Ks()){a("skipped");return}try{let{default:m}=await import("./open-QQ7FWG4A.js");(await m(d)).once("error",()=>{}),a("succeeded")}catch{a("failed")}}})))(dr).catch(f=>{throw De(f,e)??f}),u=gr(c,t.baseUrl);await Cr(u),Se({baseUrl:t.baseUrl,token:u.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:r});for(let[f,d]of Object.entries(s))Se({baseUrl:t.baseUrl,token:u.accessToken,authStage:"browser_opened",authOutcome:f,occurrenceCount:d});return i>0&&Se({baseUrl:t.baseUrl,token:u.accessToken,authStage:"callback_received",authOutcome:"succeeded",occurrenceCount:i}),Se({baseUrl:t.baseUrl,token:u.accessToken,authStage:"token_persisted",authOutcome:"succeeded"}),{...u,authorizeUrl:o}}async function md(t){let e=Ae(t.baseUrl),n=await Fn(e,{requireReachable:!0}),o=await Dt({metadata:n,clientId:Ee,scope:dr,transport:{kind:"device"},signal:t.signal,onEvent:i=>{i.type==="user_code"&&t.onDeviceCode({userCode:i.userCode,verificationUri:i.verificationUri,verificationUriComplete:i.verificationUriComplete})}}).catch(i=>{throw De(i,e)??i}),r=gr(o,t.baseUrl);return await Cr(r),r}p();p();p();function Kt(t){return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="object"&&"message"in t.error}function Ar(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}p();function Rr(t){let e=Math.max(1,t.attempt),n=Math.min(t.maxDelayMs,2147483647),o=Math.min(e-1,31),r=Math.min(t.initialDelayMs*Math.pow(2,o),n),s=(t.retryAfterMode??"ignore")==="ignore"?null:Gs(t.error);if(s!==null&&s>0){let u=Math.min(t.retryAfterMaxDelayMs??t.maxDelayMs,2147483647),f=Math.min(s,u);return Math.max(r,f)}let a=t.jitterRatio??0;if(a<=0)return r;let l=t.random??Math.random,c=r*a*(l()*2-1);return Math.min(Math.max(0,r+c),n)}function Gs(t){let e=vr(t,"retry-after")??$s(t,"retry-after");if(e===null)return null;let n=e.trim();if(/^\d+(\.\d+)?$/.test(n)){let i=Number(n);if(Number.isFinite(i)&&i>=0)return Math.min(i*1e3,2147483647)}let o=Date.parse(n);if(!Number.isFinite(o))return null;let r=o-Date.now();return r>0?Math.min(r,2147483647):0}function vr(t,e){if(!Bs(t))return null;let{headers:n}=t;if(typeof n.get=="function"){let r=n.get(e);return typeof r=="string"?r:null}if(typeof n!="object"||n===null)return null;let o=e.toLowerCase();for(let[r,i]of Object.entries(n))if(r.toLowerCase()===o)return typeof i=="string"?i:null;return null}function $s(t,e){return js(t)?vr(t.response,e):null}function Bs(t){return typeof t=="object"&&t!==null&&"headers"in t&&t.headers!=null}function js(t){return typeof t=="object"&&t!==null&&"response"in t&&typeof t.response=="object"&&t.response!==null&&"headers"in t.response&&t.response.headers!=null}var Vs=new Set([429,503,1302,1305]);function $n(t,e){if(Bn(t))return!1;let n=Ws(t);return n===null?!1:!!(Vs.has(n)||e&&e.includes(n))}function Bn(t){return zs(t)==="insufficient_quota"}function zs(t){let e=Mr(t)?.code;if(e!==void 0)return e;let n=typeof t=="object"&&t!==null&&"code"in t?t.code:void 0;return typeof n=="string"||typeof n=="number"?n:void 0}function br(t){let e=$(t),n=Mr(t),o=_r(t),r=o?.includes("event:error")||o?.includes("HTTP_STATUS/")?"sse":e!==void 0?"http":"unknown";return{...e!==void 0?{statusCode:e}:{},...n?.code!==void 0?{providerCode:String(n.code)}:{},...n?.message!==void 0?{providerMessage:n.message}:{},...n?.requestId!==void 0?{requestId:n.requestId}:{},transport:r}}function bd(t,e){return Rr({attempt:t,initialDelayMs:e.initialDelayMs,maxDelayMs:e.maxDelayMs,retryAfterMode:"minimum",retryAfterMaxDelayMs:e.maxDelayMs,error:e.error})}function Ws(t){if(Kt(t)){let n=Number(t.error.code);if(Number.isFinite(n)&&n>0)return n}let e=t instanceof Error?t.message:typeof t=="string"?t:null;if(e){let n=e.indexOf("{");if(n!==-1)try{let o=JSON.parse(e.substring(n));if(Kt(o)){let r=Number(o.error.code);if(Number.isFinite(r)&&r>0)return r}}catch{}}if(Ar(t)&&typeof t.status=="number")return t.status;if(t instanceof Error&&"status"in t){let n=t.status;if(typeof n=="number")return n}return $(t)??null}function Mr(t){for(let e of Hs(t)){if(typeof e!="object"||e===null)continue;let n=e,o=e.error,i=(typeof o=="object"&&o!==null?o:void 0)??n,s=typeof i.code=="string"||typeof i.code=="number"?i.code:void 0,a=typeof i.message=="string"?i.message:void 0,l=typeof i.request_id=="string"?i.request_id:typeof i.requestId=="string"?i.requestId:typeof n.request_id=="string"?n.request_id:typeof n.requestId=="string"?n.requestId:void 0;if(s!==void 0||a!==void 0||l!==void 0)return{code:s,message:a,requestId:l}}return Kt(t)?{code:t.error.code,message:t.error.message}:null}function Hs(t){let e=_r(t);if(!e)return[];let n=[];for(let i of e.split(/\r?\n/)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(!s||s==="[DONE]"))try{n.push(JSON.parse(s))}catch{}}if(n.length>0)return n;let o=e.indexOf("{"),r=e.lastIndexOf("}");if(o!==-1&&r>o)try{n.push(JSON.parse(e.slice(o,r+1)))}catch{}return n}function _r(t){return t instanceof Error?t.message:typeof t=="string"?t:null}function qs(t,e={}){if(Js(t))return{kind:"abort",diagnosis:"fail-fast",reason:"aborted"};let n=br(t),o=n.statusCode,r=ta(t),i=n.providerCode??r.providerCode,s=n.providerMessage??r.providerMessage,a=n.requestId??r.requestId,l={...o!==void 0?{statusCode:o}:{},...i!==void 0?{providerCode:i}:{},...s!==void 0?{providerMessage:s}:{},...a!==void 0?{requestId:a}:{}};if(ea(i))return{kind:"provider-business",diagnosis:"fail-fast",reason:"allocated-quota-exceeded",...l};if(Bn(t))return{kind:"provider-business",diagnosis:"fail-fast",reason:"insufficient-quota",...l};if($n(t,e.extraRetryErrorCodes))return{kind:n.transport==="sse"?"sse-provider":o!==void 0?"http":"provider",diagnosis:"retryable",reason:"rate-limit",...l};let c=Xs(t);if(c!==void 0&&(o===void 0||o>=500))return{kind:"transport",diagnosis:"retryable",reason:"transport-error",transportCode:c,...o!==void 0?{statusCode:o}:{}};if(o!==void 0){let u=n.transport==="sse"?"sse-provider":"http";return o===529?{kind:u,diagnosis:"retryable",reason:"capacity-overload",...l}:o===401||o===403?{kind:u,diagnosis:"fail-fast",reason:"auth-error",...l}:o>=400&&o<500?{kind:u,diagnosis:"fail-fast",reason:"client-error",...l}:o>=500&&o<600?{kind:u,diagnosis:"retryable",reason:"server-error",...l}:{kind:u,diagnosis:"unknown",reason:"http-status",...l}}return i==="upstream_unavailable"||i==="upstream_timeout"||i==="incomplete_stream"?{kind:"sse-provider",diagnosis:"retryable",reason:"server-error",...l}:{kind:"unknown",diagnosis:"unknown",reason:"unclassified",...l}}function xd(t){let e=t.statusCode??Number(t.providerCode);return t.kind!=="transport"&&t.diagnosis!=="fail-fast"&&(e>=500&&e<600||t.kind==="sse-provider"&&t.reason==="server-error"&&t.diagnosis==="retryable")}function kr(t,e){return $n(t,e)||qs(t,{extraRetryErrorCodes:e}).diagnosis==="retryable"}function Js(t){return qn(t)?!0:t instanceof Error&&t.name==="CanceledError"}var Ys=5;function Xs(t){let e=t;for(let n=0;n<=Ys;n++){if(typeof e!="object"||e===null)return;let o=e.code;if(typeof o=="string"&&Qs(o))return o;e=e instanceof Error?e.cause:void 0}}function Qs(t){return Zs.has(t)}var Zs=new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET","ConnectionClosed","ConnectionRefused","ConnectionReset","ConnectionTimedOut","FailedToOpenSocket","HostUnreachable","NetworkUnreachable"]);function ea(t){return t==="Throttling.AllocationQuota"}function ta(t){if(typeof t!="object"||t===null)return{};let e=t,n=typeof e.code=="string"||typeof e.code=="number"?String(e.code):void 0,o=typeof e.code=="number"&&e.code>=100&&e.code<600,r=t instanceof Error&&n?.startsWith("ERR_")||o?void 0:n,i=typeof e.request_id=="string"?e.request_id:typeof e.requestId=="string"?e.requestId:void 0,s=typeof e.message=="string"&&(!(t instanceof Error)||r!==void 0||i!==void 0)?e.message:void 0;return{...r!==void 0?{providerCode:r}:{},...s!==void 0?{providerMessage:s}:{},...i!==void 0?{requestId:i}:{}}}var B=(e=>(e.USE_OPENAI="openai",e))(B||{});function wr(t,e){if(delete t.usesMatildaSignIn,delete t.usesMatildaSavedApiKey,!fn(t))return;let n=t.baseUrl||K();Gn({baseUrl:n,channel:e})&&(t.usesMatildaSignIn=!0),!t.apiKey&&Ft(n)!==void 0&&(t.usesMatildaSavedApiKey=!0)}function Gd(t,e={}){let n=t.apiKey?{value:t.apiKey,from:e.apiKeyFrom??"config"}:void 0;return fn(t)?Sr({baseUrl:t.baseUrl||K(),channel:e.channel,apiKey:n,apiKeyEnvKey:t.apiKeyEnvKey}):n&&{kind:"api-key",from:n.from}}async function na(t,e){try{await Er({baseUrl:t.baseUrl||K(),channel:e})}catch(n){if(!kr(n))throw n}}function jn(t,e,n){t[e]=n}function oa(t,e){return t?.[e]}function $d(t,e,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:e,proxy:t?.getProxy()};jn(i,"authType",{kind:"computed",detail:"provided by caller"}),t?.getProxy()&&jn(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=u=>oa(o,u)??{kind:"unknown"};for(let u of xt)n&&u in n&&!i[u]&&jn(i,u,l(u));wr(a,t.getChannel());let c=_n(a,s);if(!c.valid)throw new Error(c.errors.map(u=>u.message).join(`
|
|
17
|
-
`));return{config:a,sources:i}}function _n(t,e=!1){let n=[];if(!t.apiKey&&!t.usesMatildaSignIn&&!t.usesMatildaSavedApiKey)if(e)n.push(new St(t.authType,t.model,t.apiKeyEnvKey));else{let o=t.apiKeyEnvKey||Bo(t.authType);n.push(new At({authType:t.authType,model:t.model,baseUrl:t.baseUrl,envKey:o}))}if(!t.model)if(e)n.push(new Et(t.authType));else{let o=jo(t.authType);n.push(new Rt({authType:t.authType,envKey:o}))}return{valid:n.length===0,errors:n}}function ra(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 Bd(t,e,n){vn(t,e.getOrganizationId?.(),e.getCodeCreditLimitMinor?.()),$o(t.customHeaders),wr(t,e.getChannel()),t.usesMatildaSignIn&&await na(t,e.getChannel());let o=_n(t,!1);if(!o.valid)throw new Error(o.errors.map(s=>s.message).join(`
|
|
18
|
-
`));let r=t.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai"){let{applyDeclaredInputModalities:s,createOpenAIContentGenerator:a}=await import("./openaiContentGenerator-2NF5JGUC.js");await s(t,e,n),i=a(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=ra(s);throw a?new Error(`Matilda was updated in the background and needs to be restarted.
|
|
19
|
-
Please exit and restart Matilda to use the '${r}' provider.`,{cause:a}):s}return new Le(i,e,t)}var ia=["x-matilda-client-name","x-matilda-client-version","x-matilda-client-operating-system","x-matilda-client-architecture","x-matilda-client-distribution-channel","x-matilda-client-release-channel"],sa=new Set([...ia,...Hn]),aa=new Set(["VSCode","ACP","SDK","CI"]),Re="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",la="[A-Za-z][0-9A-Za-z-]{0,23}",xr="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",ua=new RegExp(`^${Re}(?:-${la}(?:\\.${xr})+)?$`),ca=63,da=new RegExp(`^${Re}$`),pa=new RegExp(`^${Re}-preview\\.(?:0|[1-9]\\d{0,11})$`),fa=new RegExp(`^${Re}-canary\\.(?:0|[1-9]\\d{0,11})$`),ga=new RegExp(`^${Re}-nightly\\.(?:0|[1-9]\\d{0,11})\\.[0-9A-Fa-f]{7,12}$`),ma=new RegExp(`^${Re}-(preview|canary|nightly|development|internal)(?:\\.${xr})+$`);function ha(t){return t==="desktop"?"desktop":t===void 0||aa.has(t)?"code_cli":"unknown"}function Ca(t){if(t==="android")return"android";if(t==="darwin")return"macos";if(t==="win32")return"windows";if(t==="linux")return"linux"}function ya(t){if(t==="x64")return"x64";if(t==="arm64")return"arm64"}function Ta(t){if(t===void 0)return"npm";if(t==="desktop")return"direct-download";if(t==="VSCode")return"vscode-marketplace"}function Sa(t,e){if(e==="desktop")return"matilda-desktop";if(t==="VSCode")return"matilda-vscode";if(e==="code_cli")return"matilda-code"}function Ea(t){if(typeof t=="string"&&!(t.length>ca||!ua.test(t)))return t}function Aa(t){if(t!==void 0)return da.test(t)?"stable":pa.test(t)?"preview":fa.test(t)?"canary":ga.test(t)?"nightly":ma.exec(t)?.[1]}function Ir(t,e=process.platform,n=process.arch){let o=t.getChannel?.(),r=ha(o),i=Ea(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:t.getCliVersion?.()),s=Aa(i),a=Ca(e),l=ya(n),c=Ta(o),u=Sa(o,r);return{...u?{"x-matilda-client-name":u}:{},...i?{"x-matilda-client-version":i}:{},...a?{"x-matilda-client-operating-system":a}:{},...l?{"x-matilda-client-architecture":l}:{},...c?{"x-matilda-client-distribution-channel":c}:{},...s?{"x-matilda-client-release-channel":s}:{}}}function qd(t){let e=t.toLowerCase();return sa.has(e)||e.startsWith("x-matilda-reported-")}function Ra(t){let e=t??K();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"||Pe(e)}catch{return!1}}function Jd(t,e=t.apiKey){return t.authType==="openai"&&(!!e||t.usesMatildaSignIn===!0||t.usesMatildaSavedApiKey===!0)&&Ra(t.baseUrl)}var va=3e3,Ve=1,ba=24*60*60*1e3,Or=20,Pr=999,Ma=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"]),_a=new Set(["ENOTFOUND","EAI_AGAIN"]),ka=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),wa=new Set(["ABORT_ERR","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT"]),xa=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]);function Ia(t){return`${new URL(t).origin}/api/client-events`}function Oa(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 Vn(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??va);try{let a=await r(Ia(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(Oa(t)),signal:i.signal});return a.ok?!0:(Xe.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`),!1)}catch{return!1}finally{clearTimeout(s)}}async function Nn(t,e){let n=typeof t.occurrenceCount=="number"&&Number.isFinite(t.occurrenceCount)?Math.max(1,Math.min(Math.floor(t.occurrenceCount),Pr)):1;return Vn({eventType:"auth_funnel",authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:n},e)}function Dr(){try{let t=Q.readFileSync(Lr(),"utf8"),e=JSON.parse(t);return e.schemaVersion!==Ve||!Array.isArray(e.failures)?void 0:{schemaVersion:Ve,failures:e.failures.filter(Pa)}}catch{return}}function Pa(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 Ur(t){let e=Lr();if(t.failures.length===0){try{Q.rmSync(e,{force:!0})}catch{}return}try{Q.mkdirSync(Gt.dirname(e),{recursive:!0}),Q.writeFileSync(e,`${JSON.stringify(t)}
|
|
20
|
-
`,"utf8")}catch{}}function Nr(t,e){return t.filter(n=>e-n.lastObservedAtMs<=ba).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-Or)}function Da(t){let e=Ir(t);return{reportedSurface:e["x-matilda-client-name"]==="matilda-desktop"?"desktop":e["x-matilda-client-name"]==="matilda-code"||e["x-matilda-client-name"]==="matilda-vscode"?"code_cli":"unknown",reportedOs:e["x-matilda-client-operating-system"]??"unknown",reportedArchitecture:e["x-matilda-client-architecture"]??"unknown",reportedProcess:e["x-matilda-client-name"]??"unknown",reportedVersion:e["x-matilda-client-version"],reportedReleaseChannel:e["x-matilda-client-release-channel"]??"unknown"}}function Ua(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 Na(t){if(!(!t||typeof t!="object"))for(let e of["status","statusCode"]){let n=t[e];if(typeof n=="number")return n}}function La(t,e){let n=Ua(t);if(n&&Ma.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&_a.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&ka.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&wa.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&xa.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=Na(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 Fa(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 tp(t,e){let n=Da(e.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=La(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=Dr()??{schemaVersion:Ve,failures:[]},a=Nr(s.failures,r),l=Fa(a,i);if(l>=0){let c=a[l];a[l]={...c,occurrenceCount:Math.min(c.occurrenceCount+1,Pr),lastObservedAtMs:r}}else a.push(i);return Ur({schemaVersion:Ve,failures:a.slice(-Or)}),!0}async function np(t){let e=Dr();if(!e)return;let n=Nr(e.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await Vn({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}}Ur({schemaVersion:Ve,failures:o})}function Lr(){return Gt.join(Ye.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var tg="http://localhost:4317";export{vs as a,lr as b,Vr as c,un as d,dt as e,Xr as f,Qr as g,ft as h,Io as i,ki as j,En as k,Ei as l,Tl as m,Ro as n,mt as o,bl as p,_o as q,Pe as r,fn as s,De as t,Ti as u,K as v,Ir as w,qd as x,Jd as y,Nn as z,tp as A,np as B,tg as C,Pu as D,vn as E,$o as F,Du as G,Ku as H,Gu as I,bt as J,me as K,Jo as L,nc as M,sc as N,Zo as O,Kn as P,Gn as Q,Ft as R,Ns as S,Ls as T,fd as U,Er as V,Ks as W,gd as X,md as Y,Kt as Z,Ar as _,Rr as $,Gs as aa,$n as ba,Bn as ca,zs as da,br as ea,bd as fa,qs as ga,xd as ha,kr as ia,B as ja,Gd as ka,$d as la,Bd as ma};
|
|
21
|
-
/**
|
|
22
|
-
* @license
|
|
23
|
-
* Copyright 2025 Matilda
|
|
24
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
25
|
-
*/
|
|
26
|
-
/**
|
|
27
|
-
* @license
|
|
28
|
-
* Copyright 2025 Google LLC
|
|
29
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
30
|
-
*/
|
|
31
|
-
/**
|
|
32
|
-
* @license
|
|
33
|
-
* Copyright 2026 Matilda Team
|
|
34
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
35
|
-
*/
|
|
36
|
-
/**
|
|
37
|
-
* @license
|
|
38
|
-
* Copyright 2026 Google LLC
|
|
39
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
40
|
-
*/
|
|
41
|
-
/**
|
|
42
|
-
* @license
|
|
43
|
-
* Copyright 2026 Matilda
|
|
44
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
45
|
-
*/
|
|
46
|
-
/**
|
|
47
|
-
* @license
|
|
48
|
-
* Copyright 2025 Matilda Team
|
|
49
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
50
|
-
*/
|
|
51
|
-
/**
|
|
52
|
-
* @license
|
|
53
|
-
* Copyright 2026 Maincode
|
|
54
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
55
|
-
*
|
|
56
|
-
* Low-level OAuth primitives for core-auth's unified `/api/auth/oauth/*` flow
|
|
57
|
-
* (ADR-029): PKCE pair generation, RFC 8414 discovery, the RFC 8628 device
|
|
58
|
-
* grant, and refresh. Vendored (as source) from matilda-core's
|
|
59
|
-
* `packages/client-sdk/src/auth.ts` and extended to carry the `id_token`
|
|
60
|
-
* (display identity) that the higher-level flows need. Node built-ins only —
|
|
61
|
-
* no third-party runtime dependencies.
|
|
62
|
-
*/
|
|
63
|
-
/**
|
|
64
|
-
* @license
|
|
65
|
-
* Copyright 2026 Maincode
|
|
66
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
67
|
-
*
|
|
68
|
-
* File-backed token store + cross-process lock. The store persists a JSON map
|
|
69
|
-
* (`{ [key]: value }`) at 0600 so callers can key several credentials in one
|
|
70
|
-
* file; the lock is an O_EXCL lockfile that serialises refreshes across
|
|
71
|
-
* processes (the guarantee a plaintext read/modify/write can't give).
|
|
72
|
-
*/
|
|
73
|
-
/**
|
|
74
|
-
* @license
|
|
75
|
-
* Copyright 2026 Maincode
|
|
76
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
77
|
-
*
|
|
78
|
-
* Hardened access-token manager: returns a valid access token, refreshing via
|
|
79
|
-
* core-auth's token endpoint when expired or forced. Single-flight within the
|
|
80
|
-
* process, serialised across processes by the store's lock, carries a prior
|
|
81
|
-
* refresh token forward when the response omits one, and evicts on a terminal
|
|
82
|
-
* `invalid_grant` so a dead session doesn't wedge the caller in a refresh loop.
|
|
83
|
-
*/
|
|
84
|
-
/**
|
|
85
|
-
* @license
|
|
86
|
-
* Copyright 2026 Maincode
|
|
87
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
88
|
-
*
|
|
89
|
-
* Browser login orchestration: PKCE + a loopback capture server, driven off
|
|
90
|
-
* discovery metadata. Unlike a bare loopback helper, this emits lifecycle
|
|
91
|
-
* events for a UI, honours an AbortSignal, and — instead of serving its own
|
|
92
|
-
* HTML — 302-redirects the browser to an app-owned branded landing
|
|
93
|
-
* (`successRedirect`). Returns a TokenSet including the `id_token`.
|
|
94
|
-
*/
|
|
95
|
-
/**
|
|
96
|
-
* @license
|
|
97
|
-
* Copyright 2026 Maincode
|
|
98
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
99
|
-
*
|
|
100
|
-
* Node auth surface for `@maincode-ai/matilda-client-sdk/auth/node`.
|
|
101
|
-
* Re-exports the OAuth primitives plus the higher-level login flow, file token
|
|
102
|
-
* store, and hardened token manager that the CLI (`packages/core`) and the
|
|
103
|
-
* Electron desktop app consume.
|
|
104
|
-
*/
|
|
105
|
-
/**
|
|
106
|
-
* @license
|
|
107
|
-
* Copyright 2026 Maincode
|
|
108
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
109
|
-
*
|
|
110
|
-
* Matilda account auth for the CLI, backed by the shared client SDK.
|
|
111
|
-
*
|
|
112
|
-
* The OAuth dance (PKCE, loopback capture, code exchange, refresh, cross-process
|
|
113
|
-
* token locking) is owned by `@maincode-ai/matilda-client-sdk/auth/node` — the
|
|
114
|
-
* auth team's tested implementation of ADR-029's unified `/api/auth/oauth/*`
|
|
115
|
-
* flow. This module keeps ONLY the CLI-specific concerns: which endpoint, the
|
|
116
|
-
* on-disk credential shape the rest of the CLI already reads, and surfacing the
|
|
117
|
-
* authorize URL to the Ink UI. No PKCE crypto, no loopback server, no token
|
|
118
|
-
* exchange lives here anymore (replaced the 391-line hand-rolled beta that hit
|
|
119
|
-
* the divergent `/api/auth/cli/*` endpoints and stored tokens in plaintext).
|
|
120
|
-
*/
|
package/chunks/chunk-ZSGBDQXU.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{b as g}from"./chunk-GZPNIYVZ.js";import{a as re,d as I,f as ut}from"./chunk-OWGSC52X.js";var ct=I(V=>{"use strict";g();Object.defineProperty(V,"__esModule",{value:!0});V.normalizePath=V.isRootDirectory=V.convertSlashes=V.cleanPath=void 0;var lt=re("path");function qt(e){let t=(0,lt.normalize)(e);return t.length>1&&t[t.length-1]===lt.sep&&(t=t.substring(0,t.length-1)),t}V.cleanPath=qt;var gn=/[\\/]/g;function Wt(e,t){return e.replace(gn,t)}V.convertSlashes=Wt;var _n=/^[a-z]:[\\/]$/i;function bn(e){return e==="/"||_n.test(e)}V.isRootDirectory=bn;function Rn(e,t){let{resolvePaths:r,normalizePath:n,pathSeparator:s}=t,i=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(r&&(e=(0,lt.resolve)(e)),(n||i)&&(e=qt(e)),e===".")return"";let c=e[e.length-1]!==s;return Wt(c?e+s:e,s)}V.normalizePath=Rn});var zt=I(le=>{"use strict";g();Object.defineProperty(le,"__esModule",{value:!0});le.build=le.joinDirectoryPath=le.joinPathWithBasePath=void 0;var mn=re("path"),yn=ct();function Xt(e,t){return t+e}le.joinPathWithBasePath=Xt;function An(e,t){return function(r,n){return n.startsWith(e)?n.replace(e,"")+r:(0,yn.convertSlashes)((0,mn.relative)(e,n),t.pathSeparator)+t.pathSeparator+r}}function En(e){return e}function Sn(e,t,r){return t+e+r}le.joinDirectoryPath=Sn;function xn(e,t){let{relativePaths:r,includeBasePath:n}=t;return r&&e?An(e,t):n?Xt:En}le.build=xn});var Kt=I(De=>{"use strict";g();Object.defineProperty(De,"__esModule",{value:!0});De.build=void 0;function Cn(e){return function(t,r){r.push(t.substring(e.length)||".")}}function wn(e){return function(t,r,n){let s=t.substring(e.length)||".";n.every(i=>i(s,!0))&&r.push(s)}}var vn=(e,t)=>{t.push(e||".")},$n=(e,t,r)=>{let n=e||".";r.every(s=>s(n,!0))&&t.push(n)},Pn=()=>{};function Tn(e,t){let{includeDirs:r,filters:n,relativePaths:s}=t;return r?s?n&&n.length?wn(e):Cn(e):n&&n.length?$n:vn:Pn}De.build=Tn});var Ut=I(ke=>{"use strict";g();Object.defineProperty(ke,"__esModule",{value:!0});ke.build=void 0;var On=(e,t,r,n)=>{n.every(s=>s(e,!1))&&r.files++},Ln=(e,t,r,n)=>{n.every(s=>s(e,!1))&&t.push(e)},Fn=(e,t,r,n)=>{r.files++},Dn=(e,t)=>{t.push(e)},kn=()=>{};function Hn(e){let{excludeFiles:t,filters:r,onlyCounts:n}=e;return t?kn:r&&r.length?n?On:Ln:n?Fn:Dn}ke.build=Hn});var Qt=I(He=>{"use strict";g();Object.defineProperty(He,"__esModule",{value:!0});He.build=void 0;var In=e=>e,Mn=()=>[""].slice(0,0);function Nn(e){return e.group?Mn:In}He.build=Nn});var Vt=I(Ie=>{"use strict";g();Object.defineProperty(Ie,"__esModule",{value:!0});Ie.build=void 0;var Gn=(e,t,r)=>{e.push({directory:t,files:r,dir:t})},jn=()=>{};function Bn(e){return e.group?Gn:jn}Ie.build=Bn});var Jt=I(pe=>{"use strict";g();var qn=pe&&pe.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(pe,"__esModule",{value:!0});pe.build=void 0;var Me=qn(re("fs")),Yt=re("path"),Wn=function(e,t,r){let{queue:n,options:{suppressErrors:s}}=t;n.enqueue(),Me.default.realpath(e,(i,c)=>{if(i)return n.dequeue(s?null:i,t);Me.default.stat(c,(a,h)=>{if(a)return n.dequeue(s?null:a,t);if(h.isDirectory()&&Zt(e,c,t))return n.dequeue(null,t);r(h,c),n.dequeue(null,t)})})},Xn=function(e,t,r){let{queue:n,options:{suppressErrors:s}}=t;n.enqueue();try{let i=Me.default.realpathSync(e),c=Me.default.statSync(i);if(c.isDirectory()&&Zt(e,i,t))return;r(c,i)}catch(i){if(!s)throw i}};function zn(e,t){return!e.resolveSymlinks||e.excludeSymlinks?null:t?Xn:Wn}pe.build=zn;function Zt(e,t,r){if(r.options.useRealPaths)return Kn(t,r);let n=(0,Yt.dirname)(e),s=1;for(;n!==r.root&&s<2;){let i=r.symlinks.get(n);!!i&&(i===t||i.startsWith(t)||t.startsWith(i))?s++:n=(0,Yt.dirname)(n)}return r.symlinks.set(e,t),s>1}function Kn(e,t){return t.visited.includes(e+t.options.pathSeparator)}});var er=I(Ge=>{"use strict";g();Object.defineProperty(Ge,"__esModule",{value:!0});Ge.build=void 0;var Un=e=>e.counts,Qn=e=>e.groups,Vn=e=>e.paths,Yn=e=>e.paths.slice(0,e.options.maxFiles),Zn=(e,t,r)=>(Ne(t,r,e.counts,e.options.suppressErrors),null),Jn=(e,t,r)=>(Ne(t,r,e.paths,e.options.suppressErrors),null),es=(e,t,r)=>(Ne(t,r,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),ts=(e,t,r)=>(Ne(t,r,e.groups,e.options.suppressErrors),null);function Ne(e,t,r,n){t(e&&!n?e:null,r)}function rs(e,t){let{onlyCounts:r,group:n,maxFiles:s}=e;return r?t?Un:Zn:n?t?Qn:ts:s?t?Yn:es:t?Vn:Jn}Ge.build=rs});var nr=I(ge=>{"use strict";g();var ns=ge&&ge.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ge,"__esModule",{value:!0});ge.build=void 0;var tr=ns(re("fs")),rr={withFileTypes:!0},ss=(e,t,r,n,s)=>{if(e.queue.enqueue(),n<0)return e.queue.dequeue(null,e);e.visited.push(t),e.counts.directories++,tr.default.readdir(t||".",rr,(i,c=[])=>{s(c,r,n),e.queue.dequeue(e.options.suppressErrors?null:i,e)})},is=(e,t,r,n,s)=>{if(n<0)return;e.visited.push(t),e.counts.directories++;let i=[];try{i=tr.default.readdirSync(t||".",rr)}catch(c){if(!e.options.suppressErrors)throw c}s(i,r,n)};function os(e){return e?is:ss}ge.build=os});var sr=I(je=>{"use strict";g();Object.defineProperty(je,"__esModule",{value:!0});je.Queue=void 0;var at=class{onQueueEmpty;count=0;constructor(t){this.onQueueEmpty=t}enqueue(){return this.count++,this.count}dequeue(t,r){this.onQueueEmpty&&(--this.count<=0||t)&&(this.onQueueEmpty(t,r),t&&(r.controller.abort(),this.onQueueEmpty=void 0))}};je.Queue=at});var ir=I(Be=>{"use strict";g();Object.defineProperty(Be,"__esModule",{value:!0});Be.Counter=void 0;var ft=class{_files=0;_directories=0;set files(t){this._files=t}get files(){return this._files}set directories(t){this._directories=t}get directories(){return this._directories}get dirs(){return this._directories}};Be.Counter=ft});var pt=I(Y=>{"use strict";g();var us=Y&&Y.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),ls=Y&&Y.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ce=Y&&Y.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&us(t,e,r);return ls(t,e),t};Object.defineProperty(Y,"__esModule",{value:!0});Y.Walker=void 0;var or=re("path"),qe=ct(),ht=ce(zt()),cs=ce(Kt()),as=ce(Ut()),fs=ce(Qt()),hs=ce(Vt()),ds=ce(Jt()),ps=ce(er()),gs=ce(nr()),_s=sr(),bs=ir(),dt=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(t,r,n){this.isSynchronous=!n,this.callbackInvoker=ps.build(r,this.isSynchronous),this.root=(0,qe.normalizePath)(t,r),this.state={root:(0,qe.isRootDirectory)(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new bs.Counter,options:r,queue:new _s.Queue((s,i)=>this.callbackInvoker(i,s,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new AbortController},this.joinPath=ht.build(this.root,r),this.pushDirectory=cs.build(this.root,r),this.pushFile=as.build(r),this.getArray=fs.build(r),this.groupFiles=hs.build(r),this.resolveSymlink=ds.build(r,this.isSynchronous),this.walkDirectory=gs.build(this.isSynchronous)}start(){return this.pushDirectory(this.root,this.state.paths,this.state.options.filters),this.walkDirectory(this.state,this.root,this.root,this.state.options.maxDepth,this.walk),this.isSynchronous?this.callbackInvoker(this.state,null):null}walk=(t,r,n)=>{let{paths:s,options:{filters:i,resolveSymlinks:c,excludeSymlinks:a,exclude:h,maxFiles:d,signal:b,useRealPaths:E,pathSeparator:S},controller:D}=this.state;if(D.signal.aborted||b&&b.aborted||d&&s.length>d)return;let R=this.getArray(this.state.paths);for(let y=0;y<t.length;++y){let $=t[y];if($.isFile()||$.isSymbolicLink()&&!c&&!a){let C=this.joinPath($.name,r);this.pushFile(C,R,this.state.counts,i)}else if($.isDirectory()){let C=ht.joinDirectoryPath($.name,r,this.state.options.pathSeparator);if(h&&h($.name,C))continue;this.pushDirectory(C,s,i),this.walkDirectory(this.state,C,C,n-1,this.walk)}else if(this.resolveSymlink&&$.isSymbolicLink()){let C=ht.joinPathWithBasePath($.name,r);this.resolveSymlink(C,this.state,(v,L)=>{if(v.isDirectory()){if(L=(0,qe.normalizePath)(L,this.state.options),h&&h($.name,E?L:C+S))return;this.walkDirectory(this.state,L,E?L:C+S,n-1,this.walk)}else{L=E?L:C;let W=(0,or.basename)(L),A=(0,qe.normalizePath)((0,or.dirname)(L),this.state.options);L=this.joinPath(W,A),this.pushFile(L,R,this.state.counts,i)}})}}this.groupFiles(this.state.groups,r,R)}};Y.Walker=dt});var lr=I(_e=>{"use strict";g();Object.defineProperty(_e,"__esModule",{value:!0});_e.callback=_e.promise=void 0;var Rs=pt();function ms(e,t){return new Promise((r,n)=>{ur(e,t,(s,i)=>{if(s)return n(s);r(i)})})}_e.promise=ms;function ur(e,t,r){new Rs.Walker(e,t,r).start()}_e.callback=ur});var cr=I(We=>{"use strict";g();Object.defineProperty(We,"__esModule",{value:!0});We.sync=void 0;var ys=pt();function As(e,t){return new ys.Walker(e,t).start()}We.sync=As});var fr=I(Xe=>{"use strict";g();Object.defineProperty(Xe,"__esModule",{value:!0});Xe.APIBuilder=void 0;var ar=lr(),Es=cr(),gt=class{root;options;constructor(t,r){this.root=t,this.options=r}withPromise(){return(0,ar.promise)(this.root,this.options)}withCallback(t){(0,ar.callback)(this.root,this.options,t)}sync(){return(0,Es.sync)(this.root,this.options)}};Xe.APIBuilder=gt});var Ae=I((To,_r)=>{"use strict";g();var Z="\\\\/",hr=`[^${Z}]`,ne="\\.",Ss="\\+",xs="\\?",ze="\\/",Cs="(?=.)",dr="[^/]",_t=`(?:${ze}|$)`,pr=`(?:^|${ze})`,bt=`${ne}{1,2}${_t}`,ws=`(?!${ne})`,vs=`(?!${pr}${bt})`,$s=`(?!${ne}{0,1}${_t})`,Ps=`(?!${bt})`,Ts=`[^.${ze}]`,Os=`${dr}*?`,Ls="/",gr={DOT_LITERAL:ne,PLUS_LITERAL:Ss,QMARK_LITERAL:xs,SLASH_LITERAL:ze,ONE_CHAR:Cs,QMARK:dr,END_ANCHOR:_t,DOTS_SLASH:bt,NO_DOT:ws,NO_DOTS:vs,NO_DOT_SLASH:$s,NO_DOTS_SLASH:Ps,QMARK_NO_DOT:Ts,STAR:Os,START_ANCHOR:pr,SEP:Ls},Fs={...gr,SLASH_LITERAL:`[${Z}]`,QMARK:hr,STAR:`${hr}*?`,DOTS_SLASH:`${ne}{1,2}(?:[${Z}]|$)`,NO_DOT:`(?!${ne})`,NO_DOTS:`(?!(?:^|[${Z}])${ne}{1,2}(?:[${Z}]|$))`,NO_DOT_SLASH:`(?!${ne}{0,1}(?:[${Z}]|$))`,NO_DOTS_SLASH:`(?!${ne}{1,2}(?:[${Z}]|$))`,QMARK_NO_DOT:`[^.${Z}]`,START_ANCHOR:`(?:^|[${Z}])`,END_ANCHOR:`(?:[${Z}]|$)`,SEP:"\\"},Ds={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};_r.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Ds,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===!0?Fs:gr}}});var Ee=I(K=>{"use strict";g();var{REGEX_BACKSLASH:ks,REGEX_REMOVE_BACKSLASH:Hs,REGEX_SPECIAL_CHARS:Is,REGEX_SPECIAL_CHARS_GLOBAL:Ms}=Ae();K.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);K.hasRegexChars=e=>Is.test(e);K.isRegexChar=e=>e.length===1&&K.hasRegexChars(e);K.escapeRegex=e=>e.replace(Ms,"\\$1");K.toPosixSlashes=e=>e.replace(ks,"/");K.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let e=navigator.platform.toLowerCase();return e==="win32"||e==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":!1};K.removeBackslashes=e=>e.replace(Hs,t=>t==="\\"?"":t);K.escapeLast=(e,t,r)=>{let n=e.lastIndexOf(t,r);return n===-1?e:e[n-1]==="\\"?K.escapeLast(e,t,n-1):`${e.slice(0,n)}\\${e.slice(n)}`};K.removePrefix=(e,t={})=>{let r=e;return r.startsWith("./")&&(r=r.slice(2),t.prefix="./"),r};K.wrapOutput=(e,t={},r={})=>{let n=r.contains?"":"^",s=r.contains?"":"$",i=`${n}(?:${e})${s}`;return t.negated===!0&&(i=`(?:^(?!${i}).*$)`),i};K.basename=(e,{windows:t}={})=>{let r=e.split(t?/[\\/]/:"/"),n=r[r.length-1];return n===""?r[r.length-2]:n}});var xr=I((Do,Sr)=>{"use strict";g();var br=Ee(),{CHAR_ASTERISK:Rt,CHAR_AT:Ns,CHAR_BACKWARD_SLASH:Se,CHAR_COMMA:Gs,CHAR_DOT:mt,CHAR_EXCLAMATION_MARK:yt,CHAR_FORWARD_SLASH:Er,CHAR_LEFT_CURLY_BRACE:At,CHAR_LEFT_PARENTHESES:Et,CHAR_LEFT_SQUARE_BRACKET:js,CHAR_PLUS:Bs,CHAR_QUESTION_MARK:Rr,CHAR_RIGHT_CURLY_BRACE:qs,CHAR_RIGHT_PARENTHESES:mr,CHAR_RIGHT_SQUARE_BRACKET:Ws}=Ae(),yr=e=>e===Er||e===Se,Ar=e=>{e.isPrefix!==!0&&(e.depth=e.isGlobstar?1/0:1)},Xs=(e,t)=>{let r=t||{},n=e.length-1,s=r.parts===!0||r.scanToEnd===!0,i=[],c=[],a=[],h=e,d=-1,b=0,E=0,S=!1,D=!1,R=!1,y=!1,$=!1,C=!1,v=!1,L=!1,W=!1,A=!1,P=0,F,m,_={value:"",depth:0,isGlob:!1},o=()=>d>=n,B=()=>h.charCodeAt(d+1),M=()=>(F=m,h.charCodeAt(++d));for(;d<n;){m=M();let T;if(m===Se){v=_.backslashes=!0,m=M(),m===At&&(C=!0);continue}if(C===!0||m===At){for(P++;o()!==!0&&(m=M());){if(m===Se){v=_.backslashes=!0,M();continue}if(m===At){P++;continue}if(C!==!0&&m===mt&&(m=M())===mt){if(S=_.isBrace=!0,R=_.isGlob=!0,A=!0,s===!0)continue;break}if(C!==!0&&m===Gs){if(S=_.isBrace=!0,R=_.isGlob=!0,A=!0,s===!0)continue;break}if(m===qs&&(P--,P===0)){C=!1,S=_.isBrace=!0,A=!0;break}}if(s===!0)continue;break}if(m===Er){if(i.push(d),c.push(_),_={value:"",depth:0,isGlob:!1},A===!0)continue;if(F===mt&&d===b+1){b+=2;continue}E=d+1;continue}if(r.noext!==!0&&(m===Bs||m===Ns||m===Rt||m===Rr||m===yt)===!0&&B()===Et){if(R=_.isGlob=!0,y=_.isExtglob=!0,A=!0,m===yt&&d===b&&(W=!0),s===!0){for(;o()!==!0&&(m=M());){if(m===Se){v=_.backslashes=!0,m=M();continue}if(m===mr){R=_.isGlob=!0,A=!0;break}}continue}break}if(m===Rt){if(F===Rt&&($=_.isGlobstar=!0),R=_.isGlob=!0,A=!0,s===!0)continue;break}if(m===Rr){if(R=_.isGlob=!0,A=!0,s===!0)continue;break}if(m===js){for(;o()!==!0&&(T=M());){if(T===Se){v=_.backslashes=!0,M();continue}if(T===Ws){D=_.isBracket=!0,R=_.isGlob=!0,A=!0;break}}if(s===!0)continue;break}if(r.nonegate!==!0&&m===yt&&d===b){L=_.negated=!0,b++;continue}if(r.noparen!==!0&&m===Et){if(R=_.isGlob=!0,s===!0){for(;o()!==!0&&(m=M());){if(m===Et){v=_.backslashes=!0,m=M();continue}if(m===mr){A=!0;break}}continue}break}if(R===!0){if(A=!0,s===!0)continue;break}}r.noext===!0&&(y=!1,R=!1);let k=h,u="",l="";b>0&&(u=h.slice(0,b),h=h.slice(b),E-=b),k&&R===!0&&E>0?(k=h.slice(0,E),l=h.slice(E)):R===!0?(k="",l=h):k=h,k&&k!==""&&k!=="/"&&k!==h&&yr(k.charCodeAt(k.length-1))&&(k=k.slice(0,-1)),r.unescape===!0&&(l&&(l=br.removeBackslashes(l)),k&&v===!0&&(k=br.removeBackslashes(k)));let U={prefix:u,input:e,start:b,base:k,glob:l,isBrace:S,isBracket:D,isGlob:R,isExtglob:y,isGlobstar:$,negated:L,negatedExtglob:W};if(r.tokens===!0&&(U.maxDepth=0,yr(m)||c.push(_),U.tokens=c),r.parts===!0||r.tokens===!0){let T;for(let N=0;N<i.length;N++){let te=T?T+1:b,Q=i[N],ue=e.slice(te,Q);r.tokens&&(N===0&&b!==0?(c[N].isPrefix=!0,c[N].value=u):c[N].value=ue,Ar(c[N]),U.maxDepth+=c[N].depth),(N!==0||ue!=="")&&a.push(ue),T=Q}if(T&&T+1<e.length){let N=e.slice(T+1);a.push(N),r.tokens&&(c[c.length-1].value=N,Ar(c[c.length-1]),U.maxDepth+=c[c.length-1].depth)}U.slashes=i,U.parts=a}return U};Sr.exports=Xs});var vr=I((Ho,wr)=>{"use strict";g();var Ke=Ae(),J=Ee(),{MAX_LENGTH:Ue,POSIX_REGEX_SOURCE:zs,REGEX_NON_SPECIAL_CHARS:Ks,REGEX_SPECIAL_CHARS_BACKREF:Us,REPLACEMENTS:Cr}=Ke,Qs=(e,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...e,t);e.sort();let r=`[${e.join("-")}]`;try{new RegExp(r)}catch{return e.map(s=>J.escapeRegex(s)).join("..")}return r},be=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,St=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=Cr[e]||e;let r={...t},n=typeof r.maxLength=="number"?Math.min(Ue,r.maxLength):Ue,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:r.prepend||""},c=[i],a=r.capture?"":"?:",h=Ke.globChars(r.windows),d=Ke.extglobChars(h),{DOT_LITERAL:b,PLUS_LITERAL:E,SLASH_LITERAL:S,ONE_CHAR:D,DOTS_SLASH:R,NO_DOT:y,NO_DOT_SLASH:$,NO_DOTS_SLASH:C,QMARK:v,QMARK_NO_DOT:L,STAR:W,START_ANCHOR:A}=h,P=p=>`(${a}(?:(?!${A}${p.dot?R:b}).)*?)`,F=r.dot?"":y,m=r.dot?v:L,_=r.bash===!0?P(r):W;r.capture&&(_=`(${_})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let o={input:e,index:-1,start:0,dot:r.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:c};e=J.removePrefix(e,o),s=e.length;let B=[],M=[],k=[],u=i,l,U=()=>o.index===s-1,T=o.peek=(p=1)=>e[o.index+p],N=o.advance=()=>e[++o.index]||"",te=()=>e.slice(o.index+1),Q=(p="",H=0)=>{o.consumed+=p,o.index+=H},ue=p=>{o.output+=p.output!=null?p.output:p.value,Q(p.value)},dn=()=>{let p=1;for(;T()==="!"&&(T(2)!=="("||T(3)==="?");)N(),o.start++,p++;return p%2===0?!1:(o.negated=!0,o.start++,!0)},Oe=p=>{o[p]++,k.push(p)},fe=p=>{o[p]--,k.pop()},w=p=>{if(u.type==="globstar"){let H=o.braces>0&&(p.type==="comma"||p.type==="brace"),f=p.extglob===!0||B.length&&(p.type==="pipe"||p.type==="paren");p.type!=="slash"&&p.type!=="paren"&&!H&&!f&&(o.output=o.output.slice(0,-u.output.length),u.type="star",u.value="*",u.output=_,o.output+=u.output)}if(B.length&&p.type!=="paren"&&(B[B.length-1].inner+=p.value),(p.value||p.output)&&ue(p),u&&u.type==="text"&&p.type==="text"){u.output=(u.output||u.value)+p.value,u.value+=p.value;return}p.prev=u,c.push(p),u=p},Le=(p,H)=>{let f={...d[H],conditions:1,inner:""};f.prev=u,f.parens=o.parens,f.output=o.output;let x=(r.capture?"(":"")+f.open;Oe("parens"),w({type:p,value:H,output:o.output?"":D}),w({type:"paren",extglob:!0,value:N(),output:x}),B.push(f)},pn=p=>{let H=p.close+(r.capture?")":""),f;if(p.type==="negate"){let x=_;if(p.inner&&p.inner.length>1&&p.inner.includes("/")&&(x=P(r)),(x!==_||U()||/^\)+$/.test(te()))&&(H=p.close=`)$))${x}`),p.inner.includes("*")&&(f=te())&&/^\.[^\\/.]+$/.test(f)){let G=St(f,{...t,fastpaths:!1}).output;H=p.close=`)${G})${x})`}p.prev.type==="bos"&&(o.negatedExtglob=!0)}w({type:"paren",extglob:!0,value:l,output:H}),fe("parens")};if(r.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(e)){let p=!1,H=e.replace(Us,(f,x,G,z,q,ot)=>z==="\\"?(p=!0,f):z==="?"?x?x+z+(q?v.repeat(q.length):""):ot===0?m+(q?v.repeat(q.length):""):v.repeat(G.length):z==="."?b.repeat(G.length):z==="*"?x?x+z+(q?_:""):_:x?f:`\\${f}`);return p===!0&&(r.unescape===!0?H=H.replace(/\\/g,""):H=H.replace(/\\+/g,f=>f.length%2===0?"\\\\":f?"\\":"")),H===e&&r.contains===!0?(o.output=e,o):(o.output=J.wrapOutput(H,o,t),o)}for(;!U();){if(l=N(),l==="\0")continue;if(l==="\\"){let f=T();if(f==="/"&&r.bash!==!0||f==="."||f===";")continue;if(!f){l+="\\",w({type:"text",value:l});continue}let x=/^\\+/.exec(te()),G=0;if(x&&x[0].length>2&&(G=x[0].length,o.index+=G,G%2!==0&&(l+="\\")),r.unescape===!0?l=N():l+=N(),o.brackets===0){w({type:"text",value:l});continue}}if(o.brackets>0&&(l!=="]"||u.value==="["||u.value==="[^")){if(r.posix!==!1&&l===":"){let f=u.value.slice(1);if(f.includes("[")&&(u.posix=!0,f.includes(":"))){let x=u.value.lastIndexOf("["),G=u.value.slice(0,x),z=u.value.slice(x+2),q=zs[z];if(q){u.value=G+q,o.backtrack=!0,N(),!i.output&&c.indexOf(u)===1&&(i.output=D);continue}}}(l==="["&&T()!==":"||l==="-"&&T()==="]")&&(l=`\\${l}`),l==="]"&&(u.value==="["||u.value==="[^")&&(l=`\\${l}`),r.posix===!0&&l==="!"&&u.value==="["&&(l="^"),u.value+=l,ue({value:l});continue}if(o.quotes===1&&l!=='"'){l=J.escapeRegex(l),u.value+=l,ue({value:l});continue}if(l==='"'){o.quotes=o.quotes===1?0:1,r.keepQuotes===!0&&w({type:"text",value:l});continue}if(l==="("){Oe("parens"),w({type:"paren",value:l});continue}if(l===")"){if(o.parens===0&&r.strictBrackets===!0)throw new SyntaxError(be("opening","("));let f=B[B.length-1];if(f&&o.parens===f.parens+1){pn(B.pop());continue}w({type:"paren",value:l,output:o.parens?")":"\\)"}),fe("parens");continue}if(l==="["){if(r.nobracket===!0||!te().includes("]")){if(r.nobracket!==!0&&r.strictBrackets===!0)throw new SyntaxError(be("closing","]"));l=`\\${l}`}else Oe("brackets");w({type:"bracket",value:l});continue}if(l==="]"){if(r.nobracket===!0||u&&u.type==="bracket"&&u.value.length===1){w({type:"text",value:l,output:`\\${l}`});continue}if(o.brackets===0){if(r.strictBrackets===!0)throw new SyntaxError(be("opening","["));w({type:"text",value:l,output:`\\${l}`});continue}fe("brackets");let f=u.value.slice(1);if(u.posix!==!0&&f[0]==="^"&&!f.includes("/")&&(l=`/${l}`),u.value+=l,ue({value:l}),r.literalBrackets===!1||J.hasRegexChars(f))continue;let x=J.escapeRegex(u.value);if(o.output=o.output.slice(0,-u.value.length),r.literalBrackets===!0){o.output+=x,u.value=x;continue}u.value=`(${a}${x}|${u.value})`,o.output+=u.value;continue}if(l==="{"&&r.nobrace!==!0){Oe("braces");let f={type:"brace",value:l,output:"(",outputIndex:o.output.length,tokensIndex:o.tokens.length};M.push(f),w(f);continue}if(l==="}"){let f=M[M.length-1];if(r.nobrace===!0||!f){w({type:"text",value:l,output:l});continue}let x=")";if(f.dots===!0){let G=c.slice(),z=[];for(let q=G.length-1;q>=0&&(c.pop(),G[q].type!=="brace");q--)G[q].type!=="dots"&&z.unshift(G[q].value);x=Qs(z,r),o.backtrack=!0}if(f.comma!==!0&&f.dots!==!0){let G=o.output.slice(0,f.outputIndex),z=o.tokens.slice(f.tokensIndex);f.value=f.output="\\{",l=x="\\}",o.output=G;for(let q of z)o.output+=q.output||q.value}w({type:"brace",value:l,output:x}),fe("braces"),M.pop();continue}if(l==="|"){B.length>0&&B[B.length-1].conditions++,w({type:"text",value:l});continue}if(l===","){let f=l,x=M[M.length-1];x&&k[k.length-1]==="braces"&&(x.comma=!0,f="|"),w({type:"comma",value:l,output:f});continue}if(l==="/"){if(u.type==="dot"&&o.index===o.start+1){o.start=o.index+1,o.consumed="",o.output="",c.pop(),u=i;continue}w({type:"slash",value:l,output:S});continue}if(l==="."){if(o.braces>0&&u.type==="dot"){u.value==="."&&(u.output=b);let f=M[M.length-1];u.type="dots",u.output+=l,u.value+=l,f.dots=!0;continue}if(o.braces+o.parens===0&&u.type!=="bos"&&u.type!=="slash"){w({type:"text",value:l,output:b});continue}w({type:"dot",value:l,output:b});continue}if(l==="?"){if(!(u&&u.value==="(")&&r.noextglob!==!0&&T()==="("&&T(2)!=="?"){Le("qmark",l);continue}if(u&&u.type==="paren"){let x=T(),G=l;(u.value==="("&&!/[!=<:]/.test(x)||x==="<"&&!/<([!=]|\w+>)/.test(te()))&&(G=`\\${l}`),w({type:"text",value:l,output:G});continue}if(r.dot!==!0&&(u.type==="slash"||u.type==="bos")){w({type:"qmark",value:l,output:L});continue}w({type:"qmark",value:l,output:v});continue}if(l==="!"){if(r.noextglob!==!0&&T()==="("&&(T(2)!=="?"||!/[!=<:]/.test(T(3)))){Le("negate",l);continue}if(r.nonegate!==!0&&o.index===0){dn();continue}}if(l==="+"){if(r.noextglob!==!0&&T()==="("&&T(2)!=="?"){Le("plus",l);continue}if(u&&u.value==="("||r.regex===!1){w({type:"plus",value:l,output:E});continue}if(u&&(u.type==="bracket"||u.type==="paren"||u.type==="brace")||o.parens>0){w({type:"plus",value:l});continue}w({type:"plus",value:E});continue}if(l==="@"){if(r.noextglob!==!0&&T()==="("&&T(2)!=="?"){w({type:"at",extglob:!0,value:l,output:""});continue}w({type:"text",value:l});continue}if(l!=="*"){(l==="$"||l==="^")&&(l=`\\${l}`);let f=Ks.exec(te());f&&(l+=f[0],o.index+=f[0].length),w({type:"text",value:l});continue}if(u&&(u.type==="globstar"||u.star===!0)){u.type="star",u.star=!0,u.value+=l,u.output=_,o.backtrack=!0,o.globstar=!0,Q(l);continue}let p=te();if(r.noextglob!==!0&&/^\([^?]/.test(p)){Le("star",l);continue}if(u.type==="star"){if(r.noglobstar===!0){Q(l);continue}let f=u.prev,x=f.prev,G=f.type==="slash"||f.type==="bos",z=x&&(x.type==="star"||x.type==="globstar");if(r.bash===!0&&(!G||p[0]&&p[0]!=="/")){w({type:"star",value:l,output:""});continue}let q=o.braces>0&&(f.type==="comma"||f.type==="brace"),ot=B.length&&(f.type==="pipe"||f.type==="paren");if(!G&&f.type!=="paren"&&!q&&!ot){w({type:"star",value:l,output:""});continue}for(;p.slice(0,3)==="/**";){let Fe=e[o.index+4];if(Fe&&Fe!=="/")break;p=p.slice(3),Q("/**",3)}if(f.type==="bos"&&U()){u.type="globstar",u.value+=l,u.output=P(r),o.output=u.output,o.globstar=!0,Q(l);continue}if(f.type==="slash"&&f.prev.type!=="bos"&&!z&&U()){o.output=o.output.slice(0,-(f.output+u.output).length),f.output=`(?:${f.output}`,u.type="globstar",u.output=P(r)+(r.strictSlashes?")":"|$)"),u.value+=l,o.globstar=!0,o.output+=f.output+u.output,Q(l);continue}if(f.type==="slash"&&f.prev.type!=="bos"&&p[0]==="/"){let Fe=p[1]!==void 0?"|$":"";o.output=o.output.slice(0,-(f.output+u.output).length),f.output=`(?:${f.output}`,u.type="globstar",u.output=`${P(r)}${S}|${S}${Fe})`,u.value+=l,o.output+=f.output+u.output,o.globstar=!0,Q(l+N()),w({type:"slash",value:"/",output:""});continue}if(f.type==="bos"&&p[0]==="/"){u.type="globstar",u.value+=l,u.output=`(?:^|${S}|${P(r)}${S})`,o.output=u.output,o.globstar=!0,Q(l+N()),w({type:"slash",value:"/",output:""});continue}o.output=o.output.slice(0,-u.output.length),u.type="globstar",u.output=P(r),u.value+=l,o.output+=u.output,o.globstar=!0,Q(l);continue}let H={type:"star",value:l,output:_};if(r.bash===!0){H.output=".*?",(u.type==="bos"||u.type==="slash")&&(H.output=F+H.output),w(H);continue}if(u&&(u.type==="bracket"||u.type==="paren")&&r.regex===!0){H.output=l,w(H);continue}(o.index===o.start||u.type==="slash"||u.type==="dot")&&(u.type==="dot"?(o.output+=$,u.output+=$):r.dot===!0?(o.output+=C,u.output+=C):(o.output+=F,u.output+=F),T()!=="*"&&(o.output+=D,u.output+=D)),w(H)}for(;o.brackets>0;){if(r.strictBrackets===!0)throw new SyntaxError(be("closing","]"));o.output=J.escapeLast(o.output,"["),fe("brackets")}for(;o.parens>0;){if(r.strictBrackets===!0)throw new SyntaxError(be("closing",")"));o.output=J.escapeLast(o.output,"("),fe("parens")}for(;o.braces>0;){if(r.strictBrackets===!0)throw new SyntaxError(be("closing","}"));o.output=J.escapeLast(o.output,"{"),fe("braces")}if(r.strictSlashes!==!0&&(u.type==="star"||u.type==="bracket")&&w({type:"maybe_slash",value:"",output:`${S}?`}),o.backtrack===!0){o.output="";for(let p of o.tokens)o.output+=p.output!=null?p.output:p.value,p.suffix&&(o.output+=p.suffix)}return o};St.fastpaths=(e,t)=>{let r={...t},n=typeof r.maxLength=="number"?Math.min(Ue,r.maxLength):Ue,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);e=Cr[e]||e;let{DOT_LITERAL:i,SLASH_LITERAL:c,ONE_CHAR:a,DOTS_SLASH:h,NO_DOT:d,NO_DOTS:b,NO_DOTS_SLASH:E,STAR:S,START_ANCHOR:D}=Ke.globChars(r.windows),R=r.dot?b:d,y=r.dot?E:d,$=r.capture?"":"?:",C={negated:!1,prefix:""},v=r.bash===!0?".*?":S;r.capture&&(v=`(${v})`);let L=F=>F.noglobstar===!0?v:`(${$}(?:(?!${D}${F.dot?h:i}).)*?)`,W=F=>{switch(F){case"*":return`${R}${a}${v}`;case".*":return`${i}${a}${v}`;case"*.*":return`${R}${v}${i}${a}${v}`;case"*/*":return`${R}${v}${c}${a}${y}${v}`;case"**":return R+L(r);case"**/*":return`(?:${R}${L(r)}${c})?${y}${a}${v}`;case"**/*.*":return`(?:${R}${L(r)}${c})?${y}${v}${i}${a}${v}`;case"**/.*":return`(?:${R}${L(r)}${c})?${i}${a}${v}`;default:{let m=/^(.*?)\.(\w+)$/.exec(F);if(!m)return;let _=W(m[1]);return _?_+i+m[2]:void 0}}},A=J.removePrefix(e,C),P=W(A);return P&&r.strictSlashes!==!0&&(P+=`${c}?`),P};wr.exports=St});var Tr=I((Mo,Pr)=>{"use strict";g();var Vs=xr(),xt=vr(),$r=Ee(),Ys=Ae(),Zs=e=>e&&typeof e=="object"&&!Array.isArray(e),j=(e,t,r=!1)=>{if(Array.isArray(e)){let b=e.map(S=>j(S,t,r));return S=>{for(let D of b){let R=D(S);if(R)return R}return!1}}let n=Zs(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let s=t||{},i=s.windows,c=n?j.compileRe(e,t):j.makeRe(e,t,!1,!0),a=c.state;delete c.state;let h=()=>!1;if(s.ignore){let b={...t,ignore:null,onMatch:null,onResult:null};h=j(s.ignore,b,r)}let d=(b,E=!1)=>{let{isMatch:S,match:D,output:R}=j.test(b,c,t,{glob:e,posix:i}),y={glob:e,state:a,regex:c,posix:i,input:b,output:R,match:D,isMatch:S};return typeof s.onResult=="function"&&s.onResult(y),S===!1?(y.isMatch=!1,E?y:!1):h(b)?(typeof s.onIgnore=="function"&&s.onIgnore(y),y.isMatch=!1,E?y:!1):(typeof s.onMatch=="function"&&s.onMatch(y),E?y:!0)};return r&&(d.state=a),d};j.test=(e,t,r,{glob:n,posix:s}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return{isMatch:!1,output:""};let i=r||{},c=i.format||(s?$r.toPosixSlashes:null),a=e===n,h=a&&c?c(e):e;return a===!1&&(h=c?c(e):e,a=h===n),(a===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?a=j.matchBase(e,t,r,s):a=t.exec(h)),{isMatch:!!a,match:a,output:h}};j.matchBase=(e,t,r)=>(t instanceof RegExp?t:j.makeRe(t,r)).test($r.basename(e));j.isMatch=(e,t,r)=>j(t,r)(e);j.parse=(e,t)=>Array.isArray(e)?e.map(r=>j.parse(r,t)):xt(e,{...t,fastpaths:!1});j.scan=(e,t)=>Vs(e,t);j.compileRe=(e,t,r=!1,n=!1)=>{if(r===!0)return e.output;let s=t||{},i=s.contains?"":"^",c=s.contains?"":"$",a=`${i}(?:${e.output})${c}`;e&&e.negated===!0&&(a=`^(?!${a}).*$`);let h=j.toRegex(a,t);return n===!0&&(h.state=e),h};j.makeRe=(e,t={},r=!1,n=!1)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let s={negated:!1,fastpaths:!0};return t.fastpaths!==!1&&(e[0]==="."||e[0]==="*")&&(s.output=xt.fastpaths(e,t)),s.output||(s=xt(e,t)),j.compileRe(s,t,r,n)};j.toRegex=(e,t)=>{try{let r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(r){if(t&&t.debug===!0)throw r;return/$^/}};j.constants=Ys;Pr.exports=j});var Ct=I((Go,Fr)=>{"use strict";g();var Or=Tr(),Js=Ee();function Lr(e,t,r=!1){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:Js.isWindows()}),Or(e,t,r)}Object.assign(Lr,Or);Fr.exports=Lr});var Hr=I(Qe=>{"use strict";g();Object.defineProperty(Qe,"__esModule",{value:!0});Qe.Builder=void 0;var ei=re("path"),Dr=fr(),kr=null;try{re.resolve("picomatch"),kr=Ct()}catch{}var wt=class{globCache={};options={maxDepth:1/0,suppressErrors:!0,pathSeparator:ei.sep,filters:[]};globFunction;constructor(t){this.options={...this.options,...t},this.globFunction=this.options.globFunction}group(){return this.options.group=!0,this}withPathSeparator(t){return this.options.pathSeparator=t,this}withBasePath(){return this.options.includeBasePath=!0,this}withRelativePaths(){return this.options.relativePaths=!0,this}withDirs(){return this.options.includeDirs=!0,this}withMaxDepth(t){return this.options.maxDepth=t,this}withMaxFiles(t){return this.options.maxFiles=t,this}withFullPaths(){return this.options.resolvePaths=!0,this.options.includeBasePath=!0,this}withErrors(){return this.options.suppressErrors=!1,this}withSymlinks({resolvePaths:t=!0}={}){return this.options.resolveSymlinks=!0,this.options.useRealPaths=t,this.withFullPaths()}withAbortSignal(t){return this.options.signal=t,this}normalize(){return this.options.normalizePath=!0,this}filter(t){return this.options.filters.push(t),this}onlyDirs(){return this.options.excludeFiles=!0,this.options.includeDirs=!0,this}exclude(t){return this.options.exclude=t,this}onlyCounts(){return this.options.onlyCounts=!0,this}crawl(t){return new Dr.APIBuilder(t||".",this.options)}withGlobFunction(t){return this.globFunction=t,this}crawlWithOptions(t,r){return this.options={...this.options,...r},new Dr.APIBuilder(t||".",this.options)}glob(...t){return this.globFunction?this.globWithOptions(t):this.globWithOptions(t,{dot:!0})}globWithOptions(t,...r){let n=this.globFunction||kr;if(!n)throw new Error("Please specify a glob function to use glob matching.");var s=this.globCache[t.join("\0")];return s||(s=n(t,...r),this.globCache[t.join("\0")]=s),this.options.filters.push(i=>s(i)),this}};Qe.Builder=wt});var Mr=I(Ir=>{"use strict";g();Object.defineProperty(Ir,"__esModule",{value:!0})});var Nr=I(se=>{"use strict";g();var ti=se&&se.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),ri=se&&se.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&ti(t,e,r)};Object.defineProperty(se,"__esModule",{value:!0});se.fdir=void 0;var ni=Hr();Object.defineProperty(se,"fdir",{enumerable:!0,get:function(){return ni.Builder}});ri(Mr(),se)});var an=I((nu,st)=>{g();function nn(e){return Array.isArray(e)?e:[e]}var Oi=void 0,Ht="",tn=" ",kt="\\",Li=/^\s+$/,Fi=/(?:[^\\]|^)\\$/,Di=/^\\!/,ki=/^\\#/,Hi=/\r?\n/g,Ii=/^\.{0,2}\/|^\.{1,2}$/,Mi=/\/$/,me="/",sn="node-ignore";typeof Symbol<"u"&&(sn=Symbol.for("node-ignore"));var on=sn,ye=(e,t,r)=>(Object.defineProperty(e,t,{value:r}),r),Ni=/([0-z])-([0-z])/g,un=()=>!1,Gi=e=>e.replace(Ni,(t,r,n)=>r.charCodeAt(0)<=n.charCodeAt(0)?t:Ht),ji=e=>{let{length:t}=e;return e.slice(0,t-t%2)},Bi=[[/^\uFEFF/,()=>Ht],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,r)=>t+(r.indexOf("\\")===0?tn:Ht)],[/(\\+?)\s/g,(e,t)=>{let{length:r}=t;return t.slice(0,r-r%2)+tn}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,r)=>t+6<r.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,r)=>{let n=r.replace(/\\\*/g,"[^\\/]*");return t+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>kt],[/\\\\/g,()=>kt],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,r,n,s)=>t===kt?`\\[${r}${ji(n)}${s}`:s==="]"&&n.length%2===0?`[${Gi(r)}${n}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],qi=/(^|\\\/)?\\\*$/,Te="regex",rt="checkRegex",rn="_",Wi={[Te](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[rt](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Xi=e=>Bi.reduce((t,[r,n])=>t.replace(r,n.bind(e)),e),nt=e=>typeof e=="string",zi=e=>e&&nt(e)&&!Li.test(e)&&!Fi.test(e)&&e.indexOf("#")!==0,Ki=e=>e.split(Hi).filter(Boolean),It=class{constructor(t,r,n,s,i,c){this.pattern=t,this.mark=r,this.negative=i,ye(this,"body",n),ye(this,"ignoreCase",s),ye(this,"regexPrefix",c)}get regex(){let t=rn+Te;return this[t]?this[t]:this._make(Te,t)}get checkRegex(){let t=rn+rt;return this[t]?this[t]:this._make(rt,t)}_make(t,r){let n=this.regexPrefix.replace(qi,Wi[t]),s=this.ignoreCase?new RegExp(n,"i"):new RegExp(n);return ye(this,r,s)}},Ui=({pattern:e,mark:t},r)=>{let n=!1,s=e;s.indexOf("!")===0&&(n=!0,s=s.substr(1)),s=s.replace(Di,"!").replace(ki,"#");let i=Xi(s);return new It(e,t,s,r,n,i)},Mt=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[on]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if(nt(t)&&(t={pattern:t}),zi(t.pattern)){let r=Ui(t,this._ignoreCase);this._added=!0,this._rules.push(r)}}add(t){return this._added=!1,nn(nt(t)?Ki(t):t).forEach(this._add,this),this._added}test(t,r,n){let s=!1,i=!1,c;this._rules.forEach(h=>{let{negative:d}=h;i===d&&s!==i||d&&!s&&!i&&!r||!h[n].test(t)||(s=!d,i=d,c=d?Oi:h)});let a={ignored:s,unignored:i};return c&&(a.rule=c),a}},Qi=(e,t)=>{throw new t(e)},oe=(e,t,r)=>nt(e)?e?oe.isNotRelative(e)?r(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:r("path must not be empty",TypeError):r(`path must be a string, but got \`${t}\``,TypeError),ln=e=>Ii.test(e);oe.isNotRelative=ln;oe.convert=e=>e;var Nt=class{constructor({ignorecase:t=!0,ignoreCase:r=t,allowRelativePaths:n=!1}={}){ye(this,on,!0),this._rules=new Mt(r),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(t){return this._rules.add(t)&&this._initCache(),this}addPattern(t){return this.add(t)}_test(t,r,n,s){let i=t&&oe.convert(t);return oe(i,t,this._strictPathCheck?Qi:un),this._t(i,r,n,s)}checkIgnore(t){if(!Mi.test(t))return this.test(t);let r=t.split(me).filter(Boolean);if(r.pop(),r.length){let n=this._t(r.join(me)+me,this._testCache,!0,r);if(n.ignored)return n}return this._rules.test(t,!1,rt)}_t(t,r,n,s){if(t in r)return r[t];if(s||(s=t.split(me).filter(Boolean)),s.pop(),!s.length)return r[t]=this._rules.test(t,n,Te);let i=this._t(s.join(me)+me,r,n,s);return r[t]=i.ignored?i:this._rules.test(t,n,Te)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return nn(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},Gt=e=>new Nt(e),Vi=e=>oe(e&&oe.convert(e),e,un),cn=()=>{let e=r=>/^\\\\\?\\/.test(r)||/["<>|\u0000-\u001F]+/u.test(r)?r:r.replace(/\\/g,"/");oe.convert=e;let t=/^[a-z]:\//i;oe.isNotRelative=r=>t.test(r)||ln(r)};typeof process<"u"&&process.platform==="win32"&&cn();st.exports=Gt;Gt.default=Gt;st.exports.isPathValid=Vi;ye(st.exports,Symbol.for("setupWindows"),cn)});g();var Xr=ut(Nr(),1);import O from"node:path";import ie from"node:fs";import{spawn as li}from"node:child_process";g();import si from"node:crypto";var X=new Map,ee=new Map,ii=256,oi=5e4,Gr=(e,t,r,n,s=!0)=>{let i=si.createHash("sha256");return i.update(e),i.update(t),i.update(s?"gitignore":"no-gitignore"),r!==void 0&&i.update(String(r)),n!==void 0&&i.update(`maxFiles:${n}`),i.digest("hex")},jr=e=>{let t=X.get(e);return t!==void 0&&(X.delete(e),X.set(e,t)),t},Ve=(e,t,r)=>{for(ee.has(e)&&clearTimeout(ee.get(e));X.size>=ii&&!X.has(e);){let i=X.keys().next().value;i&&(X.delete(i),ee.has(i)&&(clearTimeout(ee.get(i)),ee.delete(i)))}let n=0;for(let[i,c]of X)i!==e&&(n+=c.length);for(;n+t.length>oi&&X.size>0;){let i,c=0;for(let[a,h]of X)a!==e&&h.length>c&&(c=h.length,i=a);if(i)n-=X.get(i).length,X.delete(i),ee.has(i)&&(clearTimeout(ee.get(i)),ee.delete(i));else break}X.has(e)&&X.delete(e),X.set(e,t);let s=setTimeout(()=>{X.delete(e),ee.delete(e)},r);ee.set(e,s)};function ve(e){return e.split(O.sep).join(O.posix.sep)}function vt(e,t=!1){let r=ve(e);for(;r.startsWith("./");)r=r.slice(2);return t?r.replace(/\/+$/,""):r}function zr(){return process.platform==="win32"||process.platform==="darwin"}function ci(e,t){let r=e.replace(/\/+$/,""),n=t.replace(/\/+$/,"");return r===n?!0:zr()?r.toLowerCase()===n.toLowerCase():!1}function ai(e,t){let r=`${t}/`;if(e.startsWith(r)){let n=e.slice(r.length);return n===""?null:n}if(zr()){let n=`${t.toLowerCase()}/`;if(e.toLowerCase().startsWith(n)){let i=e.slice(n.length);return i===""?null:i}}return null}var fi=5e3,hi=3e4,di=200,pi=50,xe=4096,Tt=new Map;function gi(e){for(;e.size>di;){let t=e.keys().next().value;if(t===void 0)break;e.delete(t)}}function _i(e,t){let r=e.get(t);if(r){if(Date.now()-r.cachedAt>hi){e.delete(t);return}return r.value}}function Re(e,t,r){e.set(t,{value:r,cachedAt:Date.now()}),gi(e)}function bi(e){let t=e.trim();return t.length<=xe?t:`${t.slice(0,xe)}\u2026`}function Ri(e){return e.map(t=>/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("/")&&t.length>1?"<abs-path>":t.includes(O.sep)&&t.length>32?"<path>":t).join(" ")}function Ye(e,t,r,n){let s=[`[crawler] ${e}:`,t,Ri(r)];n.code!==void 0&&n.code!==null&&s.push(`exit=${String(n.code)}`),n.stderr&&n.stderr.length>0&&s.push(bi(n.stderr)),console.warn(s.join(" "))}function et(e){return["-c","core.fsmonitor=false","-c","core.untrackedCache=false","-c","core.quotePath=false",...e]}function Ze(e){return ve(O.resolve(e))}function mi(e){return[Ze(e.crawlDirectory),Ze(e.cwd),e.ignore.getFingerprint(),e.useGitignore===!1?"no-gitignore":"gitignore",e.maxDepth===void 0?"undefined":String(e.maxDepth),e.maxFiles===void 0?"undefined":String(e.maxFiles)].join("|")}function Br(e){let t=Tt.get(e);return t===void 0?!1:Date.now()-t<fi}function Ot(e){Tt.set(e,Date.now())}var ae=new Map,he=new Map;function yi(){for(;ae.size>=pi;){let e=ae.keys().next().value;if(e===void 0)break;ae.delete(e),Tt.delete(e)}}function Ai(e){let t=Ze(e),r=_i(he,t);if(r!==void 0)return r;let n=e;for(;n;){let s=O.join(n,".git");try{let c=ie.statSync(s);if(c.isDirectory())return Re(he,t,s),s;if(c.isFile()){let h=ie.readFileSync(s,"utf8").trim().match(/^gitdir:\s*(.+)$/i);if(!h)return Re(he,t,null),null;let d=h[1].trim(),b=O.isAbsolute(d)?O.resolve(d):O.resolve(n,d);try{b=ie.realpathSync(b);try{ie.statSync(O.join(b,"HEAD"))}catch{ie.statSync(O.join(b,"index"))}}catch{return Re(he,t,null),null}return Re(he,t,b),b}}catch(c){if(c.code!=="ENOENT")return Re(he,t,null),null}let i=O.dirname(n);if(i===n)break;n=i}return Re(he,t,null),null}function tt(e){try{let t=Ai(e);if(!t)return null;let r=O.join(t,"index");return ie.statSync(r).mtimeMs}catch{}return null}function Ei(e,t){let r=tt(t),n=ae.get(e);return n?r!==null&&n.gitRootMtimeMs!==null?r<n.gitRootMtimeMs||!Br(e):r===null&&n.gitRootMtimeMs===null?!Br(e):!0:!0}function Si(e,t){let r=ae.get(e);if(!r)return;let n=tt(t);ae.set(e,{...r,gitRootMtimeMs:n})}function Lt(e,t,r,n,s){yi();let i=tt(t);ae.set(e,{gitRootMtimeMs:i,untrackedFingerprint:n===void 0?null:Je(n),deletedFingerprint:s===void 0?null:Je(s),fileList:r})}function Je(e){let t=5381;for(let r of e){for(let n=0;n<r.length;n++)t=(t<<5)+t+r.charCodeAt(n)>>>0;t=(t<<5)+t+10>>>0}return`${e.length}:${t}`}function xi(e,t=[0]){return e!==null&&t.includes(e)}function Ci(e,t,r,n=2e4,s){let i=s?.collectLines!==!1;return new Promise(c=>{let a=[],h=!1,d=!1,b=!1,E="",S=0,D=(A,P)=>{h||(h=!0,c({success:A,lines:P}))},R="",y;try{y=li(e,t,{cwd:r,windowsHide:!0,stdio:["ignore","pipe","pipe"],...e==="git"?{env:{...process.env,GIT_DIR:void 0,GIT_WORK_TREE:void 0,GIT_INDEX_FILE:void 0}}:{}})}catch(A){s?.silentOnFailure||Ye("command spawn threw",e,t,{stderr:A instanceof Error?A.message:String(A)}),D(!1,[]);return}y.stderr&&(y.stderr.setEncoding("utf8"),y.stderr.on("data",A=>{R.length<xe&&(R+=A,R.length>xe&&(R=R.slice(0,xe)))}));let $=()=>{if(!y.killed)try{y.kill()}catch{}},C=A=>{let P=A.endsWith("\r")?A.slice(0,-1):A;if(P.length===0)return!0;if(s?.onLine&&!s.onLine(P))return b=!0,$(),!1;i&&a.push(P),S++;let F=s?.yieldEveryLines;return F!==void 0&&F>0&&S%F===0&&y.stdout&&typeof y.stdout.pause=="function"&&(y.stdout.pause(),setImmediate(()=>{try{y.stdout?.resume()}catch{}})),!0},v=A=>{if(E+=A,(s?.recordDelimiter??`
|
|
4
|
-
`)==="\0"){for(;;){let F=E.indexOf("\0");if(F===-1)break;let m=E.slice(0,F);if(E=E.slice(F+1),!C(m))break}return}for(;;){let F=E.indexOf(`
|
|
5
|
-
`);if(F===-1)break;let m=E.slice(0,F);if(E=E.slice(F+1),!C(m))break}},L=()=>{E.length!==0&&(C(E),E="")},W;n>0&&(W=setTimeout(()=>{d=!0,$()},n)),y.stdout.setEncoding("utf8"),y.stdout.on("data",A=>{v(A)}),y.on("error",A=>{W&&clearTimeout(W),s?.silentOnFailure||Ye("command spawn failed",e,t,{stderr:`${String(A.code??"")} ${String(A)}`.trim()}),D(!1,[])}),y.on("close",A=>{if(W&&clearTimeout(W),b){D(!0,a);return}if(d){s?.silentOnFailure||Ye("command timed out",e,t,{code:A,stderr:R}),D(!1,[]);return}L();let P=xi(A,s?.successExitCodes);!P&&!s?.silentOnFailure&&Ye("command failed",e,t,{code:A,stderr:R}),D(P,P?a:[])})})}var $e=Ci;function Pe(e){return ve(e)}function de(e,t){let r=O.resolve(e),n=O.resolve(t),s=r,i=n;try{s=ie.realpathSync(r)}catch{}try{i=ie.realpathSync(n)}catch{}let c=O.relative(s,i),a=ve(c);return a===""?".":a}function we(e){return!e||e==="."||O.posix.isAbsolute(e)?!1:e!==".."&&!e.startsWith("../")&&!e.includes("/../")}function wi(e,t){let r=O.resolve(e),n=O.isAbsolute(t)?t:O.join(r,t),s=O.relative(r,n);return s=ve(s),!s||s.startsWith("..")||O.posix.isAbsolute(s)?null:we(s)?s:null}function Kr(e){if(e===".")return-1;let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0?-1:t.split("/").length-1}function Ur(e,t){if(e==="."||t===""||t===".")return e;let r=t.endsWith("/")?t:`${t}/`;return e===t?".":e.startsWith(r)?e.slice(r.length)||".":e}function Ft(e,t,r,n){let s=t.maxDepth,i=t.ignore.getDirectoryFilter(),c=t.ignore.getFileFilter();return e.filter(a=>{if(s!==void 0&&a!=="."){let h=r?Ur(a,r):a;if(Kr(h)>s)return!1}return a==="."?!0:a.endsWith("/")?we(a.slice(0,-1))?!i(a):!1:n?.has(a)?!0:!we(a)||Qr(a,i)?!1:!c(a)})}function Qr(e,t){let r=e.split("/"),n="";for(let s=0;s<r.length-1;s++)if(n=n?`${n}/${r[s]}`:r[s],t(`${n}/`))return!0;return!1}var Vr=1e3;async function vi(e){e>0&&e%Vr===0&&await new Promise(t=>setImmediate(t))}async function Yr(e){let t=await $e("git",et(["rev-parse","--show-toplevel"]),e,5e3,{silentOnFailure:!0});return!t.success||t.lines.length===0?null:Pe(t.lines[0])}function $t(e,t,r){return!(!we(e)||Qr(e,t)||r(e))}function Ce(e,t){return t!==void 0&&e>=t}function Pt(e,t,r){if(r===void 0)return!0;let n=Ur(e,t);return Kr(n)<=r}async function Zr(e,t,r){let n=["--literal-pathspecs","ls-files","-z","--others"];r&&n.push("--exclude-standard"),t&&t!=="."&&n.push(t);let s=await $e("git",et(n),e,1e4,{silentOnFailure:!0,recordDelimiter:"\0"});return s.success?s.lines.map(i=>Pe(i)):null}async function Jr(e,t){let r=["--literal-pathspecs","ls-files","-z","--deleted"];t&&t!=="."&&r.push(t);let n=await $e("git",et(r),e,1e4,{silentOnFailure:!0,recordDelimiter:"\0"});return n.success?n.lines.map(s=>Pe(s)):null}async function qr(e,t,r){if(e.gitRootMtimeMs===null&&e.untrackedFingerprint===null&&e.deletedFingerprint===null)return{changed:!1};let n=await Yr(t);if(e.untrackedFingerprint===null&&e.deletedFingerprint===null)return n?{changed:!0}:{changed:!1};if(!n)return{changed:!0};let s=de(n,t),[i,c]=await Promise.all([Zr(n,s,r),Jr(n,s)]);return i===null||c===null?{changed:!0}:Je(i)!==e.untrackedFingerprint||Je(c)!==e.deletedFingerprint?{changed:!0,prefetch:{gitRoot:n,untrackedFiles:i,deletedFiles:c}}:{changed:!1}}function Wr(e,t,r,n,s){let i=vt(e,!1);if(t&&t!=="."){let c=ai(i,n);if(c!==null)return O.posix.join(s,c);if(ci(i,n))return`${i.replace(/\/+$/,"")}/`;let a=i.replace(/\/+$/,"");return O.posix.join(s,a)}return O.posix.join(s,i.replace(/\/+$/,""))}async function $i(e,t,r,n,s){let i,c,a;if(s)i=s.gitRoot,c=s.untrackedFiles,a=s.deletedFiles;else{if(i=await Yr(t),!i)return{success:!1,files:[],gitRepoListingFailed:!1};let _=de(i,t),o=await Promise.all([Zr(i,_,n.useGitignore!==!1),Jr(i,_)]);c=o[0],a=o[1]}if(!i)return{success:!1,files:[],gitRepoListingFailed:!1};if(!s&&(c===null||a===null))return{success:!1,files:[],gitRepoListingFailed:!0};let h=de(r,t),d=de(i,t),b=vt(d,!0),E=vt(h,!0),S=n.ignore.getDirectoryFilter(),D=n.ignore.getFileFilter(),R=["--literal-pathspecs","ls-files","--cached","--recurse-submodules"];R.push("-t"),d&&d!=="."&&R.push(d);let y=new Set(a),$=new Set,C=0,v=_=>_.length===0?null:_.length>=3&&/\s/.test(_[1])&&/[A-Za-z]/.test(_[0])?{status:_[0].toUpperCase(),filePath:_.slice(2)}:{status:null,filePath:_},L=_=>{if(Ce(C,n.maxFiles))return!1;let o=v(_);if(!o||o.status==="S")return!0;let B=Pe(o.filePath);if(y.has(B))return!0;let M;try{M=ie.lstatSync(O.join(i,...B.split("/")))}catch{return!0}if(M.isDirectory()||d&&d!=="."&&B===d)return!0;let k=Wr(B,d,h,b,E);if(!$t(k,S,D))return!0;let u=$.size;return $.add(k),$.size>u&&Pt(k,h,n.maxDepth)&&C++,!Ce(C,n.maxFiles)},W=await $e("git",et(R),i,2e4,{collectLines:!1,onLine:L,yieldEveryLines:Vr});if(!W.success)return{success:!1,files:[],gitRepoListingFailed:!0};for(let _ of W.lines)if(!L(_))break;let A=0;if(c!==null)for(let _ of c){if(Ce(C,n.maxFiles))break;await vi(A++);let o=Wr(_,d,h,b,E);$t(o,S,D)&&($.has(o)||($.add(o),Pt(o,h,n.maxDepth)&&C++))}let P=en($),F=Ft(P,n,h,$),m=Dt(F,n.maxFiles);return Lt(e,t,m,c===null?void 0:c,a===null?void 0:a),Ot(e),{success:!0,files:m}}function en(e){let t=new Set;for(let r of e){let n=r.split("/"),s="";for(let i=0;i<n.length-1;i++)s=s?s+"/"+n[i]:n[i],t.add(s+"/")}return[".",...Array.from(t),...Array.from(e)]}async function Pi(e,t,r,n){let s=["--files","--no-require-git","--hidden"];n.useGitignore===!1&&s.push("--no-ignore");let i=de(r,t),c=n.ignore.getDirectoryFilter(),a=n.ignore.getFileFilter(),h=new Set,d=0,b=y=>{if(Ce(d,n.maxFiles))return!1;let $=Pe(y),C=O.posix.join(i,$);if(!$t(C,c,a))return!0;let v=h.size;return h.add(C),h.size>v&&Pt(C,i,n.maxDepth)&&d++,!Ce(d,n.maxFiles)},E=await $e("rg",s,t,2e4,{collectLines:!1,onLine:b,successExitCodes:[0,1]});if(!E.success)return{success:!1,files:[]};for(let y of E.lines)if(!b(y))break;let S=en(h),D=Ft(S,n,i,h),R=Dt(D,n.maxFiles);return Lt(e,t,R),Ot(e),{success:!0,files:R}}async function Ti(e){let t=de(e.cwd,e.crawlDirectory),r;try{let s=e.ignore.getDirectoryFilter(),i=e.ignore.getFileFilter(),c=new Xr.fdir().withRelativePaths().withDirs().withPathSeparator("/").exclude((a,h)=>{let d=wi(e.crawlDirectory,h);return d?s(`${d}/`):!1}).filter((a,h)=>{if(h)return!0;let d=O.posix.join(t,a);return we(d)?!i(d):!1});e.maxDepth!==void 0&&c.withMaxDepth(e.maxDepth),r=await c.crawl(e.crawlDirectory).withPromise()}catch{return[]}let n=r.filter(s=>s.length>0&&s!==".").map(s=>O.posix.join(t,s));if(t!=="."){let s=t.endsWith("/")?t:`${t}/`;if(!n.includes(s))return[s,...n]}return n}async function eu(e){let t=mi(e),r=e.cache?Gr(Ze(e.crawlDirectory),e.ignore.getFingerprint(),e.maxDepth,e.maxFiles,e.useGitignore!==!1):void 0;if(e.cache){let d=jr(r);if(d)return d}let n;if(!e.cache){let d=ae.get(t);if(d){let b=tt(e.crawlDirectory);if(b!==null&&d.gitRootMtimeMs!==null&&b>d.gitRootMtimeMs){let S=await qr(d,e.crawlDirectory,e.useGitignore!==!1);if(!S.changed)return Si(t,e.crawlDirectory),d.fileList;n=S.prefetch}else if(!Ei(t,e.crawlDirectory)){let S=await qr(d,e.crawlDirectory,e.useGitignore!==!1);if(!S.changed)return d.fileList;n=S.prefetch}}}let s=await $i(t,e.crawlDirectory,e.cwd,e,n);if(s.success){let d=s.files;return e.cache&&Ve(r,d,e.cacheTtl*1e3),d}s.gitRepoListingFailed&&console.warn("[crawler] falling back to ripgrep (git ls-files unavailable)");let i=await Pi(t,e.crawlDirectory,e.cwd,e);if(i.success){let d=i.files;return e.cache&&Ve(r,d,e.cacheTtl*1e3),d}console.warn("[crawler] falling back to fdir (ripgrep unavailable)");let c=de(e.cwd,e.crawlDirectory),a=await Ti(e);a=Ft(a,e,c),a.length===0?a=["."]:a[0]!=="."&&(a=[".",...a]);let h=Dt(a,e.maxFiles);return Lt(t,e.crawlDirectory,h),Ot(t),e.cache&&Ve(r,h,e.cacheTtl*1e3),h}function Dt(e,t){if(t===void 0||e.length<=t)return e;let r=e.slice(0,t),n=i=>i!=="."&&!i.endsWith("/");if(r.some(n))return r;let s=e.findIndex(n);return s===-1?r:e.slice(0,s+1)}g();var jt=ut(an(),1),hn=ut(Ct(),1);import it from"node:fs";import fn from"node:path";var Yi=(0,hn.default)("**/*[*.]*"),Zi=[".git","node_modules",".venv","venv","__pycache__",".mypy_cache",".pytest_cache",".ruff_cache",".next",".nuxt",".turbo",".cache","target",".gradle",".terraform"];function uu(e){let t=new Bt,r=new Set([...Zi,...e.ignoreDirs]);if(t.add([...r].map(n=>n.endsWith("/")?n:`${n}/`)),e.useGitignore){let n=fn.join(e.projectRoot,".gitignore");it.existsSync(n)&&t.add(it.readFileSync(n,"utf8"))}if(e.useMatildaignore){let n=fn.join(e.projectRoot,".matildaignore");it.existsSync(n)&&t.add(it.readFileSync(n,"utf8"))}return t}var Bt=class{allPatterns=[];dirIgnorer=(0,jt.default)();fileIgnorer=(0,jt.default)();add(t){typeof t=="string"&&(t=t.split(/\r?\n/));for(let r of t){let n=r.trim();if(n===""||n.startsWith("#"))continue;this.allPatterns.push(n),n.endsWith("/")&&!n.startsWith("!")?this.dirIgnorer.add(n):(this.fileIgnorer.add(n),Yi(n)||this.dirIgnorer.add(n))}return this}getDirectoryFilter(){return t=>this.dirIgnorer.ignores(t)}getFileFilter(){return t=>this.fileIgnorer.ignores(t)}getFingerprint(){return this.allPatterns.join(`
|
|
6
|
-
`)}};export{Ct as a,an as b,eu as c,uu as d};
|
|
7
|
-
/**
|
|
8
|
-
* @license
|
|
9
|
-
* Copyright 2025 Google LLC
|
|
10
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
11
|
-
*/
|