@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
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{a as f}from"./chunk-GT6MSEK4.js";import{b as g}from"./chunk-PFXCFIHY.js";import{H as d,P as m,ea as p}from"./chunk-WL27X35X.js";import{b as u}from"./chunk-GZPNIYVZ.js";u();import*as a from"node:fs/promises";import*as s from"node:path";var x=p("CRON_TASKS_FILE"),T="scheduled_tasks.json",L=`~/.matilda/tmp/<project-hash>/${T}`,E=15,w=2e3,b=3e3,P=0,h=new Map;function C(e){let t=h.get(e);return t||(t=new f,h.set(e,t)),t}function c(e){return s.join(m.getGlobalTempDir(),d(e),T)}async function k(e){let t=c(e),i;try{i=await a.readFile(t,"utf-8")}catch(o){if(o.code==="ENOENT")return[];throw o}let r;try{r=JSON.parse(i)}catch{throw new Error(`Malformed JSON in ${t} \u2014 fix or delete the file; refusing to treat it as an empty schedule.`)}if(!Array.isArray(r))throw new Error(`Expected a JSON array in ${t} \u2014 fix or delete the file; refusing to treat it as an empty schedule.`);let n=r.filter(A);return n.length!==r.length&&x.warn(`Dropped ${r.length-n.length} invalid task entr${r.length-n.length===1?"y":"ies"} from ${t}; a later write will persist without ${r.length-n.length===1?"it":"them"}.`),n}async function D(e,t){let i=c(e);await a.mkdir(s.dirname(i),{recursive:!0}),await g(i,t,{noFollow:!0})}async function _(e){let t=`${e}.lock`;await a.mkdir(s.dirname(t),{recursive:!0});let i=Date.now()+b;for(;;){if(Date.now()>i)throw new Error(`Timed out waiting for scheduled-tasks lock (${t})`);try{return await a.writeFile(t,String(process.pid),{flag:"wx"}),async()=>{await a.unlink(t).catch(()=>{})}}catch(r){if(r.code!=="EEXIST")throw r}try{let r=await a.stat(t);if(Date.now()-r.mtimeMs>w){let n=`${t}.stale.${process.pid}.${P++}`;try{await a.rename(t,n)}catch{continue}let o=await a.stat(n).catch(()=>null);o&&Date.now()-o.mtimeMs<=w&&await a.link(n,t).catch(()=>{}),await a.unlink(n).catch(()=>{});continue}}catch{continue}await new Promise(r=>setTimeout(r,E))}}async function y(e,t){let i=c(e);return C(i).runExclusive(async()=>{let r=await _(i);try{let n=await k(e),o=t(n);o!==n&&await D(e,o)}finally{await r()}})}async function F(e,t){await y(e,i=>[...i,t])}async function J(e,t){let i=new Set(t);if(!(await k(e)).some(o=>i.has(o.id)))return 0;let n=0;return await y(e,o=>{let l=o.filter(S=>!i.has(S.id));return n=o.length-l.length,n===0?o:l}),n}function A(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.cron=="string"&&typeof t.prompt=="string"&&typeof t.recurring=="boolean"&&typeof t.createdAt=="number"&&(t.lastFiredAt===null||typeof t.lastFiredAt=="number")}export{L as a,c as b,k as c,y as d,F as e,J as f};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{l as i}from"./chunk-
|
|
3
|
+
import{l as i}from"./chunk-HJK3NKAR.js";import{b as o}from"./chunk-GZPNIYVZ.js";o();import l from"node:path";function d(t,n){if(t.getApprovalMode()!=="bogan")return null;let r=l.resolve(n),s=t.getProjectRoot?.()??t.getTargetDir();if(i(r,s))return null;let e=t.getWorkspaceContext?.();if(!e||(typeof e.isPathWithinWorkspaceFresh=="function"?e.isPathWithinWorkspaceFresh(r):e.isPathWithinWorkspace(r)))return null;let a=e.getDirectories?.()??[t.getTargetDir()],p=t.getChannel?.()==="desktop"?"Approve the folder from Matilda Desktop, then retry the write.":"Use --include-directories to add extra roots, or a non-BOGAN approval mode for intentional external writes.";return`Refusing out-of-workspace write in BOGAN mode: ${r}. Workspace root(s): ${a.join(", ")}. This blocks path typos (e.g. writing under $HOME when the project is elsewhere). `+p}export{d as a};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Matilda Team
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{a as w,d as re}from"./chunk-225CZWD7.js";import{a as Zn,d as eo,n as ot,o as Jt,p as io,r as Oe,s as so,t as pe,u as V,x as ct}from"./chunk-WUMI5YVV.js";import{Aa as Qt,Ca as Zt,I as fe,K as rt,L as it,M as st,U as at,V as ie,ha as lt,ia as ut,qa as Y,qb as en,rb as tn,tb as nn,ya as Xt}from"./chunk-IXILJSRE.js";import{P as tt,Q as oo,V as ro,d as to,e as no,ea as L,f as B,g as Ie,k as et,r as ce,w as de}from"./chunk-WL27X35X.js";import{h as j,i as nt,k as qt,m as Yt}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 ao(t){return/^[0-9A-Fa-f]$/.test(t)}function X(t){return t>="0"&&t<="9"}function lo(t){return t>=" "}function Pe(t){return`,:[]/{}()
|
|
4
|
+
+`.includes(t)}function on(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function rn(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var sn=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,an=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function ln(t){return`,[]/{}
|
|
5
|
+
+`.includes(t)}function un(t){return De(t)||ni.test(t)}var ni=/^[[{\w-]$/;function uo(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 co(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function po(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function De(t){return cn(t)||dt(t)}function cn(t){return t==='"'||t==="\u201C"||t==="\u201D"}function dn(t){return t==='"'}function dt(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function pn(t){return t==="'"}function ge(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 fo(t,e,n){return t.substring(0,e)+t.substring(e+n)}function go(t){return/[,\n][ \t\r]*$/.test(t)}var oi={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},ri={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
7
|
+
`,r:"\r",t:" "};function pt(t){let e=0,n="";u(["```","[```","{```"]),i()||ne(),u(["```","```]","```}"]);let r=f(",");for(r&&s(),un(t[e])&&go(n)?(r||(n=F(n,",")),C()):r&&(n=ge(n,","));t[e]==="}"||t[e]==="]";)e++,s();if(e>=t.length)return n;Qe();function i(){s();let T=g()||y()||S()||M()||b()||K(!1)||ee();return s(),T}function s(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,A=e,R=a(T);do R=l(),R&&(R=a(T));while(R);return e>A}function a(T){let A=T?J:co,R="";for(;;)if(A(t,e))R+=t[e],e++;else if(po(t,e))R+=" ",e++;else break;return R.length>0?(n+=R,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!ii(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 u(T){if(c(T)){if(on(t[e]))for(;e<t.length&&rn(t[e]);)e++;return s(),!0}return!1}function c(T){a(!0);for(let A of T){let R=e+A.length;if(t.slice(e,R)===A)return e=R,!0}return!1}function f(T){return t[e]===T?(n+=t[e],e++,!0):!1}function d(T){return t[e]===T?(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 T=!0;for(;e<t.length&&t[e]!=="}";){let A;if(T?(A=!0,T=!1):(A=f(","),A||(n=F(n,",")),s()),h(),!(S()||K(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?n=ge(n,","):N();break}s();let Ze=f(":"),oe=e>=t.length;Ze||(un(t[e])||oe?n=F(n,":"):we()),i()||(Ze||oe?n+="null":we())}return t[e]==="}"?(n+="}",e++):n=F(n,"}"),!0}return!1}function y(){if(t[e]==="["){n+="[",e++,s(),d(",")&&s();let T=!0;for(;e<t.length&&t[e]!=="]";)if(T?T=!1:f(",")||(n=F(n,",")),h(),!i()){n=ge(n,",");break}return t[e]==="]"?(n+="]",e++):n=F(n,"]"),!0}return!1}function C(){let T=!0,A=!0;for(;A;)T?T=!1:f(",")||(n=F(n,",")),A=i();A||(n=ge(n,",")),n=`[
|
|
9
|
+
${n}
|
|
10
|
+
]`}function S(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,R=t[e]==="\\";if(R&&(e++,R=!0),De(t[e])){let Ze=dn(t[e])?dn:pn(t[e])?pn:dt(t[e])?dt:cn,oe=e,xe=n.length,k='"';for(e++;;){if(e>=t.length){let O=P(e-1);return!T&&Pe(t.charAt(O))?(e=oe,n=n.substring(0,xe),S(!0)):(k=F(k,'"'),n+=k,!0)}if(e===A)return k=F(k,'"'),n+=k,!0;if(Ze(t[e])){let O=e,Ht=k.length;if(k+='"',e++,n+=k,s(!1),T||e>=t.length||Pe(t[e])||De(t[e])||X(t[e]))return E(),!0;let q=P(O-1),Qn=t.charAt(q);if(Qn===",")return e=oe,n=n.substring(0,xe),S(!1,q);if(Pe(Qn))return e=oe,n=n.substring(0,xe),S(!0);n=n.substring(0,xe),e=O+1,k=`${k.substring(0,Ht)}\\${k.substring(Ht)}`}else if(T&&ln(t[e])){if(t[e-1]===":"&&sn.test(t.substring(oe+1,e+2)))for(;e<t.length&&an.test(t[e]);)k+=t[e],e++;return k=F(k,'"'),n+=k,E(),!0}else if(t[e]==="\\"){let O=t.charAt(e+1);if(ri[O]!==void 0)k+=t.slice(e,e+2),e+=2;else if(O==="u"){let q=2;for(;q<6&&ao(t[e+q]);)q++;q===6?(k+=t.slice(e,e+6),e+=6):e+q>=t.length?e=t.length:ti()}else k+=O,e+=2}else{let O=t.charAt(e);O==='"'&&t[e-1]!=="\\"?(k+=`\\${O}`,e++):uo(O)?(k+=oi[O],e++):(lo(O)||te(O),k+=O,e++)}R&&m()}}return!1}function E(){let T=!1;for(s();t[e]==="+";){T=!0,e++,s(),n=ge(n,'"',!0);let A=n.length;S()?n=fo(n,A,1):n=F(n,'"')}return T}function M(){let T=e;if(t[e]==="-"){if(e++,ue())return I(T),!0;if(!X(t[e]))return e=T,!1}for(;X(t[e]);)e++;if(t[e]==="."){if(e++,ue())return I(T),!0;if(!X(t[e]))return e=T,!1;for(;X(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,ue())return I(T),!0;if(!X(t[e]))return e=T,!1;for(;X(t[e]);)e++}if(!ue())return e=T,!1;if(e>T){let A=t.slice(T,e),R=/^0\d/.test(A);return n+=R?`"${A}"`:A,!0}return!1}function b(){return _("true","true")||_("false","false")||_("null","null")||_("True","true")||_("False","false")||_("None","null")}function _(T,A){return t.slice(e,e+T.length)===T?(n+=A,e+=T.length,!0):!1}function K(T){let A=e;if(on(t[e])){for(;e<t.length&&rn(t[e]);)e++;let R=e;for(;J(t,R);)R++;if(t[R]==="(")return e=R+1,i(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!ln(t[e])&&!De(t[e])&&(!T||t[e]!==":");)e++;if(t[e-1]===":"&&sn.test(t.substring(A,e+2)))for(;e<t.length&&an.test(t[e]);)e++;if(e>A){for(;J(t,e-1)&&e>0;)e--;let R=t.slice(A,e);return n+=R==="undefined"?"null":JSON.stringify(R),t[e]==='"'&&e++,!0}}function ee(){if(t[e]==="/"){let T=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=`"${t.substring(T,e)}"`,!0}}function P(T){let A=T;for(;A>0&&J(t,A);)A--;return A}function ue(){return e>=t.length||Pe(t[e])||J(t,e)}function I(T){n+=`${t.slice(T,e)}0`}function te(T){throw new z(`Invalid character ${JSON.stringify(T)}`,e)}function Qe(){throw new z(`Unexpected character ${JSON.stringify(t[e])}`,e)}function ne(){throw new z("Unexpected end of json string",t.length)}function N(){throw new z("Object key expected",e)}function we(){throw new z("Colon expected",e)}function ti(){let T=t.slice(e,e+6);throw new z(`Invalid unicode character "${T}"`,e)}}function ii(t,e){return t[e]==="*"&&t[e+1]==="/"}var si=L("JSON_PARSE");function ai(t,e={}){if(!t||typeof t!="string")return e;try{return JSON.parse(t)}catch(n){let o=li(t);if(o!==void 0)return o;try{let r=pt(t);return JSON.parse(r)}catch(r){let i=Co(t);if(i&&i!==t)try{return JSON.parse(pt(i))}catch{}return si.error("Failed to parse JSON even with jsonrepair:",{originalError:n,repairError:r,jsonString:t}),e}}}var mo=Symbol("tool-args-parse-failed");function ho(t){if(t==null)return{};let e=typeof t=="string"?t.trim():"";if(!e)return{};let n=ai(e,mo);return n===mo?null:n&&typeof n=="object"&&!Array.isArray(n)?n:null}function li(t){let e=Co(t);if(e&&e!==t.trim())try{return JSON.parse(e)}catch{return}}function Co(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 ui=/[A-Za-z\u00C0-\u024F]/g;function ci(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 fn(t){let e=t.codePointAt(0);return e!==void 0&&ci(e)}function di(t){let e=t.match(ui)?.length??0;if(e<24)return!1;let n=0;for(let o of t)fn(o)&&n++;return n===0||e>=n*8}function ft(t){if(!t||!di(t))return t;let e="",n=0,o=[...t];for(;n<o.length;){if(!fn(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&&fn(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 me=L("TAGGED_THINKING_PARSER"),Ue=["<think>","<thinking>"],Le=["</think>","</thinking>"],pi=Math.max(...Ue.map(t=>t.length),...Le.map(t=>t.length));function Ne(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function gt(t,e,n){let o=t.length-e;return o<=0||o>pi?!1:n.some(r=>r.startsWith(t.slice(e,e+o)))}function mt(t,e,n){return n.find(o=>t.startsWith(o,e))}function mn(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 yo(t){let e=[];for(let n of t){if(n.thought===!0||typeof n.text!="string"){e.push(n);continue}let o=ft(mn(n.text));(o.length>0||/^\s+$/.test(n.text))&&e.push({text:o.length>0?o:n.text})}return e}var gn=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=mt(o,s,Ue);if(a){me.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),Ne(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=mt(o,s,Le);if(l){me.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),Ne(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(gt(o,s,Ue)||gt(o,s,Le)))break}else{let a=mt(o,s,Le);if(a){me.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),Ne(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=mt(o,s,Ue);if(l){s+=l.length;continue}if(!n&&(gt(o,s,Le)||gt(o,s,Ue)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(Ne(r,i,this.mode),this.buffer=this.buffer.slice(s),me.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),yo(r)):(this.buffer="",this.mode==="thought"&&i&&me.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),Ne(r,i,this.mode),me.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),yo(r))}};function To(t){return new gn().parse(t,!0)}p();function So(t,e="auto"){return e==="openapi_30"?fi(t):t}function fi(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 he(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function ht(t){let e=t.candidates||0,n=t.thoughts||0;return n>e?e+n:Math.max(e,n)}function gi(t){return t.total&&t.total>0?Math.max(t.total,(t.prompt||0)+ht(t)):(t.prompt||0)+ht(t)}function mi(t){let e=Math.max(0,t.thoughtsTokens||0),n=ht({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"),_o="(attached media from previous tool call)";function ko(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,u=Math.max(0,e.estimatedReasoningTokens??0),c=Math.max(0,e.estimatedContentTokens??0),f=l>0?l:u,d=o;f>0&&(o>=f?d=o:d=o+f),(c>0||u>0)&&(d=Math.max(d,c+(l>0?0:u),c+f)),r>n&&(n>0||o>0||f>0)&&(d=Math.max(d,r-n)),f===0&&u>0&&(f=u),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 hi=64,Eo=1024;function Ao(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>=Eo&&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>=hi?(e.cumulativeMode=!0,W.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<Eo&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function wo(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 Ci(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=wo(i.parameters)),s&&(s=So(s,e)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function yi(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return Si(t,o),Ei(t.contents,o,e),o=Mo(o),n.cleanOrphanToolCalls&&(o=Ii(o),o=Mo(o)),o}function Ti(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},u=r.join("");u&&(l.reasoning_content=u),s.length>0&&(l.tool_calls=s);let c=xi(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:c,logprobs:null}],usage:d}}function Si(t,e){if(!t.config?.systemInstruction)return;let n=Io(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function Ei(t,e,n){if(Array.isArray(t))for(let o of t)Ro(o,e,n);else t&&Ro(t,e,n)}function Ro(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!vi(t))return;let o=t.parts||[],r=t.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,u=new Set,c=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=xo(d,n);if(m&&r==="user"&&i.push(m),"functionCall"in d&&d.functionCall&&r==="assistant"){let h=d.functionCall.id;if(h){if(u.has(h)){W.debug(`Dropping duplicate functionCall id=${h} while converting content`);continue}u.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(c.has(h))continue;c.add(h)}let g=Ri(d.functionResponse,n);if(g){if(n.splitToolMedia&&Array.isArray(g.content)){let y=[],C=[];for(let S of g.content)S&&(S.type==="image_url"||S.type==="input_audio"||S.type==="video_url"||S.type==="file")?y.push(S):S&&S.type==="text"&&C.push(S);if(y.length>0){let S=C.map(E=>E.text).join(`
|
|
11
|
+
`);g.content=S||"[media attached in following user message]",f.push(...y)}}e.push(g)}}}if(f.length>0&&e.push({role:"user",content:[{type:"text",text:_o},...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 Ai(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 Ri(t,e){let n=Ai(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=xo(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 xo(t,e){let{modalities:n}=e;if(t.inlineData?.mimeType&&t.inlineData?.data){let o=t.inlineData.mimeType,r=bo(o),i=t.inlineData.displayName||o;if(r==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${t.inlineData.data}`}}:se("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}`}}:se("pdf",i,e);if(r==="audio"){if(!n.audio)return se("audio",i,e);let s=bi(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}`}}:se("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=bo(i);if(s==="image")return n.image?{type:"image_url",image_url:{url:r}}:se("image",o,e);if(i==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:r}}:se("pdf",o,e);if(s==="video")return n.video?{type:"video_url",video_url:{url:r}}:se("video",o,e);let a=t.fileData.displayName?` (${t.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${i}${a}.`}}return null}function se(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 bo(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function bi(t){return t.includes("wav")?"wav":t.includes("mp3")||t.includes("mpeg")?"mp3":null}function vi(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&Array.isArray(t.parts)}function Io(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>Io(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 Ct(t,e,n=!0){if(e.taggedThinkingParser)return e.taggedThinkingParser.parse(t,n);if(e.responseParsingOptions?.taggedThinkingTags)return To(t);if(!t)return[];let o=ft(mn(t));return o?[{text:o}]:[]}function Mi(t,e){let n=t.choices?.[0],o=new re;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(...Ct(n.message.content,e)),n.message.tool_calls){for(let i of n.message.tool_calls)if(i.function){let s=ho(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:Oo(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=ko(t.usage,{estimatedReasoningTokens:he(i.length),estimatedContentTokens:he(s.length)})}return o}function _i(t,e){let n=t.choices?.[0],o=new re,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 u=n.delta?.reasoning_content??n.delta?.reasoning;if(u){let c=Ao(u,e.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});c&&i.push({text:c,thought:!0})}}if(typeof n.delta?.content=="string"){let u=Ao(n.delta.content,e.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(u||n.finish_reason)&&i.push(...Ct(u,e,!!n.finish_reason))}else n.finish_reason&&i.push(...Ct("",e,!0));if(n.delta?.tool_calls)for(let u of n.delta.tool_calls){let c=u.index??0;u.function?.arguments?r.addChunk(c,u.function.arguments,u.id,u.function.name):r.addChunk(c,"",u.id,u.function?.name)}let s=!1;if(n.finish_reason){s=r.hasIncompleteToolCalls();let u=r.getCompletedToolCalls();for(let c of u)c.name&&i.push({functionCall:{id:c.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:c.name,args:c.args}})}let a=s&&n.finish_reason!=="length"?"length":n.finish_reason,l={content:{parts:i,role:"model"},index:0,safetyRatings:[]};a&&(l.finishReason=Oo(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=ko(t.usage,wi(e))),o}function ki(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(...Ct("",t,!0)),n.length===0&&!r)return null;let i=new re;return i.candidates=[{content:{parts:n,role:"model"},index:0,safetyRatings:[],finishReason:r?w.MAX_TOKENS:w.STOP}],i.responseId=`stream-flush-${Date.now()}`,i.createTime=new Date().getTime().toString(),i.modelVersion=t.model,i.promptFeedback={safetyRatings:[]},i}function wi(t){return{estimatedReasoningTokens:he(t.reasoningDeltaState?.emittedLength??0),estimatedContentTokens:he(t.textDeltaState?.emittedLength??0)}}function Oo(t){return t?{stop:w.STOP,length:w.MAX_TOKENS,content_filter:w.SAFETY,function_call:w.STOP,tool_calls:w.STOP}[t]||w.FINISH_REASON_UNSPECIFIED:w.FINISH_REASON_UNSPECIFIED}function xi(t){if(!t)return"stop";switch(t){case w.STOP:return"stop";case w.MAX_TOKENS:return"length";case w.SAFETY:case w.RECITATION:case w.BLOCKLIST:case w.PROHIBITED_CONTENT:case w.SPII:case w.IMAGE_SAFETY:case w.IMAGE_RECITATION:case w.IMAGE_PROHIBITED_CONTENT:case w.IMAGE_OTHER:return"content_filter";case w.NO_IMAGE:return"stop";default:return"stop"}}function hn(t){return t.role==="assistant"&&"tool_calls"in t&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0}function vo(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===_o}function Ii(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(hn(l)){let u=[],c=new Set;for(let y of l.tool_calls){let C=y.id;!C||s.has(C)||c.has(C)||(c.add(C),u.push(y))}let f=new Set,d=[],m=[],h=!1;for(let y=a+1;y<t.length;y+=1){let C=t[y];if(C.role==="tool"&&"tool_call_id"in C){if(!C.tool_call_id){h=!1;continue}c.has(C.tool_call_id)&&!f.has(C.tool_call_id)?(f.add(C.tool_call_id),d.push(y),h=!0):h=!1;continue}if(vo(C)){h&&m.push(y);continue}if(!(C.role==="assistant"&&!hn(C)))break}let g=u.filter(y=>f.has(y.id));for(let y of g)s.add(y.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(hn(l)){let u=l.reasoning_content,c=n.get(a)??[];if(c.length>0){let f={...l};f.tool_calls=c,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()||u){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>"}`):vo(l)?W.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):e.push(l)}return e}function Mo(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),u;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}]:[];u=[...f,...d]}else u=[typeof s=="string"?s:"",typeof a=="string"?a:""].filter(Boolean).join("")||null;let c=[...r,...i];o.content=u||null,c.length>0&&(o.tool_calls=c);continue}}e.push(n)}return e}var yt={convertGeminiToolParametersToOpenAI:wo,convertGeminiToolsToOpenAI:Ci,convertGeminiRequestToOpenAI:yi,convertGeminiResponseToOpenAI:Ti,convertOpenAIResponseToGemini:Mi,convertOpenAIChunkToGemini:_i,flushOpenAIStreamToGemini:ki};p();p();var Jl=new Set(["ECONNRESET","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET","ConnectionClosed","ConnectionReset","ConnectionTimedOut"]),Po=new Set(["EAI_AGAIN","ECONNREFUSED","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","UND_ERR_CONNECT_TIMEOUT","ConnectionRefused","FailedToOpenSocket","HostUnreachable","NetworkUnreachable"]);p();var St="NOT_A_PROXY",Oi=/^(?:UND_ERR_SOCKET|HPE_.*|ERR_SSL_(?:WRONG_VERSION_NUMBER|PACKET_LENGTH_TOO_LONG|HTTP_REQUEST|UNKNOWN_PROTOCOL))$/,Pi={"http:":80,"https:":443},Di=/^(?:(?:.+\.)?localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|::1)$/;function Ni(t){let e=t.toLowerCase().replace(/^\*?\./,"");if(e==="*")return{host:"*",wildcard:!0};let n=e.match(/^\[(.+)\](?::(\d+))?$/)??e.match(/^([^:]+):(\d+)$/),o=n?.[1]??e;return n?.[2]?{host:o,port:Number(n[2]),wildcard:!1}:{host:o,wildcard:!1}}function Ui(t){return(t??"").split(/[,\s]+/).filter(Boolean)}function Zl(t){return Ui(t).map(Ni)}function Li(t,e){let n=typeof t=="string"?new URL(t):t,o=n.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(Di.test(o))return!0;let r=n.port?Number(n.port):Pi[n.protocol];return e.some(i=>i.wildcard||(i.port===void 0||i.port===r)&&(o===i.host||o.endsWith(`.${i.host}`)))}function eu(t){let e=t.connect.bind(t);return t.connect=async n=>{try{return await e(n)}catch(o){let{code:r}=o;throw typeof r=="string"&&Oi.test(r)?Object.assign(new Error("The address did not answer as a proxy."),{code:St}):o}},t}var Tt;function tu(t,e=[]){Tt=t?{host:new URL(t).host,noProxy:e}:void 0}function Do(t){return Tt&&URL.canParse(t)&&!Li(t,Tt.noProxy)?Tt.host:void 0}var Fe="MATILDA_BASE_URL",Fi=new Set(["localhost","127.0.0.1","[::1]"]);function H(t){return V(t.trim()).replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}var Lo=new Set;function Fo(t){let e=H(t||G());try{let{origin:n,pathname:o}=new URL(e);return`${n}${o.replace(/\/+$/,"")}`}catch{return e}}function Gi(t){Lo.add(Fo(t))}function lu(t,e=(n,o)=>globalThis.fetch(n,o)){return async(n,o)=>{let r=await e(n,o);return Gi(t),r}}function uu(t){return Lo.has(Fo(t))}function cu(t){try{let{host:e}=new URL(H(t));return e===new URL(Oe).host?"Matilda":e}catch{return t}}function Go(t){let e;try{e=new URL(H(t))}catch{return}if(!(!(e.protocol==="https:"||e.protocol==="http:"&&Fi.has(e.hostname))||e.username||e.password||e.search||e.hash))return`${e.origin}${e.pathname.replace(/\/+$/,"")}/api/v1/code`}function Ko(t=process.env){let e=t[Fe]?.trim();return e?Go(e):void 0}function Ge(t,e=process.env){let n=Ko(e);if(!n||!t)return!1;try{return new URL(t).origin===new URL(n).origin}catch{return!1}}function Cn(t){return t.apiKeyEnvKey===ot||Ki(t.baseUrl)}function Ki(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&&(pe(n)||n==="localhost"||n==="127.0.0.1"||n.endsWith(".matilda")||n==="core-api.matilda")||Ge(e)}var Et="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.",$i=new Map([["UNABLE_TO_GET_ISSUER_CERT_LOCALLY",Et],["UNABLE_TO_VERIFY_LEAF_SIGNATURE",Et],["SELF_SIGNED_CERT_IN_CHAIN",Et],["DEPTH_ZERO_SELF_SIGNED_CERT",Et],["CERT_HAS_EXPIRED","its certificate has expired."],["ERR_TLS_CERT_ALTNAME_INVALID","its certificate is for another name. Check the address."]]),No="its name does not resolve. Check the address and your network.",Uo="it refused the connection. Check the address, and that it is running.",Bi=new Map([["ENOTFOUND",No],["EAI_AGAIN",No],["ECONNREFUSED",Uo],["ConnectionRefused",Uo],["UND_ERR_CONNECT_TIMEOUT","it did not answer. Check your network, VPN and proxy."]]),$o=5,ji=/^Proxy response \((\d+)\)/,Bo=t=>t?`the proxy at ${t}`:"your proxy";function Vi(t,e){let n=Bo(e);if(t===407)return`${n} did not accept a user name and password (407). Set them in its address, as http://user:password@host:port.`;let o="add it to NO_PROXY if it is on your own network";return t===403?`${n} blocks it (403). Ask your network team to allow it, or ${o}.`:`${n} could not connect to it (${t}). Check the address, or ${o}.`}function Ke(t,e){if(B(t)!==void 0)return;let n=Do(e),o=t;for(let r=0;r<=$o;r++){if(typeof o!="object"||o===null)return;let i=o,s=i.transportCode??i.code,{cause:a,message:l}=i,u=typeof l=="string"?ji.exec(l):null;if(u)return new ce(`Could not reach ${H(e)}: ${Vi(Number(u[1]),n)}`,"UND_ERR_ABORTED");if(s===St)return new ce(`Could not reach ${H(e)}: ${Bo(n)} did not answer as a proxy. Check its address, and whether it starts with http:// or https://.`,St);if(typeof s=="string"){let c=H(e),f=$i.get(s);if(f)return new ce(`Could not connect securely to ${c}: ${f}`,s);if(Po.has(s))return new ce(`Could not reach ${n?`the proxy at ${n}, for ${c}`:c}: ${Bi.get(s)??"the network cannot reach it. Check your network, VPN and proxy."}`,s)}o=a}}function yn(t,e){let n=t;for(let o=0;o<=$o;o++){if(typeof n!="object"||n===null)return;let{name:r,code:i,cause:s}=n;if(r==="TimeoutError"||r==="AuthError"&&i==="timeout")return new ce(`${H(e)} did not answer in time. Check your network, VPN and proxy.`,"ETIMEDOUT");n=s}}function zi(t=process.env){let e=t[Fe]?.trim();if(e&&!Go(e))throw new et(`${Fe} must be the HTTPS address of your Matilda deployment, such as https://matilda.example.com. HTTP is accepted only for localhost.`)}function G(t=process.env){return zi(t),Ko(t)??Oe}p();p();p();Yt();var Wi=new Set(["service.version","service.instance.id","session.id"]);function ae(t,e){nt.warn(t),e?.push(t)}function jo(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){ae(`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{ae(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,e),l=s}let u;try{u=decodeURIComponent(a)}catch{ae(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${l}", using raw value`,e),u=a}n[l]=u}return n}function Tn(t,e,n){for(let o of Wi)o in t&&(ae(`${e} cannot override reserved key "${o}"; ignoring`,n),delete t[o]);return t}function Vo(t,e){if(t==null)return{};if(typeof t!="object"||Array.isArray(t))return ae("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){ae("settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",e);continue}typeof r=="string"?n[i]=r:ae(`settings.telemetry.resourceAttributes value for "${i}" must be a string (got ${typeof r}); ignoring`,e)}return n}function $e(t){if(t!==void 0)return t==="true"||t==="1"}async function Hi(t){let e=t.argv??{},n=t.env??{},o=t.settings??{},r=e.telemetry??$e(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 et(`Invalid telemetry OTLP protocol: ${String(s)}. Valid values are: grpc, http`);let l=e.telemetryLogPrompts??$e(n.MATILDA_TELEMETRY_LOG_PROMPTS)??o.logPrompts,u=$e(n.MATILDA_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES)??o.includeSensitiveSpanAttributes??!1,c=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=Tn(jo(n.OTEL_RESOURCE_ATTRIBUTES,h),"OTEL_RESOURCE_ATTRIBUTES",h),y=Tn(Vo(o.resourceAttributes,h),"settings.telemetry.resourceAttributes",h),C={...g,...y},S=n.OTEL_SERVICE_NAME?.trim();S&&(C["service.name"]=S);let E=Object.keys(C).length?C:void 0,M=$e(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:u,outfile:c,resourceAttributes:E,metrics:{includeSessionId:M},resourceAttributeWarnings:h.length?h:void 0}}p();Yt();import*as Z from"node:fs";import*as Wt from"node:path";p();p();p();p();Yt();p();import{AsyncLocalStorage as qi}from"node:async_hooks";var zo=new qi;p();import*as $ from"node:path";import{promises as bt}from"node:fs";p();p();import Yi from"crypto";var Rt=new Uint8Array(256),At=Rt.length;function Sn(){return At>Rt.length-16&&(Yi.randomFillSync(Rt),At=0),Rt.slice(At,At+=16)}p();var x=[];for(let t=0;t<256;++t)x.push((t+256).toString(16).slice(1));function Wo(t,e=0){return x[t[e+0]]+x[t[e+1]]+x[t[e+2]]+x[t[e+3]]+"-"+x[t[e+4]]+x[t[e+5]]+"-"+x[t[e+6]]+x[t[e+7]]+"-"+x[t[e+8]]+x[t[e+9]]+"-"+x[t[e+10]]+x[t[e+11]]+x[t[e+12]]+x[t[e+13]]+x[t[e+14]]+x[t[e+15]]}p();p();import Ji from"crypto";var En={randomUUID:Ji.randomUUID};function Xi(t,e,n){if(En.randomUUID&&!e&&!t)return En.randomUUID();t=t||{};let o=t.random||(t.rng||Sn)();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 Wo(o)}var An=Xi;import*as Q from"os";var vt=L("OPENAI_LOGGER"),Qi="########",Zi=/^[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 es(t,e){let n=e||process.cwd();if(!t)return $.join(n,"logs","openai");let o=t;return t==="~"||t.startsWith("~/")?o=$.join(Q.homedir(),t.slice(1)):$.isAbsolute(t)||(o=$.resolve(n,t)),$.normalize(o)}function Ho(t){return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function ts(t){let e=t.split("#");if(e.length!==3)return;let[,n,o]=e;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function ns(t){if(t)return fe(t)?Ho(t):Ho(ts(t))}function os(t){if(!t)return;let e=t.indexOf(Qi);if(e>0)return t.slice(0,e);if(Zi.test(t))return t;let n=t.split("#");if(n.length>=3&&n[0])return n[0]}function rs(t){let e=t?.trim(),n=os(e);return!e&&!n?null:{...e?{promptId:e}:{},...n?{sessionId:n}:{}}}var Be=class{logDir;initialized=!1;constructor(e,n){this.logDir=es(e,n)}async initialize(){if(!this.initialized)try{await bt.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(e){throw vt.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=An().slice(0,8),a=ns(r),l=a?`openai-${i}-${s}-${a}.json`:`openai-${i}-${s}.json`,u=$.join(this.logDir,l),c={timestamp:new Date().toISOString(),request:e,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:rs(r),system:{hostname:Q.hostname(),platform:Q.platform(),release:Q.release(),nodeVersion:process.version}};try{return await bt.writeFile(u,JSON.stringify(c,(f,d)=>typeof d=="string"?ro(d):d,2),"utf-8"),u}catch(f){throw vt.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 bt.readdir(this.logDir)).filter(r=>r.startsWith("openai-")&&r.endsWith(".json")).map(r=>$.join(this.logDir,r)).sort().reverse();return e?o.slice(0,e):o}catch(n){return n.code==="ENOENT"?[]:(vt.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(e){try{let n=await bt.readFile(e,"utf-8");return JSON.parse(n)}catch(n){throw vt.error(`Failed to read log file ${e}:`,n),new Error(`Failed to read log file: ${n}`)}}},Vu=new Be;p();var is="MATILDA_CODE_PROFILE_RUNTIME";function qo(t=process.env){return t[is]==="1"}var bn=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;requests=[];openaiWireRequests=[];tools=Yo();constructor(e={}){this.enabled=e.enabled??qo(),this.now=e.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(e={}){this.enabled=e.enabled??qo(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.tools=Yo()}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(ds(e)),contents:Jo(e.contents),systemInstructionBytes:ls(e.config?.systemInstruction),generationConfigBytes:D(Xo(e.config)),tools:cs(e.config?.tools)}))}recordOpenAIWireRequest(e){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...ss(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=as();return this.tools.byName[e]=o,o}},vn=new bn;function ss(t){let e=Ce(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let i of n){let s=Ce(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 Yo(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function as(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function Jo(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=Ce(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:[];us(s,e)}return e}function ls(t){return Jo(t).textBytes}function us(t,e){for(let n of t){if(e.partCount+=1,typeof n=="string"){e.textBytes+=D(n);continue}let o=Ce(n);typeof o.text=="string"&&(e.textBytes+=D(o.text));let r=Rn(o.functionCall);r&&(e.functionCallCount+=1,e.functionCallArgBytes+=D(r.args));let i=Rn(o.functionResponse);i&&(e.functionResponseCount+=1,e.functionResponseBytes+=D(i.response)+D(i.parts));let s=Rn(o.inlineData);s&&(e.inlineDataCount+=1,e.inlineDataBytes+=D(s.data)),o.fileData&&(e.fileDataCount+=1)}}function cs(t){let e=Array.isArray(t)?t:[],n=0;for(let o of e){let r=Ce(o),i=Array.isArray(r.functionDeclarations)?r.functionDeclarations:[];n+=i.length}return{count:e.length,functionDeclarationCount:n,schemaBytes:D(e)}}function ds(t){return{model:t.model,contents:t.contents,config:Xo(t.config)}}function Xo(t){if(!t)return;let e=Ce(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(ps(t),"utf8")}function ps(t){try{return JSON.stringify(t)??""}catch{return"[unserializable]"}}function Ce(t){return typeof t=="object"&&t!==null?t:{}}function Rn(t){return typeof t=="object"&&t!==null?t:null}p();function Qo(t){let e=t.candidates?.[0]?.content?.parts;return!e||e.length===0?!1:e.some(fs)}function fs(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 Zo(){let t=Zn.getStore();return{attempt:t?.attempt??1,requestSetupMs:t?.requestSetupMs,retryTotalDelayMs:t?.retryTotalDelayMs}}var le=L("LOGGING_CONTENT_GENERATOR"),gs=4096,er="...[truncated]",ms=gs-er.length,je=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 Be(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);Xt(this.config,new en(n,o,r,Y.getStore()))}_logApiResponse(e,n,o,r,i,s){Zt(this.config,new nn(e,o,n,r,this.generatorAuthType,i,s,Y.getStore()))}_logApiError(e,n,o,r,i){let s=no(o),a=Ie(o),l=o?.requestID||o?.request_id||e,u=B(o);Qt(this.config,new tn({responseId:l,model:r,durationMs:n,promptId:i,authType:this.generatorAuthType,errorMessage:s,errorType:a,statusCode:u,subagentName:Y.getStore()}))}safelyLogApiError(e,n,o,r,i){try{this._logApiError(e,n,o,r,i)}catch(s){le.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){le.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=Zo(),r=at(e.model,n);try{r.setAttribute("llm_request.stream",!1)}catch{}let i=qt.setSpan(j.active(),r),s=Date.now(),a=fe(n),l=this.startCaptureSession();try{vn.recordGenerateContentRequest(e,{stream:!1,source:"generateContent"}),a||(rt(this.config,r,e.config?.systemInstruction),it(this.config,r,e.config?.tools));let u=await j.with(i,async()=>{a||this.logApiRequest(this.toContents(e.contents),e.model,n);let c=await l.wrap(()=>this.wrapped.generateContent(e,n)),f=Date.now()-s,d=a?void 0:this.extractResponseText(c);a||st(this.config,r,d),this.safelyLogApiResponse(c.responseId??"",f,this.getClientVisibleModelId(e.model,c.modelVersion),n,c.usageMetadata,d);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),c,void 0,n)}catch(m){le.warn("Failed to log OpenAI interaction:",m)}return c});return ie(r,{success:!0,inputTokens:u.usageMetadata?.promptTokenCount,outputTokens:u.usageMetadata?.candidatesTokenCount,cachedInputTokens:u.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-s,responseId:u.responseId||void 0,finishReason:u.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:u.usageMetadata?.thoughtsTokenCount,subagentName:Y.getStore()||void 0,...o}),u}catch(u){let c=Date.now()-s,f=e.config?.abortSignal?.aborted??!1;throw ie(r,{success:!1,durationMs:c,error:f?ut:lt,errorType:Ie(u),errorStatusCode:B(u),subagentName:Y.getStore()||void 0,...o}),await j.with(i,async()=>{this.safelyLogApiError("",c,u,this.getClientVisibleModelId(e.model),n);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,u,n)}catch(d){le.warn("Failed to log OpenAI interaction:",d)}}),u}}async generateContentStream(e,n){let o=Zo(),r=at(e.model,n);try{r.setAttribute("llm_request.stream",!0)}catch{}let i=qt.setSpan(j.active(),r),s=Date.now(),a=fe(n),l=this.startCaptureSession(),u;try{vn.recordGenerateContentRequest(e,{stream:!0,source:"generateContentStream"}),a||(rt(this.config,r,e.config?.systemInstruction),it(this.config,r,e.config?.tools)),u=await j.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;j.with(i,()=>this.safelyLogApiError("",d,f,e.model,n));let m=e.config?.abortSignal?.aborted??!1;ie(r,{success:!1,durationMs:d,error:m?ut:lt,errorType:Ie(f),errorStatusCode:B(f),subagentName:Y.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,f,n)}catch(h){le.warn("Failed to log OpenAI interaction:",h)}throw f}let c;if(this.openaiLogger)try{c=await l.resolve(e)}catch(f){le.warn("Failed to resolve OpenAI request:",f)}return j.with(i,()=>this.loggingStreamWrapper(u,s,n,e.model,c,r,i,e.config?.abortSignal,o))}startCaptureSession(){let e,n=!this.openaiLogger;return{wrap:o=>n?o():zo.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,u){let c=fe(o),f=!c||!!this.openaiLogger,d=[],m="",h="",g,y=!1,C,S=!1,E,M=Y.getStore(),b,_=!1,K=I=>a?j.with(a,I):I(),ee=5*6e4,P,ue=s?()=>{_||(P!==void 0&&clearTimeout(P),P=setTimeout(()=>{try{s.setAttribute("stream.timed_out",!0)}catch{}ie(s,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:m||void 0,subagentName:M||void 0,...u}),_=!0},ee),P.unref())}:void 0;try{for await(let N of e){!m&&N.responseId&&(m=N.responseId),!h&&N.modelVersion&&(h=N.modelVersion),f&&d.push(N),N.usageMetadata&&(g=N.usageMetadata);let we=N.candidates?.[0];we?.finishReason&&(C=we.finishReason),N.functionCalls?.length&&(S=!0),b===void 0&&Qo(N)&&(b=Date.now()-n),ue?.(),yield N,P!==void 0&&(clearTimeout(P),P=void 0)}P!==void 0&&(clearTimeout(P),P=void 0);let I=Date.now()-n,te=f?this.consolidateGeminiResponsesForLogging(d):void 0,Qe=c?void 0:this.extractResponseText(te),ne=!C&&!S?new Error("Model stream ended without a finish reason"):void 0;ne&&(y=!0,E=ne),_||(ne?(K(()=>this.safelyLogApiError(m,I,ne,this.getClientVisibleModelId(r,h),o)),await K(()=>this.safelyLogOpenAIInteraction(i,te,ne,o))):(K(()=>this.safelyLogApiResponse(m,I,this.getClientVisibleModelId(r,h),o,g,Qe)),!c&&s&&st(this.config,s,Qe),await K(()=>this.safelyLogOpenAIInteraction(i,te,void 0,o))))}catch(I){if(y=!0,E=I,!_){let te=Date.now()-n;K(()=>this.safelyLogApiError(m,te,I,this.getClientVisibleModelId(r,h),o)),await K(()=>this.safelyLogOpenAIInteraction(i,void 0,I,o))}throw I}finally{if(P!==void 0&&clearTimeout(P),s&&!_){let I=l?.aborted??!1;ie(s,{success:!y,inputTokens:g?.promptTokenCount,outputTokens:g?.candidatesTokenCount,cachedInputTokens:g?.cachedContentTokenCount,ttftMs:b,durationMs:Date.now()-n,error:y?I?ut:lt:void 0,responseId:m||void 0,finishReason:C,thoughtsTokenCount:g?.thoughtsTokenCount,subagentName:M||void 0,errorType:E?Ie(E):void 0,errorStatusCode:E?B(E):void 0,...u})}}}async buildOpenAIRequestForLogging(e){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(e.model),o=yt.convertGeminiRequestToOpenAI(e,n,{cleanOrphanToolCalls:!1}),r={model:e.model,messages:o};return e.config?.tools&&(r.tools=await yt.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){le.warn("Failed to log OpenAI interaction:",i)}}convertGeminiResponseToOpenAIForLogging(e,n){let o=new re;return Object.assign(o,e),o.modelVersion=this.getClientVisibleModelId(n.model,e.modelVersion),yt.convertGeminiResponseToOpenAI(o,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(e){if(e.length===0)return;let n=new re,o=[],r=new Map,i,s;for(let u of e){u.usageMetadata&&(s=u.usageMetadata);let c=u.candidates?.[0];c?.finishReason&&(i=c.finishReason);let f=c?.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=ms-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}${er}`: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 Mn="x-matilda-organization-id",hs=/^[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 Sc(t){if(t!==void 0){if(typeof t!="string"||t.length!==36||!hs.test(t))throw new Error("--organization-id must be a single UUID.");return t.toLowerCase()}}function _n(t){if(t)try{let e=new URL(t);if((so(e.hostname)&&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 Cs(t){let e=_n(t.baseUrl);return!!e&&e.pathname.replace(/\/$/,"")==="/api/v1/code"&&t.authType==="openai"}function kn(t,e,n){if(!(e===void 0&&n===void 0)&&!Cs(t))throw new Error("Organization selection and credit spending require the first-party Matilda Core Code endpoint.")}function tr(t){for(let e of Object.keys(t??{})){let n=e.toLowerCase();if(n===Mn)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 Ec(t,e,n,o,r){kn(n,o,r);let i=_n(n.baseUrl),s=_n(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(Mn);if(a!==null&&a!==o)throw new Error("The request organization conflicts with --organization-id.");o!==void 0&&e.set(Mn,o)}p();function nr(t){switch(t){case"openai":return"OPENAI_API_KEY";default:return"API_KEY"}}function or(t){switch(t){case"openai":return"OPENAI_MODEL";default:return"MODEL"}}var Te=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}},Mt=class extends Te{name="StrictMissingCredentialsError";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.`))}},_t=class extends Te{name="StrictMissingModelIdError";code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},kt=class extends Te{name="MissingApiKeyError";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}'.`)}},wt=class extends Te{name="MissingModelError";code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}};p();import Pn from"node:process";p();function Mc(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 xt(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 ys=[[/^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"]]],rr=[[/^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 Ts(t,e="input"){let n=xt(t),o=e==="output"?rr:ys;for(let[r,i]of o)if(r.test(n))return i}function _c(t){let e=xt(t);return rr.some(([n])=>n.test(e))}function Ss(t,e="input"){return Ts(t,e)}function It(t,e="input"){return Ss(t,e)??(e==="output"?32e3:131072)}p();p();var ir={image:!0,pdf:!0,audio:!0,video:!0},Es=[[/^gemini-3/,ir],[/^gemini-/,ir],[/^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 Ot(t){let e=xt(t);for(let[n,o]of Es)if(n.test(e))return{...o};return{}}p();function sr(t,e,n={kind:"default"}){for(let o of t)if(ar(o.value))return{value:o.value,source:o.source};return{value:e,source:n}}function wn(t){for(let e of t)if(ar(e.value))return{value:e.value,source:e.source}}function ar(t){return!(t==null||typeof t=="string"&&t.trim()==="")}function Pt(t){return{kind:"cli",detail:t}}function As(t){return{kind:"env",envKey:t}}function Ve(t){return{kind:"settings",settingsPath:t}}function Se(t,e,n){return{kind:"modelProviders",authType:t,modelId:e,detail:n}}function xn(t){return{kind:"default",detail:t}}function Dt(t){return{kind:"computed",detail:t}}function Nt(t,e,n){let o=t[e];return{value:o!==void 0?n?n(o):o:void 0,source:As(e)}}function U(t,e){return{value:t,source:e}}p();var ze=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","openAIRequestProfile"],lr=["model","apiKey","apiKeyEnvKey","baseUrl"],In=[...lr,...ze],ur={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","MATILDA_MODEL"]}},cr={openai:ct};var Ee="MATILDA_API_KEY",Rs="matilda-code-1.0";function bs(t,e){if(!t)return!0;try{let{hostname:n}=new URL(t);return pe(n)||Ge(t,e)}catch{return!1}}function vs(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 Vc(t){let{authType:e,cli:n,settings:o,env:r,modelProvider:i,proxy:s}=t,a=[],l={},u=e?ur[e]:{model:[],apiKey:[],baseUrl:[]},c=[];e&&i&&c.push(U(i.id,Se(e,i.id,"model.id"))),n?.model&&c.push(U(n.model,Pt("--model"))),e==="openai"&&r[Ee]&&!r.OPENAI_MODEL&&!r.MATILDA_MODEL&&c.push(U(Rs,{kind:"env",envKey:Ee}));for(let b of u.model)c.push(Nt(r,b));o?.model&&c.push(U(o.model,Ve("model.name")));let f=e?cr[e]:"",d=sr(c,f,xn(f));l.model=d.source;let m=[];e&&i?.baseUrl&&m.push(U(i.baseUrl,Se(e,i.id,"baseUrl"))),n?.baseUrl&&m.push(U(n.baseUrl,Pt("--openaiBaseUrl"))),e==="openai"&&r[Ee]&&!r.OPENAI_BASE_URL&&(r[Fe]?.trim()||!o?.baseUrl)&&m.push(U(G(r),{kind:"env",envKey:Ee}));for(let b of u.baseUrl)m.push(Nt(r,b));o?.baseUrl&&m.push(U(o.baseUrl,Ve("security.auth.baseUrl")));let h=wn(m)??(e==="openai"?{value:G(r),source:xn("the configured Matilda endpoint")}:void 0);h&&(l.baseUrl=h.source);let g=[];if(e&&i?.envKey){let b=r[i.envKey];b&&g.push(U(b,{kind:"env",envKey:i.envKey,via:Se(e,i.id,"envKey")}))}if(n?.apiKey&&g.push(U(n.apiKey,Pt("--openaiApiKey"))),!i?.envKey){let b=r[Ee];if(e==="openai"&&b&&bs(h?.value,r)&&g.push(U(b,{kind:"env",envKey:Ee})),h?.source.kind!=="default")for(let _ of u.apiKey)g.push(Nt(r,_))}o?.apiKey&&g.push(U(o.apiKey,Ve("security.auth.apiKey")));let y=wn(g);y&&(l.apiKey=y.source);let C;e&&i?.envKey&&(C=i.envKey,l.apiKeyEnvKey={...Se(e,i.id,"envKey"),envKey:i.envKey});let S=Ut(o?.generationConfig,i?.generationConfig,e,i?.id??d.value,r),E=S.config;Object.assign(l,S.sources);let M={authType:e,model:d.value||"",apiKey:y?.value,apiKeyEnvKey:C,baseUrl:h&&V(h.value),proxy:s,...E};return s&&(l.proxy=Dt("Config.getProxy()")),l.authType=Dt("provided by caller"),{config:M,sources:l,warnings:a}}function Ut(t,e,n,o,r){let i={},s=Ms(t,e,n,o,i);return vs(r,s,i,e),{config:s,sources:i}}function Ms(t,e,n,o,r){let i={};for(let s of ze)n&&e&&s in e?(i[s]=e[s],r[s]=Se(n,o||"",`generationConfig.${s}`)):t&&s in t&&(i[s]=t[s],r[s]=Ve(`model.generationConfig.${s}`));return i.modalities===void 0&&o&&(i.modalities=Ot(o),r.modalities=Dt("auto-detected from model")),i}p();var Lt="$runtime|";function qc(t){let e=t;for(;e.startsWith(Lt);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}p();p();var dr=L("MODEL_REGISTRY");function pr(t,e){return e?`${t}\0${V(e)}`:t}var Ft=class{constructor(e,n=!1){this.noFallbackServer=n;this.reloadModels(e)}models=new Map;registerModels(e){let n=new Map;for(let o of e){if(this.noFallbackServer&&!o.baseUrl)continue;let r=pr(o.id,o.baseUrl);if(n.has(r)){dr.warn(`Duplicate model id "${o.id}"${o.baseUrl?` with baseUrl "${o.baseUrl}"`:""} for authType "openai". Using the first registered config.`);continue}n.set(r,this.resolveModelConfig(o))}return n}getModels(){return Array.from(this.models.values()).map(e=>({id:e.id,label:e.name,description:e.description,capabilities:e.capabilities,authType:e.authType,isVision:e.capabilities?.vision??!1,contextWindowSize:e.generationConfig.contextWindowSize??It(e.id),modalities:e.generationConfig.modalities??Ot(e.id),baseUrl:e.baseUrl,envKey:e.envKey}))}findModel(e,n){if(n)return this.models.get(pr(e,n));let o=this.models.get(e);if(o)return o;for(let r of this.models.values())if(r.id===e)return r}containsModel(e,n){return this.findModel(e,n)!==void 0}getDefaultModel(){return this.models.values().next().value}resolveModelConfig(e){return this.validateModelConfig(e),{...e,authType:"openai",name:e.name||e.id,baseUrl:V(e.baseUrl||G()),generationConfig:{...e.generationConfig??{}},capabilities:e.capabilities||{}}}validateModelConfig(e){if(!e.id)throw new Error("Model config in authType 'openai' missing required field: id")}reloadModels(e){this.models=new Map;for(let[n,o]of Object.entries(e??{})){if(n!=="openai"){dr.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(ye).join(", ")}. Skipping.`);continue}this.models=this.registerModels(o)}}};var fr=class t{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!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 Ft(e.modelProvidersConfig,e.noFallbackServer),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,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(e){this.currentAuthType=e.currentAuthType,this._generationConfig=e.generationConfig,this.generationConfigSources=e.generationConfigSources,this.strictModelProviderSelection=e.strictModelProviderSelection,this.activeRuntimeModelSnapshotId=e.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||ct}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModels():[]}getAllConfiguredModels(){let e=this.getRuntimeModelOption();return[...e?[e]:[],...this.modelRegistry.getModels()]}getResolvedModel(e){let n=this.modelRegistry.findModel(e);if(n)return{...n,generationConfig:{...this.resolveEntryGenerationConfig(n).config,customHeaders:n.generationConfig.customHeaders}}}resolveEntryGenerationConfig(e){return Ut(this.settingsGenerationConfig,e.generationConfig,e.authType,e.id,Pn.env)}isManagedMatildaResolvedModel(e){return e?.id===Jt&&e?.envKey===ot&&e?.baseUrl===Oe&&e?.generationConfig?.openAIRequestProfile==="matilda-code"}isManagedMatildaModel(e){let n=e.trim();return!n||!this.currentAuthType?!1:this.isManagedMatildaResolvedModel(this.modelRegistry.findModel(n))}getPublicModelId(e){return this.isManagedMatildaModel(e)?Jt:e}getModelDisplayName(e){return this.isManagedMatildaModel(e)?io:this.currentAuthType?this.modelRegistry.findModel(e)?.name??e:e}async setModel(e,n){if(this.currentAuthType&&this.modelRegistry.containsModel(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=Ut(this.settingsGenerationConfig,void 0,this.currentAuthType,e,Pn.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=It(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.findModel(n,o?.baseUrl);if(!a)throw new Error(`Model '${n}' not found for authType '${e}'`);let l=i.generationConfig.model||"",u=!s&&l?this.modelRegistry.findModel(l,i.generationConfig.baseUrl)??this.modelRegistry.findModel(l):void 0,c=!s&&!!i.generationConfig.apiKey&&!!a.envKey&&u?.envKey===a.envKey&&u.baseUrl===a.baseUrl,f=c?i.generationConfig.apiKey:void 0,d=c?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`${Lt}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(Lt))return this.runtimeModelSnapshots.has(e)?e:void 0;if(this.runtimeModelSnapshots.has(e))return e}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}isStrictModelProviderSelection(){return this.strictModelProviderSelection}applyResolvedModelDefaults(e){if(this.strictModelProviderSelection=!0,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=Pn.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 ze)this.applyResolvedField(o,n);this.fillContextWindowSize(e.id)}syncAfterAuthRefresh(e,n,{replacesApiKey:o=!1}={}){this.strictModelProviderSelection=!1;let r=this.currentAuthType;this.currentAuthType=e;let i=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,s=n?this.modelRegistry.findModel(n,i)??this.modelRegistry.findModel(n):void 0;if(s){let h=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==s.envKey||this._generationConfig.baseUrl!==s.baseUrl),g=r===e&&this._generationConfig.model===n&&!h,y=g&&!o,C=y?this._generationConfig.apiKey:void 0,S=y&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,E=this.generationConfigSources.baseUrl,M=g&&!!this._generationConfig.baseUrl&&(E?.kind==="cli"||E?.kind==="env"||E?.kind==="settings"),b=M?this._generationConfig.baseUrl:void 0,_=M&&E?{...E}:void 0;this.applyResolvedModelDefaults(s),!this._generationConfig.apiKey&&C&&(this._generationConfig.apiKey=C,S&&(this.generationConfigSources.apiKey=S)),b&&(this._generationConfig.baseUrl=b,_&&(this.generationConfigSources.baseUrl=_)),this.strictModelProviderSelection=!0,this.activeRuntimeModelSnapshotId=void 0;return}let a=this.generationConfigSources.apiKey,l=this.generationConfigSources.baseUrl,u=this._generationConfig.apiKey&&a?.kind!=="modelProviders"||this._generationConfig.baseUrl&&l?.kind!=="modelProviders";if(!(r!==e)&&(n===void 0||!this.modelRegistry.containsModel(n))&&u){n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (preserved credentials)"}));return}let d=this.modelRegistry.getDefaultModel();if(d){this.applyResolvedModelDefaults(d),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.containsModel(e,o)){this.clearRuntimeModelSnapshotForAuthType(s);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(s,e),u={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,u),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._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 na}from"node:crypto";import{mkdirSync as oa,readFileSync as ra}from"node:fs";import{dirname as ia,join as sa}from"node:path";p();p();import{randomBytes as _s,createHash as ks}from"node:crypto";import{setTimeout as ws}from"node:timers/promises";var xs="urn:ietf:params:oauth:grant-type:device_code";function gr(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function Nn(){let t=_s(32).toString("base64url"),e=ks("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function Ae(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 Is=15e3;async function Un(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!gr(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(Is)});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 Os=15e3,Dn="Device code expired: restart the sign-in";async function Ln(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:Cr(AbortSignal.timeout(Os),n.signal)})}catch(i){throw yr(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 mr(t,e,n={}){let o=await fetch(t,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:xs,client_id:e.clientId,device_code:e.deviceCode}),signal:n.signal});if(o.ok)return{kind:"authorized",tokens:Ae(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 hr(t,e,n={}){let o=e.interval*1e3;try{for(;Date.now()<e.expiresAt;){await ws(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 mr(t,e,{signal:Cr(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(Dn);case"access_denied":throw new Error("User denied the authorization request");default:throw new Error(`Device flow error: ${i.error}`)}}}}catch(r){throw yr(r,n.signal)?new Error(Dn):r}throw new Error(Dn)}function Cr(t,e){return e?AbortSignal.any([t,e]):t}function yr(t,e){return!e?.aborted&&t instanceof Error&&t.name==="TimeoutError"}p();import{randomBytes as Ps}from"node:crypto";import{promises as Re,openSync as Ds,closeSync as Ns,unlinkSync as Sr,statSync as Us}from"node:fs";import{dirname as Ls}from"node:path";var Tr=new Map,Fs=2e4,Gs=3e4,Ks=50;function Fn(t,e={}){let n=async()=>{try{let s=await Re.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 Re.mkdir(Ls(t),{recursive:!0});let l=`${t}.${process.pid}.${Ps(4).toString("hex")}.tmp`;try{await Re.writeFile(l,JSON.stringify(s,null,2),{mode:384}),a?.throwIfAborted(),await Re.rename(l,t)}catch(u){throw await Re.rm(l,{force:!0}).catch(()=>{}),u}await Re.chmod(t,384).catch(()=>{})},r=(s,a={})=>{let u=(Tr.get(t)??Promise.resolve()).then(async()=>{a.signal?.throwIfAborted();let c=await n(),f=!1;for(let[d,m]of Object.entries(s)){if(m===null){if(!(d in c))continue;delete c[d]}else{if(c[d]===m)continue;c[d]=m}f=!0}f&&await o(c,a.signal),a.onCommit?.()});return Tr.set(t,u.catch(()=>{})),u};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:$s(`${t}.lock`,e.lockTimeoutMs??Fs),update:r}}function $s(t,e){let n=Promise.resolve();return o=>{let r=n.then(async()=>{await Bs(t,e);try{return await o()}finally{js(t)}});return n=r.then(()=>{},()=>{}),r}}async function Bs(t,e){let n=Date.now()+e;for(;;)try{Ns(Ds(t,"wx"));return}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-Us(t).mtimeMs>Gs){Sr(t);continue}}catch{continue}if(Date.now()>n)throw Object.assign(new Error(`Timed out acquiring credential lock at ${t}`),{code:"ETIMEDOUT"});await Vs(Ks)}}function js(t){try{Sr(t)}catch{}}function Vs(t){return new Promise(e=>setTimeout(e,t))}p();var be=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function Gn(t){let e=t.storageKey??"default",n=t.fetchImpl??fetch,o=t.expirySkewMs??6e4,r=t.refreshTimeoutMs??15e3,i=null,s=async()=>{let u=await t.store.get(e);if(!u)return null;try{let c=JSON.parse(u);return c.accessToken?c:null}catch{return null}},a=u=>u.expiresAt-Date.now()>o,l=u=>t.lock(async()=>{let c=await s()??u;if(c.accessToken!==u.accessToken&&a(c))return c.accessToken;if(!c.refreshToken)throw new be("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:c.refreshToken}),signal:AbortSignal.timeout(r)});if(!m.ok){let h=await m.text().catch(()=>"");throw m.status>=400&&m.status<500&&zs(h)==="invalid_grant"?(await t.store.remove(e),new be):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=Ae(f,c);return await t.store.set(e,JSON.stringify(d)),d.accessToken});return{async getAccessToken(u){let c=await s();if(!c)throw new be("Not signed in.");return!u?.forceRefresh&&a(c)?c.accessToken:(i||(i=l(c).finally(()=>{i=null})),i)}}}function zs(t){try{return JSON.parse(t).error}catch{return}}p();import{createServer as Ws}from"node:http";import{randomBytes as Hs}from"node:crypto";async function Gt(t){if(t.transport.kind==="device")return qs(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}=Nn(),r=Hs(16).toString("hex"),i=t.timeoutMs??5*60*1e3,s=t.transport.successRedirect,a=t.transport.port;e({type:"state",status:"idle"});let l,u,c=new Promise((g,y)=>{l=g,u=y});c.catch(()=>{});let f=Ws((g,y)=>{let C=new URL(g.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){y.writeHead(404).end();return}let S=C.searchParams.get("error"),E=C.searchParams.get("state"),M=C.searchParams.get("code");if(S){let b=C.searchParams.get("error_description"),_=b?`OAuth error: ${S} (${b})`:`OAuth error: ${S}`;y.writeHead(400,{"content-type":"text/plain; charset=utf-8"}).end(`Sign-in failed: ${S}
|
|
16
|
+
`,()=>u(new Error(_)));return}if(E!==r){y.writeHead(400).end("State mismatch"),u(new Error("OAuth state mismatch"));return}if(!M){y.writeHead(400).end("Missing authorization code");return}Ys(y,s,()=>l(M))}),d=await new Promise((g,y)=>{f.once("error",y),f.listen(a??0,"127.0.0.1",()=>{g(f.address().port)})}),m=setTimeout(()=>u(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=()=>u(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`,y=new URL(t.metadata.authorization_endpoint);y.searchParams.set("client_id",t.clientId),y.searchParams.set("response_type","code"),y.searchParams.set("redirect_uri",g),y.searchParams.set("code_challenge",o),y.searchParams.set("code_challenge_method","S256"),y.searchParams.set("state",r),y.searchParams.set("prompt","select_account"),y.searchParams.set("scope",t.scope??"openid offline_access");let C=y.toString();e({type:"authorize_url",url:C}),e({type:"state",status:"awaiting_user"}),t.openBrowser&&await t.openBrowser(C);let S=await c;await Er(f),e({type:"state",status:"exchanging"});let E=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(!E.ok){let b=await E.text().catch(()=>"");throw new Error(`Token exchange failed (${E.status}): ${b}`)}let M=Ae(await E.json());return e({type:"state",status:"authenticated"}),M}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 Er(f)}}async function qs(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 Ln(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 hr(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 Er(t){return t.listening?new Promise(e=>{t.close(()=>e()),t.closeAllConnections()}):Promise.resolve()}function Ys(t,e,n){t.writeHead(302,{location:e}).end(n)}p();var Js=["www-browser"];function Xs(t){let e=t.replace(/\\/g,"/").split("/").pop();return!!e&&Js.includes(e)}function Ar(t={}){let n=process.env.BROWSER?.trim()?.match(/^\S+/)?.[0];if(!t.ignoreBrowserBlocklist&&process.platform!=="win32"&&n&&Xs(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")}p();p();import{setMaxListeners as Qs}from"node:events";var Zs=50;function Kt(t=Zs){let e=new AbortController;return Qs(t,e.signal),e}function ea(t){if(t)return t instanceof AbortController?t.signal:t}function Hd(t,e){let n=Kt(e),o=ea(t);if(!o)return n;if(o.aborted)return n.abort(o.reason),n;let r=new WeakRef(o),i=()=>{n.abort(r.deref()?.reason)};return o.addEventListener("abort",i,{once:!0}),n.signal.addEventListener("abort",()=>{r.deref()?.removeEventListener("abort",i)},{once:!0}),n}function Rr(t,e){let n=Kt(e?.maxListeners),o=t.find(l=>l?.aborted);if(o)return n.abort(o.reason),{signal:n.signal,cleanup:()=>{}};let r=[];for(let l of t){if(!l)continue;if(l.aborted){n.abort(l.reason);break}let u=()=>n.abort(l.reason);l.addEventListener("abort",u,{once:!0}),r.push(()=>l.removeEventListener("abort",u))}let i=e?.timeoutMs;if(i!==void 0&&i>0&&!n.signal.aborted){let l=setTimeout(()=>{n.abort(new DOMException("Operation timed out","TimeoutError"))},i);r.push(()=>clearTimeout(l))}let s=!1,a=()=>{if(!s){s=!0;for(let l of r)l()}};return n.signal.aborted?a():n.signal.addEventListener("abort",a,{once:!0}),{signal:n.signal,cleanup:a}}async function br(t,e){if(e?.throwIfAborted(),!e)return t();let n=()=>{},o=new Promise((i,s)=>{n=()=>s(e.reason),e.addEventListener("abort",n,{once:!0})});o.catch(()=>{});let r;try{r=await Promise.race([t(),o])}finally{e.removeEventListener("abort",n)}return e.throwIfAborted(),r}var vr=5*6e4;async function Kn(t,e){let n=performance.now()+vr,o=Kt(),r=()=>o.abort(new DOMException("Sign-in timed out","TimeoutError")),i=setTimeout(r,vr),{signal:s,cleanup:a}=Rr([t,o.signal]),l=()=>{t?.throwIfAborted(),performance.now()>=n&&r(),o.signal.throwIfAborted(),s.throwIfAborted()},u;try{l(),u=await e({signal:s,check:l})}finally{clearTimeout(i),a()}return l(),u}var ta=Un;function Mr(t,e){return br(()=>ta(t,void 0,{signal:e}),e)}var Me="matilda-code",_r="matilda-desktop",kr="openid profile email offline_access",$t="MATILDA_API_KEY",aa="matilda",$n=3e5;function _e(t){return H(t)}function wr(){return sa(tt.getGlobalMatildaDir(),"matilda-auth.json")}function qe(){let t=wr();return oa(ia(t),{recursive:!0}),Fn(t,{lockTimeoutMs:2e4})}function la(t){return t==="desktop"}function Ye(t){return t?.clientId?t.clientId:la(t?.channel)?_r:Me}function He(t){return`matilda:${t}`}function jt(t){return`${He(t)}:refresh-rejected`}function Je(t){return t===Me?[He(t),aa]:[He(t)]}function xr(){try{let t=ra(wr(),"utf8");return JSON.parse(t)}catch{return{}}}function Bt(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 Vn(t,e){return _e(t)===_e(e)}function ua(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 Ir(t,e){let n=ua(t.idToken);return{accessToken:t.accessToken,accessTokenExpiresAt:t.expiresAt,refreshToken:t.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:e}}var Bn=new Map;async function zn(t,e={}){let n=()=>{e.signal?.throwIfAborted(),e.check?.()};n();let o=!e.signingIn&&Bn.get(t);if(o)return o;try{let r=await Mr(t,e.signal);return n(),Bn.set(t,r),r}catch(r){n();let i=e.signingIn&&(Ke(r,t)??yn(r,t));if(i)throw i;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 Wn(t){try{let e=xr(),n=Ye(t);for(let o of Je(n)){let r=Bt(e[o]);if(r)return r}return null}catch{return null}}function Or(t){let e=Wn(t);return!e||t?.baseUrl&&!Vn(e.baseUrl,t.baseUrl)?null:e}function Hn(t){return Or(t)!==null}async function Pr(t,e){for(let n of e){let o=await t.get(n);if(Bt(o))return o}return null}async function ca(t,e){let n=Ye(t),o=Je(n),{store:r,lock:i,update:s}=qe();await i(async()=>{let a=await Pr(r,o);a!==null&&a!==e||await s({...Object.fromEntries(o.map(l=>[l,null])),[jt(n)]:"1"})})}function da(t){return t instanceof Error?t.code==="invalid_grant"||t.name==="InvalidGrantError"?!0:t.message==="Token refresh failed (401)":!1}function ve(t){jn({authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:t.occurrenceCount},{baseUrl:t.baseUrl,token:t.token}).catch(()=>{})}async function Dr(t,e,n={}){let o=Ye(e),r=He(o),i={[r]:JSON.stringify(t),[jt(o)]:null};for(let l of Je(o))l!==r&&(i[l]=null);let{lock:s,update:a}=qe();await s(()=>(n.check?.(),a(i,{signal:n.signal})))}async function pa(t,e){for(let n of Je(e))await t.remove(n);await t.remove(jt(e))}var We="matilda:api-key";function Nr(){let t=xr()[We];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 Vt(t){let e=Nr();return e&&Vn(e.baseUrl,t)?e.apiKey:void 0}async function fa(t){let e=na(),n=JSON.stringify(t?{...t,saveId:e}:{saveId:e}),{store:o,lock:r,update:i}=qe(),s=await r(async()=>{let a=await o.get(We);return(t||a!==null)&&await i({[We]:n}),a});return()=>r(async()=>{await o.get(We)===n&&await i({[We]:s})})}function ga(t){let e=Wn(t);return e?{authenticated:!0,userId:e.userId,email:e.email,displayName:e.displayName,baseUrl:e.baseUrl,accessTokenExpiresAt:e.accessTokenExpiresAt}:{authenticated:!1}}async function cp(t){let e={channel:t?.channel,clientId:t?.clientId},{store:n,lock:o}=qe(),r=await o(async()=>{let s=Wn(e);return await pa(n,Ye(e)),s}),i=Nr()!==null;if(await fa(null),r?.accessToken){let s=_e(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 Ur(t){return!t||t===$t}function Lr(t){let{baseUrl:e,channel:n,apiKey:o,apiKeyEnvKey:r}=t;if(Hn({baseUrl:e,channel:n})){let i=ga({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}:Ur(r)&&process.env[$t]?{kind:"api-key",from:$t}:Vt(e)!==void 0?{kind:"api-key",from:"saved"}:{kind:"none"}}async function Fr(t){t?.signal?.throwIfAborted();let e=Ye(t),n=He(e),o=Or({baseUrl:t?.baseUrl,channel:t?.channel,clientId:e});if(!o)return t?.fallbackAccessToken||(Ur(t?.apiKeyEnvKey)?process.env[$t]:void 0)||t?.baseUrl&&Vt(t.baseUrl)||"";let r=_e(o.baseUrl),i=await zn(r,{signal:t?.signal}),{manager:s,startedFrom:a}=ma(qe(),i.token_endpoint,o.baseUrl,e,n,t?.signal),l=e===Me&&(!!t?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=$n),u;try{u=await s.getAccessToken({forceRefresh:t?.forceRefresh})}catch(c){t?.signal?.throwIfAborted(),l&&ve({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"});let f=c instanceof Error?c.code:void 0;throw f==="session_changed"||f==="no_session"?new de({cause:c,channel:t?.channel}):!da(c)&&f!=="no_refresh_token"?(Bn.delete(r),Ke(c,r)??yn(c,r)??c):c instanceof de?new de({cause:c,channel:t?.channel}):(e===_r&&await ca({channel:t?.channel,clientId:e},a()),new de({cause:c,channel:t?.channel}))}return t?.signal?.throwIfAborted(),l&&ve({baseUrl:o.baseUrl,token:u,authStage:"refresh",authOutcome:"succeeded"}),u}function ma({store:t,lock:e,update:n},o,r,i,s,a){let l=Je(i),u=(C,S)=>{d=f;let E=[S?.signal,a].filter(M=>M instanceof AbortSignal);return fetch(C,{...S,signal:E.length>1?AbortSignal.any(E):E[0]})},c=C=>Pr(t,C===s?l:[C]),f=null,d,m=()=>d===void 0?f:d;return{manager:Gn({tokenEndpoint:o,clientId:i,store:{get:async C=>{let S=await c(C),E=Bt(S);if(f=E&&Vn(E.baseUrl,r)?S:null,!f||!E?.accessToken)return null;let M={accessToken:E.accessToken,refreshToken:E.refreshToken,expiresAt:E.accessTokenExpiresAt};return JSON.stringify(M)},set:async(C,S,E={})=>{let M=await c(C);if(M===null||M!==m())throw new de;let b=JSON.parse(S),_=Bt(M)??{},K={..._,accessToken:b.accessToken,accessTokenExpiresAt:b.expiresAt,refreshToken:b.refreshToken??_.refreshToken??"",baseUrl:_.baseUrl??r};await n({...Object.fromEntries(l.filter(ee=>ee!==s).map(ee=>[ee,null])),[s]:JSON.stringify(K),[jt(i)]:null},E)},remove:async(C,S={})=>{if(await c(C)!==m())return;await n(Object.fromEntries((C===s?l:[C]).map(M=>[M,null])),S)}},storageKey:s,lock:e,fetchImpl:u,expirySkewMs:$n,skewMs:$n}),startedFrom:m}}function ha(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&Ar()}async function dp(t){let{baseUrl:e,openBrowser:n,onAuthorizeUrl:o,signal:r}=t;return Kn(r,async i=>{let s=_e(e),a=await zn(s,{signingIn:!0,...i}),l="",u=0,c=0,f={},d=y=>{f[y]=(f[y]??0)+1},h=await(y=>(u+=1,Gt({metadata:a,clientId:Me,scope:y,transport:{kind:"loopback",successRedirect:`${s}/api/auth/oauth/success?client_id=${encodeURIComponent(Me)}`},signal:i.signal,onEvent:C=>{i.check(),C.type==="authorize_url"&&(l=C.url,o?.(C.url)),C.type==="state"&&C.status==="exchanging"&&(c+=1),i.check()},openBrowser:async C=>{if(i.check(),n===!1||!ha()){d("skipped");return}try{let{default:S}=await import("./open-QQ7FWG4A.js");i.check(),(await S(C)).once("error",()=>{}),d("succeeded")}catch{i.check(),d("failed")}i.check()}})))(kr).catch(y=>{throw i.check(),Ke(y,s)??y});i.check();let g=Ir(h,e);await Dr(g,void 0,i),i.check(),ve({baseUrl:e,token:g.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:u});for(let[y,C]of Object.entries(f))ve({baseUrl:e,token:g.accessToken,authStage:"browser_opened",authOutcome:y,occurrenceCount:C});return c>0&&ve({baseUrl:e,token:g.accessToken,authStage:"callback_received",authOutcome:"succeeded",occurrenceCount:c}),ve({baseUrl:e,token:g.accessToken,authStage:"token_persisted",authOutcome:"succeeded"}),{...g,authorizeUrl:l}})}async function pp(t){let{baseUrl:e,onDeviceCode:n,signal:o}=t;return Kn(o,async r=>{let i=_e(e),s=await zn(i,{signingIn:!0,...r}),a=await Gt({metadata:s,clientId:Me,scope:kr,transport:{kind:"device"},signal:r.signal,onEvent:u=>{r.check(),u.type==="user_code"&&n({userCode:u.userCode,verificationUri:u.verificationUri,verificationUriComplete:u.verificationUriComplete}),r.check()}}).catch(u=>{throw r.check(),Ke(u,i)??u});r.check();let l=Ir(a,e);return await Dr(l,void 0,r),l})}p();p();p();function zt(t){return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="object"&&"message"in t.error}function Gr(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}p();function Kr(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:Ca(t.error);if(s!==null&&s>0){let c=Math.min(t.retryAfterMaxDelayMs??t.maxDelayMs,2147483647),f=Math.min(s,c);return Math.max(r,f)}let a=t.jitterRatio??0;if(a<=0)return r;let l=t.random??Math.random,u=r*a*(l()*2-1);return Math.min(Math.max(0,r+u),n)}function Ca(t){let e=$r(t,"retry-after")??ya(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 $r(t,e){if(!Ta(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 ya(t,e){return Sa(t)?$r(t.response,e):null}function Ta(t){return typeof t=="object"&&t!==null&&"headers"in t&&t.headers!=null}function Sa(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 Ea=new Set([429,503,1302,1305]);function qn(t,e){if(Yn(t))return!1;let n=Ra(t);return n===null?!1:!!(Ea.has(n)||e&&e.includes(n))}function Yn(t){return Aa(t)==="insufficient_quota"}function Aa(t){let e=jr(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=B(t),n=jr(t),o=Vr(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 Ap(t,e){return Kr({attempt:t,initialDelayMs:e.initialDelayMs,maxDelayMs:e.maxDelayMs,retryAfterMode:"minimum",retryAfterMaxDelayMs:e.maxDelayMs,error:e.error})}function Ra(t){if(zt(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(zt(o)){let r=Number(o.error.code);if(Number.isFinite(r)&&r>0)return r}}catch{}}if(Gr(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 B(t)??null}function jr(t){for(let e of ba(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 zt(t)?{code:t.error.code,message:t.error.message}:null}function ba(t){let e=Vr(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 Vr(t){return t instanceof Error?t.message:typeof t=="string"?t:null}function va(t,e={}){if(Ma(t))return{kind:"abort",diagnosis:"fail-fast",reason:"aborted"};let n=Br(t),o=n.statusCode,r=Oa(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(Ia(i))return{kind:"provider-business",diagnosis:"fail-fast",reason:"allocated-quota-exceeded",...l};if(Yn(t))return{kind:"provider-business",diagnosis:"fail-fast",reason:"insufficient-quota",...l};if(qn(t,e.extraRetryErrorCodes))return{kind:n.transport==="sse"?"sse-provider":o!==void 0?"http":"provider",diagnosis:"retryable",reason:"rate-limit",...l};let u=ka(t);if(u!==void 0&&(o===void 0||o>=500))return{kind:"transport",diagnosis:"retryable",reason:"transport-error",transportCode:u,...o!==void 0?{statusCode:o}:{}};if(o!==void 0){let c=n.transport==="sse"?"sse-provider":"http";return o===529?{kind:c,diagnosis:"retryable",reason:"capacity-overload",...l}:o===401||o===403?{kind:c,diagnosis:"fail-fast",reason:"auth-error",...l}:o>=400&&o<500?{kind:c,diagnosis:"fail-fast",reason:"client-error",...l}:o>=500&&o<600?{kind:c,diagnosis:"retryable",reason:"server-error",...l}:{kind:c,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 _p(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 zr(t,e){return qn(t,e)||va(t,{extraRetryErrorCodes:e}).diagnosis==="retryable"}function Ma(t){return to(t)?!0:t instanceof Error&&t.name==="CanceledError"}var _a=5;function ka(t){let e=t;for(let n=0;n<=_a;n++){if(typeof e!="object"||e===null)return;let o=e.code;if(typeof o=="string"&&wa(o))return o;e=e instanceof Error?e.cause:void 0}}function wa(t){return xa.has(t)}var xa=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 Ia(t){return t==="Throttling.AllocationQuota"}function Oa(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 ye=(e=>(e.USE_OPENAI="openai",e))(ye||{});function Wr(t,e){if(delete t.usesMatildaSignIn,delete t.usesMatildaSavedApiKey,!Cn(t))return;let n=t.baseUrl||G();Hn({baseUrl:n,channel:e})&&(t.usesMatildaSignIn=!0),!t.apiKey&&Vt(n)!==void 0&&(t.usesMatildaSavedApiKey=!0)}function Fp(t,e={}){let n=t.apiKey?{value:t.apiKey,from:e.apiKeyFrom??"config"}:void 0;return Cn(t)?Lr({baseUrl:t.baseUrl||G(),channel:e.channel,apiKey:n,apiKeyEnvKey:t.apiKeyEnvKey}):n&&{kind:"api-key",from:n.from}}async function Pa(t,e){try{await Fr({baseUrl:t.baseUrl||G(),channel:e})}catch(n){if(!zr(n))throw n}}function Jn(t,e,n){t[e]=n}function Da(t,e){return t?.[e]}function Gp(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=c=>Da(o,c)??{kind:"unknown"};for(let c of In)n&&c in n&&!i[c]&&Jn(i,c,l(c));Wr(a,t.getChannel());let u=On(a,s);if(!u.valid)throw new Error(u.errors.map(c=>c.message).join(`
|
|
17
|
+
`));return{config:a,sources:i}}function On(t,e=!1){let n=[];if(!t.apiKey&&!t.usesMatildaSignIn&&!t.usesMatildaSavedApiKey)if(e)n.push(new Mt(t.authType,t.model,t.apiKeyEnvKey));else{let o=t.apiKeyEnvKey||nr(t.authType);n.push(new kt({authType:t.authType,model:t.model,baseUrl:t.baseUrl,envKey:o}))}if(!t.model)if(e)n.push(new _t(t.authType));else{let o=or(t.authType);n.push(new wt({authType:t.authType,envKey:o}))}return{valid:n.length===0,errors:n}}function Na(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 Kp(t,e,n){e.assertServer?.(t.baseUrl,n,e.getContentGeneratorConfig?.()?.baseUrl),kn(t,e.getOrganizationId?.(),e.getCodeCreditLimitMinor?.()),tr(t.customHeaders),Wr(t,e.getChannel()),t.usesMatildaSignIn&&await Pa(t,e.getChannel());let o=On(t,!1);if(!o.valid)throw new Error(o.errors.map(s=>s.message).join(`
|
|
18
|
+
`));oo(t.apiKey);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-T2E7ARNR.js");await s(t,e,n),i=a(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=Na(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 je(i,e,t)}var Ua=["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"],La=new Set([...Ua,...eo]),Fa=new Set(["VSCode","ACP","SDK","CI"]),ke="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",Ga="[A-Za-z][0-9A-Za-z-]{0,23}",Hr="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",Ka=new RegExp(`^${ke}(?:-${Ga}(?:\\.${Hr})+)?$`),$a=63,Ba=new RegExp(`^${ke}$`),ja=new RegExp(`^${ke}-preview\\.(?:0|[1-9]\\d{0,11})$`),Va=new RegExp(`^${ke}-canary\\.(?:0|[1-9]\\d{0,11})$`),za=new RegExp(`^${ke}-nightly\\.(?:0|[1-9]\\d{0,11})\\.[0-9A-Fa-f]{7,12}$`),Wa=new RegExp(`^${ke}-(preview|canary|nightly|development|internal)(?:\\.${Hr})+$`);function Ha(t){return t==="desktop"?"desktop":t===void 0||Fa.has(t)?"code_cli":"unknown"}function qa(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 Ja(t){if(t===void 0)return"npm";if(t==="desktop")return"direct-download";if(t==="VSCode")return"vscode-marketplace"}function Xa(t,e){if(e==="desktop")return"matilda-desktop";if(t==="VSCode")return"matilda-vscode";if(e==="code_cli")return"matilda-code"}function Qa(t){if(typeof t=="string"&&!(t.length>$a||!Ka.test(t)))return t}function Za(t){if(t!==void 0)return Ba.test(t)?"stable":ja.test(t)?"preview":Va.test(t)?"canary":za.test(t)?"nightly":Wa.exec(t)?.[1]}function qr(t,e=process.platform,n=process.arch){let o=t.getChannel?.(),r=Ha(o),i=Qa(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:t.getCliVersion?.()),s=Za(i),a=qa(e),l=Ya(n),u=Ja(o),c=Xa(o,r);return{...c?{"x-matilda-client-name":c}:{},...i?{"x-matilda-client-version":i}:{},...a?{"x-matilda-client-operating-system":a}:{},...l?{"x-matilda-client-architecture":l}:{},...u?{"x-matilda-client-distribution-channel":u}:{},...s?{"x-matilda-client-release-channel":s}:{}}}function Hp(t){let e=t.toLowerCase();return La.has(e)||e.startsWith("x-matilda-reported-")}function el(t){let e=t??G();try{let n=new URL(e);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let o=n.hostname.toLowerCase();return pe(o)||o==="core-api.matilda"||Ge(e)}catch{return!1}}function qp(t,e=t.apiKey){return t.authType==="openai"&&(!!e||t.usesMatildaSignIn===!0||t.usesMatildaSavedApiKey===!0)&&el(t.baseUrl)}var tl=3e3,Xe=1,nl=24*60*60*1e3,Yr=20,Jr=999,ol=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"]),rl=new Set(["ENOTFOUND","EAI_AGAIN"]),il=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),sl=new Set(["ABORT_ERR","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT"]),al=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]);function ll(t){return`${new URL(V(t)).origin}/api/client-events`}function ul(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 Xn(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??tl);try{let a=await r(ll(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(ul(t)),signal:i.signal});return a.ok?!0:(nt.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`),!1)}catch{return!1}finally{clearTimeout(s)}}async function jn(t,e){let n=typeof t.occurrenceCount=="number"&&Number.isFinite(t.occurrenceCount)?Math.max(1,Math.min(Math.floor(t.occurrenceCount),Jr)):1;return Xn({eventType:"auth_funnel",authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:n},e)}function Xr(){try{let t=Z.readFileSync(ei(),"utf8"),e=JSON.parse(t);return e.schemaVersion!==Xe||!Array.isArray(e.failures)?void 0:{schemaVersion:Xe,failures:e.failures.filter(cl)}}catch{return}}function cl(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 Qr(t){let e=ei();if(t.failures.length===0){try{Z.rmSync(e,{force:!0})}catch{}return}try{Z.mkdirSync(Wt.dirname(e),{recursive:!0}),Z.writeFileSync(e,`${JSON.stringify(t)}
|
|
20
|
+
`,"utf8")}catch{}}function Zr(t,e){return t.filter(n=>e-n.lastObservedAtMs<=nl).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-Yr)}function dl(t){let e=qr(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 pl(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 fl(t){if(!(!t||typeof t!="object"))for(let e of["status","statusCode"]){let n=t[e];if(typeof n=="number")return n}}function gl(t,e){let n=pl(t);if(n&&ol.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&rl.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&il.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&sl.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&al.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=fl(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 ml(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 tf(t,e){let n=dl(e.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=gl(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=Xr()??{schemaVersion:Xe,failures:[]},a=Zr(s.failures,r),l=ml(a,i);if(l>=0){let u=a[l];a[l]={...u,occurrenceCount:Math.min(u.occurrenceCount+1,Jr),lastObservedAtMs:r}}else a.push(i);return Qr({schemaVersion:Xe,failures:a.slice(-Yr)}),!0}async function nf(t){let e=Xr();if(!e)return;let n=Zr(e.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await Xn({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}}Qr({schemaVersion:Xe,failures:o})}function ei(){return Wt.join(tt.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var tm="http://localhost:4317";export{Xs as a,Ar as b,ai as c,gn as d,ht as e,gi as f,mi as g,yt as h,zo as i,es as j,vn as k,Hi as l,Jl as m,Po as n,Zl as o,Li as p,eu as q,tu as r,Fe as s,H as t,lu as u,uu as v,cu as w,Go as x,Ko as y,Ge as z,Cn as A,Ke as B,zi as C,G as D,qr as E,Hp as F,qp as G,jn as H,tf as I,nf as J,tm as K,Sc as L,_n as M,Cs as N,kn as O,tr as P,Ec as Q,Mc as R,_c as S,It as T,ze as U,ur as V,Vc as W,qc as X,fr as Y,Kt as Z,Hd as _,Rr as $,br as aa,_e as ba,Wn as ca,Hn as da,Nr as ea,Vt as fa,fa as ga,ga as ha,cp as ia,Fr as ja,ha as ka,dp as la,pp as ma,zt as na,Gr as oa,Kr as pa,Ca as qa,qn as ra,Yn as sa,Aa as ta,Br as ua,Ap as va,va as wa,_p as xa,zr as ya,ye as za,Fp as Aa,Gp as Ba,Kp as Ca};
|
|
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
|
+
/** @license Copyright 2026 Maincode SPDX-License-Identifier: Apache-2.0 */
|
|
106
|
+
/**
|
|
107
|
+
* @license
|
|
108
|
+
* Copyright 2026 Maincode
|
|
109
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
110
|
+
*
|
|
111
|
+
* Matilda account auth for the CLI, backed by the shared client SDK.
|
|
112
|
+
*
|
|
113
|
+
* The OAuth dance (PKCE, loopback capture, code exchange, refresh, cross-process
|
|
114
|
+
* token locking) is owned by `@maincode-ai/matilda-client-sdk/auth/node` — the
|
|
115
|
+
* auth team's tested implementation of ADR-029's unified `/api/auth/oauth/*`
|
|
116
|
+
* flow. This module keeps ONLY the CLI-specific concerns: which endpoint, the
|
|
117
|
+
* on-disk credential shape the rest of the CLI already reads, and surfacing the
|
|
118
|
+
* authorize URL to the Ink UI. No PKCE crypto, no loopback server, no token
|
|
119
|
+
* exchange lives here anymore (replaced the 391-line hand-rolled beta that hit
|
|
120
|
+
* the divergent `/api/auth/cli/*` endpoints and stored tokens in plaintext).
|
|
121
|
+
*/
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{A as m,I as g,L as h,P as l,W as M}from"./chunk-WL27X35X.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();import*as s from"node:fs";import*as t from"node:path";var A="memory",y="MEMORY.md",x="meta.json",R="extract-cursor.json",O="consolidation.lock",T="memories";function D(r){let e=t.resolve(r);for(;;){let n=t.join(e,".git");if(s.existsSync(n))return e;let o=t.dirname(e);if(o===e)return null;e=o}}function j(r){let e=D(r);if(!e)return null;try{let n=s.readFileSync(t.join(e,".git"),"utf-8").trim();if(!n.startsWith("gitdir:"))return e;let o=t.resolve(e,n.slice(7).trim()),i=t.resolve(o,s.readFileSync(t.join(o,"commondir"),"utf-8").trim());return t.resolve(t.dirname(o))!==t.join(i,"worktrees")||s.realpathSync(s.readFileSync(t.join(o,"gitdir"),"utf-8").trim())!==t.join(s.realpathSync(e),".git")?e:t.basename(i)!==".git"?i.normalize("NFC"):t.dirname(i).normalize("NFC")}catch{return e}}function E(){return process.env.MATILDA_CODE_MEMORY_BASE_DIR?h(void 0,process.env.MATILDA_CODE_MEMORY_BASE_DIR):l.getRuntimeBaseDir()}var f=new Map;function c(r){let e=process.env.MATILDA_CODE_MEMORY_LOCAL==="1",n=e?"":E(),o=`${e?"local":n}\0${r}`,i=f.get(o);if(i!==void 0)return i;let a;if(e)a=t.join(r,m,A);else{let d=j(r)??t.resolve(r);a=t.join(n,"projects",g(d),A)}return f.set(o,a),a}function u(r){return t.dirname(c(r))}function C(r,e){let n=t.normalize(r),o=t.normalize(c(e)),i=t.relative(o,n);return i===""||!i.startsWith("..")&&!t.isAbsolute(i)}function N(r){return t.join(c(r),y)}function U(r){return t.join(u(r),x)}function F(r){return t.join(u(r),R)}function Y(r){return t.join(u(r),O)}function _(){return t.join(E(),T)}function k(){return t.join(_(),y)}function I(r){let e=t.normalize(r),n=t.normalize(_()),o=t.relative(n,e);return o===""||!o.startsWith("..")&&!t.isAbsolute(o)}function S(r,e){return C(r,e)||I(r)}var z="A secret in this text was stored as ***REDACTED***, as a memory should keep none.";function b(r,e,n){return S(t.resolve(r),e)?M(n):n}export{y as a,E as b,c,u as d,C as e,N as f,U as g,F as h,Y as i,_ as j,k,S as l,z as m,b as n};
|
|
4
|
+
/**
|
|
5
|
+
* @license
|
|
6
|
+
* Copyright 2025 Google LLC
|
|
7
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
+
*/
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as r}from"./chunk-V6UPUMP3.js";import{
|
|
3
|
+
import{a as r}from"./chunk-V6UPUMP3.js";import{ea as g}from"./chunk-WL27X35X.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();function C(n,o){return`Base directory for this skill: ${n}
|
|
4
4
|
Important: ALWAYS resolve absolute paths from this base directory when working with skills.
|
|
5
5
|
|
|
6
6
|
${o}
|
|
7
|
-
`}async function
|
|
7
|
+
`}async function h(n,o){let i=await n.listSkills(),l=o.getDisabledSkillNames(),t=e=>l.has(e.toLowerCase()),s=i.filter(e=>!e.disableModelInvocation&&n.isSkillActive(e)&&!t(e.name)),m=new Set(i.filter(e=>!e.disableModelInvocation&&e.paths&&e.paths.length>0&&!n.isSkillActive(e)&&!t(e.name)).map(e=>e.name)),a=o.getModelInvocableCommandsProvider(),c=a?a():[],k=new Set(i.filter(e=>!e.disableModelInvocation&&!t(e.name)).map(e=>e.name)),d=c.filter(e=>!k.has(e.name)),S=[...s.map(e=>({name:e.name,description:e.description,whenToUse:e.whenToUse,level:e.level})),...d.map(e=>({name:e.name,description:e.description}))];return{availableSkills:s,pendingConditionalSkillNames:m,modelInvocableCommands:d,entries:S}}function u(n,o){let i=n.level!==void 0?0:1,l=o.level!==void 0?0:1;return i!==l?i-l:n.name.localeCompare(o.name)}function H(n){return[...n].sort(u).map(o=>{if(o.level!==void 0){let i=`${r(o.description)}${o.whenToUse?` \u2014 ${r(o.whenToUse)}`:""} (${o.level})`;return`<skill>
|
|
8
8
|
<name>
|
|
9
9
|
${r(o.name)}
|
|
10
10
|
</name>
|
|
@@ -22,7 +22,7 @@ ${r(o.name)}
|
|
|
22
22
|
${r(o.description)}
|
|
23
23
|
</description>
|
|
24
24
|
</skill>`}).join(`
|
|
25
|
-
`)}function y(n,o){if(!(!n||!o?.length))for(let i of o)n.addSessionAllowRule(i)}f();var p=g("SKILL_HOOKS");function M(n,o,i){if(!i.hooks)return p.debug(`Skill '${i.name}' has no hooks to register`),0;let l=i.hooks,t=0;for(let s of Object.keys(l)){let m=l[s];if(m)for(let a of m){let c=a.matcher||"";for(let k of a.hooks){if(k.type==="function"){p.debug("Skipping function hook from skill (not supported in frontmatter)");continue}let d=v(k,i.skillRoot);n.addSessionHook(o,s,c,d,{skillRoot:i.skillRoot}),t++,p.debug(`Registered hook for ${s}
|
|
25
|
+
`)}function y(n,o){if(!(!n||!o?.length))for(let i of o)n.addSessionAllowRule(i)}f();var p=g("SKILL_HOOKS");function M(n,o,i){if(!i.hooks)return p.debug(`Skill '${i.name}' has no hooks to register`),0;let l=i.hooks,t=0;for(let s of Object.keys(l)){let m=l[s];if(m)for(let a of m){let c=a.matcher||"";for(let k of a.hooks){if(k.type==="function"){p.debug("Skipping function hook from skill (not supported in frontmatter)");continue}let d=v(k,i.skillRoot);n.addSessionHook(o,s,c,d,{skillRoot:i.skillRoot}),t++,p.debug(`Registered hook for ${s} from skill '${i.name}', matcher:`,c)}}}return t>0&&p.info(`Registered ${t} hooks from skill '${i.name}'`),t}function v(n,o){return n.type==="command"&&o?{...n,env:{...n.env,MATILDA_SKILL_ROOT:o}}:n}export{C as a,h as b,H as c,y as d,M as e};
|
|
26
26
|
/**
|
|
27
27
|
* @license
|
|
28
28
|
* Copyright 2025 Matilda
|