@maincode-ai/matilda-code 0.22.3 → 0.22.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/chunks/agent-MOVDRLTH.js +3 -0
  2. package/chunks/agent-headless-OIL2DH2J.js +3 -0
  3. package/chunks/{askUserQuestion-Y66GA5LV.js → askUserQuestion-76LPP5ST.js} +1 -1
  4. package/chunks/{chunk-RDTF45AP.js → chunk-3EQIOCSJ.js} +1 -1
  5. package/chunks/{chunk-6SPPO7RK.js → chunk-4SDFTVQW.js} +1 -1
  6. package/chunks/chunk-5372BQ2X.js +18 -0
  7. package/chunks/chunk-5MS3VZDH.js +12 -0
  8. package/chunks/chunk-B7BF33U4.js +31 -0
  9. package/chunks/{chunk-C2AKSF3S.js → chunk-EC2IF7DG.js} +1 -1
  10. package/chunks/{chunk-TGRZ364D.js → chunk-EEPSTT7K.js} +1 -1
  11. package/chunks/{chunk-JRGQUM3K.js → chunk-J6NYCXUR.js} +1 -1
  12. package/chunks/chunk-J6YVJMKL.js +207 -0
  13. package/chunks/{chunk-SLKJK36M.js → chunk-JVQHQDDE.js} +1 -1
  14. package/chunks/chunk-LPPYEBZM.js +2557 -0
  15. package/chunks/{chunk-DNDA5SY7.js → chunk-LQ3VS2EV.js} +76 -67
  16. package/chunks/{chunk-SHISTILE.js → chunk-M5ABGGE7.js} +1 -1
  17. package/chunks/chunk-MUYVUUSO.js +80 -0
  18. package/chunks/{chunk-YTKDUEUJ.js → chunk-QKAKC34Q.js} +1 -1
  19. package/chunks/{chunk-I4KER2VG.js → chunk-QUITDDTB.js} +1 -1
  20. package/chunks/{chunk-YZ33K24S.js → chunk-R373GBK6.js} +1 -1
  21. package/chunks/chunk-RR3LDVGW.js +8 -0
  22. package/chunks/chunk-RT2VU2QV.js +68 -0
  23. package/chunks/{chunk-U6ATDQUV.js → chunk-T6MRYRLI.js} +1 -1
  24. package/chunks/{chunk-7SPPCSW2.js → chunk-VNSW4TSX.js} +1 -1
  25. package/chunks/{chunk-GFKFHWDN.js → chunk-WAZCC4SE.js} +1 -1
  26. package/chunks/{chunk-TVTJEK4V.js → chunk-YUCEPXGG.js} +1 -1
  27. package/chunks/{computer-use-ISO4RC44.js → computer-use-MBKJPMWZ.js} +4 -4
  28. package/chunks/{cron-create-4AQ43RPW.js → cron-create-K6DCVCY3.js} +3 -3
  29. package/chunks/{cron-delete-HB7V5CZ5.js → cron-delete-XNCDKPVV.js} +1 -1
  30. package/chunks/{cron-list-DIZZQW44.js → cron-list-3IPROBTC.js} +1 -1
  31. package/chunks/{edit-MHYRQVE6.js → edit-72ASKQO7.js} +17 -17
  32. package/chunks/en-SCZAH2YB.js +23 -0
  33. package/chunks/{enter-worktree-BSZTMEDU.js → enter-worktree-YYH4RD3G.js} +1 -1
  34. package/chunks/enterPlanMode-SKK26RKS.js +18 -0
  35. package/chunks/{exit-worktree-BI3PAII4.js → exit-worktree-5K5Y2UR4.js} +1 -1
  36. package/chunks/{exitPlanMode-W5VIX4WC.js → exitPlanMode-XDH6WKKD.js} +30 -27
  37. package/chunks/{glob-V3O2W6OW.js → glob-3PF3E5R2.js} +1 -1
  38. package/chunks/{goal-tools-H4HYCQUP.js → goal-tools-4SWS6CGW.js} +1 -1
  39. package/chunks/{grep-ANJ5PXWU.js → grep-RQLOBTPU.js} +3 -3
  40. package/chunks/{ls-I6JUFOTE.js → ls-EP4ZVFNW.js} +1 -1
  41. package/chunks/{lsp-JMVZE3IL.js → lsp-ULZTGWC4.js} +1 -1
  42. package/chunks/monitor-ZS5E3EAX.js +33 -0
  43. package/chunks/notebook-edit-JMRHVFA4.js +17 -0
  44. package/chunks/openaiContentGenerator-PRVYEJIU.js +52 -0
  45. package/chunks/read-file-GWUQN2ZM.js +3 -0
  46. package/chunks/ripGrep-CWJYHBK6.js +3 -0
  47. package/chunks/scheduler-LPJ66QW3.js +8 -0
  48. package/chunks/{send-message-F2OT25N7.js → send-message-TDOMZHNJ.js} +1 -1
  49. package/chunks/shell-AXB4E537.js +3 -0
  50. package/chunks/{skill-2ISAMUAZ.js → skill-7PMKFRET.js} +1 -1
  51. package/chunks/symbol-search-NHVD4D3O.js +19 -0
  52. package/chunks/{syntheticOutput-ULZO4GEC.js → syntheticOutput-5SCRQCXN.js} +1 -1
  53. package/chunks/{task-create-ARA6A3IM.js → task-create-T4DIVG5X.js} +1 -1
  54. package/chunks/{task-detach-DNYZ6B3V.js → task-detach-ES3IMGJ4.js} +2 -2
  55. package/chunks/{task-list-MUF5W3YQ.js → task-list-LYK4TOBS.js} +1 -1
  56. package/chunks/{task-stop-JDLVQ7YB.js → task-stop-FETAYKFU.js} +1 -1
  57. package/chunks/{task-update-Z6PWEP2K.js → task-update-I6PVT46S.js} +1 -1
  58. package/chunks/{team-create-5NCGVBX5.js → team-create-3S7UXATW.js} +1 -1
  59. package/chunks/{team-delete-7YXVWNUC.js → team-delete-P5F32IYK.js} +1 -1
  60. package/chunks/todoWrite-ADAGHJLI.js +3 -0
  61. package/chunks/{tool-call-O4FMFOGR.js → tool-call-W6PAJOF6.js} +1 -1
  62. package/chunks/{tool-search-IRVSMFYZ.js → tool-search-ECQHNTSM.js} +1 -1
  63. package/chunks/{web-fetch-L3AFPTQ3.js → web-fetch-2BMJPIBC.js} +1 -1
  64. package/chunks/{web-search-CQZ35NJW.js → web-search-CHJGDUDM.js} +1 -1
  65. package/chunks/{workflow-Z7BMQ6HQ.js → workflow-H5E25IZN.js} +2 -2
  66. package/chunks/write-file-UPXM654K.js +15 -0
  67. package/cli.js +474 -472
  68. package/locales/en.js +36 -93
  69. package/package.json +2 -2
  70. package/chunks/agent-CZV2RVXO.js +0 -3
  71. package/chunks/agent-headless-ZANXAE75.js +0 -3
  72. package/chunks/ca-3NRDXS7D.js +0 -23
  73. package/chunks/chunk-225CZWD7.js +0 -89
  74. package/chunks/chunk-4OBUTJ5U.js +0 -56
  75. package/chunks/chunk-ADMI5U2X.js +0 -46
  76. package/chunks/chunk-BNPG5OZM.js +0 -2582
  77. package/chunks/chunk-L76BNXJ2.js +0 -13
  78. package/chunks/chunk-NGIEYIMB.js +0 -80
  79. package/chunks/chunk-OODGPZRX.js +0 -12
  80. package/chunks/chunk-QYVSSMHJ.js +0 -121
  81. package/chunks/chunk-UJWYKBZM.js +0 -8
  82. package/chunks/de-MINTIKBC.js +0 -23
  83. package/chunks/en-PBTDLJES.js +0 -23
  84. package/chunks/enterPlanMode-XUABOR3E.js +0 -18
  85. package/chunks/fr-XRDTBTRU.js +0 -23
  86. package/chunks/ja-OYFHC7MP.js +0 -23
  87. package/chunks/mcp-client-F5W7WEZP.js +0 -3
  88. package/chunks/monitor-OEMTAZ5B.js +0 -32
  89. package/chunks/notebook-edit-L3SBV7YM.js +0 -17
  90. package/chunks/openaiContentGenerator-PBSIX6IL.js +0 -52
  91. package/chunks/pt-6DJAKXHE.js +0 -23
  92. package/chunks/read-file-YNB554TW.js +0 -3
  93. package/chunks/ripGrep-FPRMOSPK.js +0 -3
  94. package/chunks/ru-4UMYCMY6.js +0 -23
  95. package/chunks/scheduler-JCQAZK5I.js +0 -8
  96. package/chunks/shell-JOPPKFDV.js +0 -3
  97. package/chunks/symbol-search-R7VDY7D2.js +0 -19
  98. package/chunks/todoWrite-RJABGUPD.js +0 -3
  99. package/chunks/write-file-I4DCL6AB.js +0 -15
  100. package/locales/ca.js +0 -1894
  101. package/locales/de.js +0 -1934
  102. package/locales/fr.js +0 -1935
  103. package/locales/ja.js +0 -1697
  104. package/locales/pt.js +0 -1920
  105. package/locales/ru.js +0 -1910
@@ -1,12 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{j as i,x as c}from"./chunk-L76BNXJ2.js";import{ia as l}from"./chunk-6SPPO7RK.js";import{b as g}from"./chunk-GZPNIYVZ.js";g();import{readFile as y}from"node:fs/promises";function S(t){return t?`side-query:${t}`:"side-query"}function T(t,e){return e??t.getFastModel?.()??t.getModel()??c}function x(t){let e=t?.thinkingConfig;return{...t??{},thinkingConfig:e?{includeThoughts:!1,...e}:{includeThoughts:!1}}}async function h(t){let e=t.getOutputLanguageFilePath?.();if(e)try{let n=(await y(e,"utf8")).trim();return n?["Follow the user-visible output language preference below for this side query.",n].join(`
4
-
5
- `):void 0}catch{return}}function C(t,e){return e?t===void 0?e:typeof t=="string"?`${t}
6
-
7
- ${e}`:Array.isArray(t)?[...t,{text:e}]:typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)?{...t,parts:[...t.parts,{text:e}]}:[t,{text:e}]:t}function R(t){return t.schema!==void 0&&t.schema!==null}async function A(t,e){let n=T(t,e.model),o=e.promptId??S(e.purpose),s=x(e.config),a=C(e.systemInstruction,await h(t)),u=e.purpose==="chat-compression"?"compaction":"unknown";if(R(e)){let r=await i(u,()=>t.getBaseLlmClient().generateJson({contents:e.contents,schema:e.schema,abortSignal:e.abortSignal,model:n,systemInstruction:a,promptId:o,config:s,...e.maxAttempts!==void 0&&{maxAttempts:e.maxAttempts}})),f=l.validate(e.schema,r);if(f)throw new Error(`Invalid side query response: ${f}`);let m=e.validate?.(r);if(m)throw new Error(m);return r}let p=await i(u,()=>t.getBaseLlmClient().generateText({contents:e.contents,model:n,systemInstruction:a,abortSignal:e.abortSignal,promptId:o,config:s,...e.maxAttempts!==void 0&&{maxAttempts:e.maxAttempts},...e.stream&&{stream:!0}})),d=e.validate?.(p.text);if(d)throw new Error(d);return p}export{A as a};
8
- /**
9
- * @license
10
- * Copyright 2025 Google LLC
11
- * SPDX-License-Identifier: Apache-2.0
12
- */
@@ -1,121 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{a as w,d as le}from"./chunk-225CZWD7.js";import{a as lo,d as uo,n as ut,o as rn,p as mo,q as ct,r as Ke,t as he,u as N,x as Ct}from"./chunk-L76BNXJ2.js";import{Aa as an,Ca as ln,I as Ce,K as dt,L as pt,M as ft,U as gt,V as ue,ha as mt,ia as ht,qa as Z,qb as un,rb as cn,tb as dn,ya as sn}from"./chunk-DNDA5SY7.js";import{P as at,Q as fo,V as go,d as co,e as po,ea as K,f as V,g as Ge,k as st,r as me,w as G}from"./chunk-6SPPO7RK.js";import{h as W,i as lt,k as nn,m as on}from"./chunk-HEJO7OBH.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();p();p();p();p();var q=class extends Error{constructor(t,n){super(`${t} at position ${n}`),this.position=n}};p();function ho(e){return/^[0-9A-Fa-f]$/.test(e)}function te(e){return e>="0"&&e<="9"}function Co(e){return e>=" "}function $e(e){return`,:[]/{}()
4
- +`.includes(e)}function pn(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"||e==="$"}function fn(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"||e==="$"||e>="0"&&e<="9"}var gn=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,mn=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function hn(e){return`,[]/{}
5
- +`.includes(e)}function Cn(e){return Be(e)||ci.test(e)}var ci=/^[[{\w-]$/;function yo(e){return e===`
6
- `||e==="\r"||e===" "||e==="\b"||e==="\f"}function ee(e,t){let n=e.charCodeAt(t);return n===32||n===10||n===9||n===13}function To(e,t){let n=e.charCodeAt(t);return n===32||n===9||n===13}function So(e,t){let n=e.charCodeAt(t);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function Be(e){return yn(e)||yt(e)}function yn(e){return e==='"'||e==="\u201C"||e==="\u201D"}function Tn(e){return e==='"'}function yt(e){return e==="'"||e==="\u2018"||e==="\u2019"||e==="`"||e==="\xB4"}function Sn(e){return e==="'"}function ye(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=e.lastIndexOf(t);return o!==-1?e.substring(0,o)+(n?"":e.substring(o+1)):e}function $(e,t){let n=e.length;if(!ee(e,n-1))return e+t;for(;ee(e,n-1);)n--;return e.substring(0,n)+t+e.substring(n)}function Eo(e,t,n){return e.substring(0,t)+e.substring(t+n)}function Ao(e){return/[,\n][ \t\r]*$/.test(e)}var di={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},pi={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
7
- `,r:"\r",t:" "};function Tt(e){let t=0,n="";u(["```","[```","{```"]),i()||se(),u(["```","```]","```}"]);let r=f(",");for(r&&s(),Cn(e[t])&&Ao(n)?(r||(n=$(n,",")),C()):r&&(n=ye(n,","));e[t]==="}"||e[t]==="]";)t++,s();if(t>=e.length)return n;rt();function i(){s();let T=g()||y()||S()||M()||b()||F(!1)||re();return s(),T}function s(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,A=t,R=a(T);do R=l(),R&&(R=a(T));while(R);return t>A}function a(T){let A=T?ee:To,R="";for(;;)if(A(e,t))R+=e[t],t++;else if(So(e,t))R+=" ",t++;else break;return R.length>0?(n+=R,!0):!1}function l(){if(e[t]==="/"&&e[t+1]==="*"){for(;t<e.length&&!fi(e,t);)t++;return t+=2,!0}if(e[t]==="/"&&e[t+1]==="/"){for(;t<e.length&&e[t]!==`
8
- `;)t++;return!0}return!1}function u(T){if(c(T)){if(pn(e[t]))for(;t<e.length&&fn(e[t]);)t++;return s(),!0}return!1}function c(T){a(!0);for(let A of T){let R=t+A.length;if(e.slice(t,R)===A)return t=R,!0}return!1}function f(T){return e[t]===T?(n+=e[t],t++,!0):!1}function d(T){return e[t]===T?(t++,!0):!1}function m(){return d("\\")}function h(){return s(),e[t]==="."&&e[t+1]==="."&&e[t+2]==="."?(t+=3,s(),d(","),!0):!1}function g(){if(e[t]==="{"){n+="{",t++,s(),d(",")&&s();let T=!0;for(;t<e.length&&e[t]!=="}";){let A;if(T?(A=!0,T=!1):(A=f(","),A||(n=$(n,",")),s()),h(),!(S()||F(!0))){e[t]==="}"||e[t]==="{"||e[t]==="]"||e[t]==="["||e[t]===void 0?n=ye(n,","):D();break}s();let it=f(":"),ae=t>=e.length;it||(Cn(e[t])||ae?n=$(n,":"):Le()),i()||(it||ae?n+="null":Le())}return e[t]==="}"?(n+="}",t++):n=$(n,"}"),!0}return!1}function y(){if(e[t]==="["){n+="[",t++,s(),d(",")&&s();let T=!0;for(;t<e.length&&e[t]!=="]";)if(T?T=!1:f(",")||(n=$(n,",")),h(),!i()){n=ye(n,",");break}return e[t]==="]"?(n+="]",t++):n=$(n,"]"),!0}return!1}function C(){let T=!0,A=!0;for(;A;)T?T=!1:f(",")||(n=$(n,",")),A=i();A||(n=ye(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=e[t]==="\\";if(R&&(t++,R=!0),Be(e[t])){let it=Tn(e[t])?Tn:Sn(e[t])?Sn:yt(e[t])?yt:yn,ae=t,Fe=n.length,k='"';for(t++;;){if(t>=e.length){let O=P(t-1);return!T&&$e(e.charAt(O))?(t=ae,n=n.substring(0,Fe),S(!0)):(k=$(k,'"'),n+=k,!0)}if(t===A)return k=$(k,'"'),n+=k,!0;if(it(e[t])){let O=t,tn=k.length;if(k+='"',t++,n+=k,s(!1),T||t>=e.length||$e(e[t])||Be(e[t])||te(e[t]))return E(),!0;let Q=P(O-1),ao=e.charAt(Q);if(ao===",")return t=ae,n=n.substring(0,Fe),S(!1,Q);if($e(ao))return t=ae,n=n.substring(0,Fe),S(!0);n=n.substring(0,Fe),t=O+1,k=`${k.substring(0,tn)}\\${k.substring(tn)}`}else if(T&&hn(e[t])){if(e[t-1]===":"&&gn.test(e.substring(ae+1,t+2)))for(;t<e.length&&mn.test(e[t]);)k+=e[t],t++;return k=$(k,'"'),n+=k,E(),!0}else if(e[t]==="\\"){let O=e.charAt(t+1);if(pi[O]!==void 0)k+=e.slice(t,t+2),t+=2;else if(O==="u"){let Q=2;for(;Q<6&&ho(e[t+Q]);)Q++;Q===6?(k+=e.slice(t,t+6),t+=6):t+Q>=e.length?t=e.length:ui()}else k+=O,t+=2}else{let O=e.charAt(t);O==='"'&&e[t-1]!=="\\"?(k+=`\\${O}`,t++):yo(O)?(k+=di[O],t++):(Co(O)||ie(O),k+=O,t++)}R&&m()}}return!1}function E(){let T=!1;for(s();e[t]==="+";){T=!0,t++,s(),n=ye(n,'"',!0);let A=n.length;S()?n=Eo(n,A,1):n=$(n,'"')}return T}function M(){let T=t;if(e[t]==="-"){if(t++,ge())return I(T),!0;if(!te(e[t]))return t=T,!1}for(;te(e[t]);)t++;if(e[t]==="."){if(t++,ge())return I(T),!0;if(!te(e[t]))return t=T,!1;for(;te(e[t]);)t++}if(e[t]==="e"||e[t]==="E"){if(t++,(e[t]==="-"||e[t]==="+")&&t++,ge())return I(T),!0;if(!te(e[t]))return t=T,!1;for(;te(e[t]);)t++}if(!ge())return t=T,!1;if(t>T){let A=e.slice(T,t),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 e.slice(t,t+T.length)===T?(n+=A,t+=T.length,!0):!1}function F(T){let A=t;if(pn(e[t])){for(;t<e.length&&fn(e[t]);)t++;let R=t;for(;ee(e,R);)R++;if(e[R]==="(")return t=R+1,i(),e[t]===")"&&(t++,e[t]===";"&&t++),!0}for(;t<e.length&&!hn(e[t])&&!Be(e[t])&&(!T||e[t]!==":");)t++;if(e[t-1]===":"&&gn.test(e.substring(A,t+2)))for(;t<e.length&&mn.test(e[t]);)t++;if(t>A){for(;ee(e,t-1)&&t>0;)t--;let R=e.slice(A,t);return n+=R==="undefined"?"null":JSON.stringify(R),e[t]==='"'&&t++,!0}}function re(){if(e[t]==="/"){let T=t;for(t++;t<e.length&&(e[t]!=="/"||e[t-1]==="\\");)t++;return t++,n+=`"${e.substring(T,t)}"`,!0}}function P(T){let A=T;for(;A>0&&ee(e,A);)A--;return A}function ge(){return t>=e.length||$e(e[t])||ee(e,t)}function I(T){n+=`${e.slice(T,t)}0`}function ie(T){throw new q(`Invalid character ${JSON.stringify(T)}`,t)}function rt(){throw new q(`Unexpected character ${JSON.stringify(e[t])}`,t)}function se(){throw new q("Unexpected end of json string",e.length)}function D(){throw new q("Object key expected",t)}function Le(){throw new q("Colon expected",t)}function ui(){let T=e.slice(t,t+6);throw new q(`Invalid unicode character "${T}"`,t)}}function fi(e,t){return e[t]==="*"&&e[t+1]==="/"}var gi=K("JSON_PARSE");function mi(e,t={}){if(!e||typeof e!="string")return t;try{return JSON.parse(e)}catch(n){let o=hi(e);if(o!==void 0)return o;try{let r=Tt(e);return JSON.parse(r)}catch(r){let i=vo(e);if(i&&i!==e)try{return JSON.parse(Tt(i))}catch{}return gi.error("Failed to parse JSON even with jsonrepair:",{originalError:n,repairError:r,jsonString:e}),t}}}var Ro=Symbol("tool-args-parse-failed");function bo(e){if(e==null)return{};let t=typeof e=="string"?e.trim():"";if(!t)return{};let n=mi(t,Ro);return n===Ro?null:n&&typeof n=="object"&&!Array.isArray(n)?n:null}function hi(e){let t=vo(e);if(t&&t!==e.trim())try{return JSON.parse(t)}catch{return}}function vo(e){let t=e.trimStart();if(!t)return null;let n=t[0];if(n!=="{"&&n!=="[")return null;let o=0,r=!1,i=!1;for(let s=0;s<t.length;s++){let a=t[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 t.slice(0,s+1);if(o<0)return null}}return null}p();var Ci=/[A-Za-z\u00C0-\u024F]/g;function yi(e){return e>=1024&&e<=1279||e>=1280&&e<=1327||e>=11744&&e<=11775||e>=42560&&e<=42655||e>=12352&&e<=12543||e>=13312&&e<=19903||e>=19968&&e<=40959||e>=63744&&e<=64255||e>=44032&&e<=55215}function En(e){let t=e.codePointAt(0);return t!==void 0&&yi(t)}function Ti(e){let t=e.match(Ci)?.length??0;if(t<24)return!1;let n=0;for(let o of e)En(o)&&n++;return n===0||t>=n*8}function St(e){if(!e||!Ti(e))return e;let t="",n=0,o=[...e];for(;n<o.length;){if(!En(o[n])){t+=o[n],n++;continue}let r=n;for(;r>0&&o[r-1]===" ";)r--;let i=n+1;for(;i<o.length&&En(o[i]);)i++;for(;i<o.length&&o[i]===" ";)i++;let s=r>0?o[r-1]:"",a=i<o.length?o[i]:"";(/[A-Za-z0-9]/.test(s)&&/[A-Za-z0-9]/.test(a)||o[r]===" "||o[i-1]===" ")&&(t+=" "),n=i,r<n&&o[r]===" "&&t.endsWith(" ")&&(t=t.slice(0,-1))}return t.replace(/ {2,}/g," ")}p();var Te=K("TAGGED_THINKING_PARSER"),Ve=["<think>","<thinking>"],ze=["</think>","</thinking>"],Si=Math.max(...Ve.map(e=>e.length),...ze.map(e=>e.length));function je(e,t,n){t&&e.push(n==="thought"?{text:t,thought:!0}:{text:t})}function Et(e,t,n){let o=e.length-t;return o<=0||o>Si?!1:n.some(r=>r.startsWith(e.slice(t,t+o)))}function At(e,t,n){return n.find(o=>e.startsWith(o,t))}function Rn(e){if(!e)return e;let t=e;return t=t.replace(/<\/?think(?:ing)?>/gi,""),t=t.replace(/[A-Za-z]*long[_-]?message[_-]?THINKING/gi,""),t=t.replace(/\bM?long[_-]?message\b/gi,""),t=t.replace(/(^|[\s>])THINKING(?=[\sA-Z<]|$)/g,"$1"),t!==e&&(t=t.replace(/[ \t]{2,}/g," ")),t}function Mo(e){let t=[];for(let n of e){if(n.thought===!0||typeof n.text!="string"){t.push(n);continue}let o=St(Rn(n.text));(o.length>0||/^\s+$/.test(n.text))&&t.push({text:o.length>0?o:n.text})}return t}var An=class{mode="text";buffer="";parse(t,n=!1){this.buffer+=t;let o=this.buffer.toLowerCase(),r=[],i="",s=0;for(;s<this.buffer.length;){if(this.mode==="text"){let a=At(o,s,Ve);if(a){Te.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),je(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=At(o,s,ze);if(l){Te.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),je(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(Et(o,s,Ve)||Et(o,s,ze)))break}else{let a=At(o,s,ze);if(a){Te.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),je(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=At(o,s,Ve);if(l){s+=l.length;continue}if(!n&&(Et(o,s,ze)||Et(o,s,Ve)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(je(r,i,this.mode),this.buffer=this.buffer.slice(s),Te.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),Mo(r)):(this.buffer="",this.mode==="thought"&&i&&Te.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),je(r,i,this.mode),Te.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),Mo(r))}};function _o(e){return new An().parse(e,!0)}p();function ko(e,t="auto"){return t==="openapi_30"?Ei(e):e}function Ei(e){let t=n=>{if(typeof n!="object"||n===null)return n;if(Array.isArray(n))return n.map(t);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=t(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]=t(s));return r};return t(e)}p();function Se(e){return!Number.isFinite(e)||e<=0?0:Math.ceil(e/4)}function Rt(e){let t=e.candidates||0,n=e.thoughts||0;return n>t?t+n:Math.max(t,n)}function Ai(e){return e.total&&e.total>0?Math.max(e.total,(e.prompt||0)+Rt(e)):(e.prompt||0)+Rt(e)}function Ri(e){let t=Math.max(0,e.thoughtsTokens||0),n=Rt({candidates:e.outputTokens||0,thoughts:t}),o=Math.max(e.totalTokens||0,(e.inputTokens||0)+n);return{...e,outputTokens:n,thoughtsTokens:t,totalTokens:o}}var Y=K("CONVERTER"),Do="(attached media from previous tool call)";function No(e,t={}){let n=e.prompt_tokens||0,o=e.completion_tokens||0,r=e.total_tokens||0,i=e.prompt_tokens_details,s=i?.cached_tokens??i?.cachedTokens??e.cached_tokens??e.prompt_cache_hit_tokens??e.cache_read_input_tokens??0,a=e.completion_tokens_details,l=a?.reasoning_tokens??a?.reasoningTokens??e.reasoning_tokens??0,u=Math.max(0,t.estimatedReasoningTokens??0),c=Math.max(0,t.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=e.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 bi=64,wo=1024;function xo(e,t){if(e.length===0)return"";if(t.emittedText.length===0)return t.emittedText=e,t.emittedLength=e.length,e;if(t.cumulativeMode){if(e.startsWith(t.emittedText)){let n=e.slice(t.emittedText.length);return t.emittedText=e,t.emittedLength=e.length,n}return t.emittedText.startsWith(e)?(Y.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${t.emittedText.length}b, chunk=${e.length}b)`),""):(Y.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),t.cumulativeMode=!1,t.emittedText=e,t.emittedLength+=e.length,e)}if(e.length>t.emittedText.length&&e.startsWith(t.emittedText)){let n=t.emittedText.length,r=n>=wo&&t.emittedLength>n?t.emittedLength:n;if(e.length>r){let i=e.slice(r);return t.emittedText=e,t.emittedLength=e.length,t.cumulativeMode=!0,Y.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${e.length}b)`),i}}return e===t.emittedText?e.length>=bi?(t.cumulativeMode=!0,Y.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${e.length}b)`),""):(t.emittedLength+=e.length,e):(t.emittedText.length<wo&&(t.emittedText+=e),t.emittedLength+=e.length,e)}function Lo(e){if(!e||typeof e!="object")return e;let t=JSON.parse(JSON.stringify(e)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let r={};for(let[i,s]of Object.entries(o))if(i==="type"&&typeof s=="string"){let a=s.toLowerCase();a==="integer"?r[i]="integer":a==="number"?r[i]="number":r[i]=a}else i==="minimum"||i==="maximum"||i==="multipleOf"?typeof s=="string"&&!isNaN(Number(s))?r[i]=Number(s):r[i]=s:i==="minLength"||i==="maxLength"||i==="minItems"||i==="maxItems"?typeof s=="string"&&!isNaN(Number(s))?r[i]=parseInt(s,10):r[i]=s:typeof s=="object"?r[i]=n(s):r[i]=s;return r};return n(t)}async function vi(e,t="auto"){let n=[];for(let o of e){let r;if("tool"in o?r=await o.tool():r=o,r.functionDeclarations){for(let i of r.functionDeclarations)if(i.name&&i.description){let s;i.parametersJsonSchema?s={...i.parametersJsonSchema}:i.parameters&&(s=Lo(i.parameters)),s&&(s=ko(s,t)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function Mi(e,t,n={cleanOrphanToolCalls:!0}){let o=[];return ki(e,o),wi(e.contents,o,t),o=Uo(o),n.cleanOrphanToolCalls&&(o=Gi(o),o=Uo(o)),o}function _i(e,t){let n=e.candidates?.[0],o=n?.content?.parts||[],r=[],i=[],s=[],a=0;for(let g of o)typeof g=="string"?i.push(g):"text"in g&&g.text?"thought"in g&&g.thought?r.push(g.text):i.push(g.text):"functionCall"in g&&g.functionCall&&(s.push({id:g.functionCall.id||`call_${a}`,type:"function",function:{name:g.functionCall.name||"",arguments:JSON.stringify(g.functionCall.args||{})}}),a+=1);let l={role:"assistant",content:i.join("")||null,refusal:null},u=r.join("");u&&(l.reasoning_content=u),s.length>0&&(l.tool_calls=s);let c=Fi(n?.finishReason),f=e.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=e.createTime?Number(e.createTime):Date.now(),h=Number.isFinite(m)?Math.floor(m/1e3):Math.floor(Date.now()/1e3);return{id:e.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:h,model:e.modelVersion||t.model,choices:[{index:0,message:l,finish_reason:c,logprobs:null}],usage:d}}function ki(e,t){if(!e.config?.systemInstruction)return;let n=Go(e.config.systemInstruction);n&&t.push({role:"system",content:n})}function wi(e,t,n){if(Array.isArray(e))for(let o of e)Io(o,t,n);else e&&Io(e,t,n)}function Io(e,t,n){if(typeof e=="string"){t.push({role:"user",content:e});return}if(!Pi(e))return;let o=e.parts||[],r=e.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=Fo(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)){Y.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=Ii(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)}}t.push(g)}}}if(f.length>0&&t.push({role:"user",content:[{type:"text",text:Do},...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),t.push(m);return}i.length>0&&t.push({role:"user",content:i})}function xi(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e,n=t.output;if(typeof n=="string")return n;let o=t.error;if(typeof o=="string")return o}try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Ii(e,t){let n=xi(e.response),o=[];n&&o.push({type:"text",text:n});for(let r of e.parts||[]){if("text"in r&&typeof r.text=="string"){r.text.length>0&&o.push({type:"text",text:r.text});continue}let i=Fo(r,t);i&&o.push(i)}return o.length===0?{role:"tool",tool_call_id:e.id||"",content:""}:{role:"tool",tool_call_id:e.id||"",content:o}}function Fo(e,t){let{modalities:n}=t;if(e.inlineData?.mimeType&&e.inlineData?.data){let o=e.inlineData.mimeType,r=Oo(o),i=e.inlineData.displayName||o;if(r==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${e.inlineData.data}`}}:ce("image",i,t);if(o==="application/pdf")return n.pdf?{type:"file",file:{filename:e.inlineData.displayName||"document.pdf",file_data:`data:${o};base64,${e.inlineData.data}`}}:ce("pdf",i,t);if(r==="audio"){if(!n.audio)return ce("audio",i,t);let s=Oi(o);if(s)return{type:"input_audio",input_audio:{data:`data:${o};base64,${e.inlineData.data}`,format:s}}}return r==="video"?n.video?{type:"video_url",video_url:{url:`data:${o};base64,${e.inlineData.data}`}}:ce("video",i,t):{type:"text",text:`Unsupported inline media type: ${o} (${i}).`}}if(e.fileData?.mimeType&&e.fileData?.fileUri){let o=e.fileData.displayName||"file",r=e.fileData.fileUri,i=e.fileData.mimeType,s=Oo(i);if(s==="image")return n.image?{type:"image_url",image_url:{url:r}}:ce("image",o,t);if(i==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:r}}:ce("pdf",o,t);if(s==="video")return n.video?{type:"video_url",video_url:{url:r}}:ce("video",o,t);let a=e.fileData.displayName?` (${e.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${i}${a}.`}}return null}function ce(e,t,n){Y.warn(`Model '${n.model}' does not support ${e} input. Replacing with text placeholder: ${t}`);let o;return e==="pdf"?o=`This model does not support PDF input directly. The read_file tool cannot extract PDF content either. To extract text from the PDF file, try using skills if applicable, or guide user to install pdf skill by running this slash command:
12
- /extensions install https://github.com/anthropics/skills:document-skills`:o=`This model does not support ${e} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`,{type:"text",text:`[Unsupported ${e} file: "${t}". ${o}]`}}function Oo(e){return e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":e.startsWith("video/")?"video":"file"}function Oi(e){return e.includes("wav")?"wav":e.includes("mp3")||e.includes("mpeg")?"mp3":null}function Pi(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&Array.isArray(e.parts)}function Go(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>Go(t)).filter(Boolean).join(`
13
- `):typeof e=="object"&&e!==null&&"parts"in e&&e.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
14
- `)||""}function bt(e,t,n=!0){if(t.taggedThinkingParser)return t.taggedThinkingParser.parse(e,n);if(t.responseParsingOptions?.taggedThinkingTags)return _o(e);if(!e)return[];let o=St(Rn(e));return o?[{text:o}]:[]}function Ui(e,t){let n=e.choices?.[0],o=new le;if(n){let r=[];if(!t.responseParsingOptions?.taggedThinkingTags){let i=n.message.reasoning_content??n.message.reasoning;i&&r.push({text:i,thought:!0})}if(n.message.content&&r.push(...bt(n.message.content,t)),n.message.tool_calls){for(let i of n.message.tool_calls)if(i.function){let s=bo(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:Ko(n.finish_reason),index:0,safetyRatings:[]}]}else o.candidates=[];if(o.responseId=e.id,o.createTime=e.created?e.created.toString():new Date().getTime().toString(),o.modelVersion=t.model,o.promptFeedback={safetyRatings:[]},e.usage){let r=e.choices?.[0]?.message,i=r?.reasoning_content??r?.reasoning??"",s=typeof r?.content=="string"?r.content:"";o.usageMetadata=No(e.usage,{estimatedReasoningTokens:Se(i.length),estimatedContentTokens:Se(s.length)})}return o}function Di(e,t){let n=e.choices?.[0],o=new le,r=t.toolCallParser;if(!r)throw new Error("convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start.");if(n){let i=[];if(!t.responseParsingOptions?.taggedThinkingTags){let u=n.delta?.reasoning_content??n.delta?.reasoning;if(u){let c=xo(u,t.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});c&&i.push({text:c,thought:!0})}}if(typeof n.delta?.content=="string"){let u=xo(n.delta.content,t.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(u||n.finish_reason)&&i.push(...bt(u,t,!!n.finish_reason))}else n.finish_reason&&i.push(...bt("",t,!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=Ko(a)),o.candidates=[l]}else o.candidates=[];return o.responseId=e.id,o.createTime=e.created?e.created.toString():new Date().getTime().toString(),o.modelVersion=t.model,o.promptFeedback={safetyRatings:[]},e.usage&&(o.usageMetadata=No(e.usage,Li(t))),o}function Ni(e){let t=e.toolCallParser;if(!t)return null;let n=[],o=t.getStrictCompletedToolCalls(),r=t.hasIncompleteToolCalls();for(let s of o)s.name&&n.push({functionCall:{id:s.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:s.name,args:s.args}});if(n.push(...bt("",e,!0)),n.length===0&&!r)return null;let i=new le;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=e.model,i.promptFeedback={safetyRatings:[]},i}function Li(e){return{estimatedReasoningTokens:Se(e.reasoningDeltaState?.emittedLength??0),estimatedContentTokens:Se(e.textDeltaState?.emittedLength??0)}}function Ko(e){return e?{stop:w.STOP,length:w.MAX_TOKENS,content_filter:w.SAFETY,function_call:w.STOP,tool_calls:w.STOP}[e]||w.FINISH_REASON_UNSPECIFIED:w.FINISH_REASON_UNSPECIFIED}function Fi(e){if(!e)return"stop";switch(e){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 bn(e){return e.role==="assistant"&&"tool_calls"in e&&Array.isArray(e.tool_calls)&&e.tool_calls.length>0}function Po(e){if(e.role!=="user"||!("content"in e)||!Array.isArray(e.content))return!1;let t=e.content[0];return t?.type==="text"&&t.text===Do}function Gi(e){let t=[],n=new Map,o=new Map,r=new Map,i=new Set,s=new Set;for(let a=0;a<e.length;a+=1){let l=e[a];if(bn(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<e.length;y+=1){let C=e[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(Po(C)){h&&m.push(y);continue}if(!(C.role==="assistant"&&!bn(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<e.length;a+=1){if(i.has(a))continue;let l=e[a];if(bn(l)){let u=l.reasoning_content,c=n.get(a)??[];if(c.length>0){let f={...l};f.tool_calls=c,t.push(f);for(let d of o.get(a)??[]){let m=e[d];m&&(t.push(m),i.add(d))}for(let d of r.get(a)??[]){let m=e[d];m&&(t.push(m),i.add(d))}}else if(typeof l.content=="string"&&l.content.trim()||u){let f={...l};delete f.tool_calls,t.push(f)}else Y.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?Y.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):Po(l)?Y.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):t.push(l)}return t}function Uo(e){let t=[];for(let n of e){if(n.role==="assistant"&&t.length>0){let o=t[t.length-1];if(o.role==="assistant"){let r="tool_calls"in o?o.tool_calls||[]:[],i="tool_calls"in n?n.tool_calls||[]:[],s=o.content,a=n.content,l=Array.isArray(s)||Array.isArray(a),u;if(l){let 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}}t.push(n)}return t}var vt={convertGeminiToolParametersToOpenAI:Lo,convertGeminiToolsToOpenAI:vi,convertGeminiRequestToOpenAI:Mi,convertGeminiResponseToOpenAI:_i,convertOpenAIResponseToGemini:Ui,convertOpenAIChunkToGemini:Di,flushOpenAIStreamToGemini:Ni};p();p();var He=ct,Ki="https://matilda.maincode.com",z="Matilda has moved to https://matilda.com. Update your server address and sign in again.";function Mt(e){try{return new URL(e).hostname==="matilda.maincode.com"}catch{return!1}}function J(e){if(Mt(e))throw new Error(z);if(Ee(e)){let t=new URL(e);if(t.origin!==He||t.username||t.password)throw new Error("Use https://matilda.com for Matilda sign-in and API requests.")}}function Ee(e){try{return new URL(e).hostname==="matilda.com"}catch{return!1}}function H(e){if(e.baseUrl&&Mt(e.baseUrl))return!0;try{return e.baseUrl&&new URL(e.baseUrl).origin!==He?!1:JSON.parse(Buffer.from(e.accessToken.split(".")[1]??"","base64url").toString()).iss===Ki}catch{return!1}}p();var lu=new Set(["ECONNRESET","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET","ConnectionClosed","ConnectionReset","ConnectionTimedOut"]),$o=new Set(["EAI_AGAIN","ECONNREFUSED","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","UND_ERR_CONNECT_TIMEOUT","ConnectionRefused","FailedToOpenSocket","HostUnreachable","NetworkUnreachable"]);p();var kt="NOT_A_PROXY",$i=/^(?:UND_ERR_SOCKET|HPE_.*|ERR_SSL_(?:WRONG_VERSION_NUMBER|PACKET_LENGTH_TOO_LONG|HTTP_REQUEST|UNKNOWN_PROTOCOL))$/,Bi={"http:":80,"https:":443},ji=/^(?:(?:.+\.)?localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|::1)$/;function Vi(e){let t=e.toLowerCase().replace(/^\*?\./,"");if(t==="*")return{host:"*",wildcard:!0};let n=t.match(/^\[(.+)\](?::(\d+))?$/)??t.match(/^([^:]+):(\d+)$/),o=n?.[1]??t;return n?.[2]?{host:o,port:Number(n[2]),wildcard:!1}:{host:o,wildcard:!1}}function zi(e){return(e??"").split(/[,\s]+/).filter(Boolean)}function du(e){return zi(e).map(Vi)}function Hi(e,t){let n=typeof e=="string"?new URL(e):e,o=n.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(ji.test(o))return!0;let r=n.port?Number(n.port):Bi[n.protocol];return t.some(i=>i.wildcard||(i.port===void 0||i.port===r)&&(o===i.host||o.endsWith(`.${i.host}`)))}function pu(e){let t=e.connect.bind(e);return e.connect=async n=>{try{return await t(n)}catch(o){let{code:r}=o;throw typeof r=="string"&&$i.test(r)?Object.assign(new Error("The address did not answer as a proxy."),{code:kt}):o}},e}var _t;function fu(e,t=[]){_t=e?{host:new URL(e).host,noProxy:t}:void 0}function Bo(e){return _t&&URL.canParse(e)&&!Hi(e,_t.noProxy)?_t.host:void 0}var We="MATILDA_BASE_URL",Wi=new Set(["localhost","127.0.0.1","[::1]"]);function X(e){return N(e.trim()).replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}var zo=new Set;function Ho(e){let t=X(e||B());try{let{origin:n,pathname:o}=new URL(t);return`${n}${o.replace(/\/+$/,"")}`}catch{return t}}function qi(e){zo.add(Ho(e))}function Eu(e,t=(n,o)=>globalThis.fetch(n,o)){return async(n,o)=>{let r=await t(n,o);return qi(e),r}}function Au(e){return zo.has(Ho(e))}function Ru(e){try{let{host:t}=new URL(X(e));return t===new URL(Ke).host?"Matilda":t}catch{return e}}function Wo(e){let t;try{t=new URL(X(e))}catch{return}if(!(!(t.protocol==="https:"||t.protocol==="http:"&&Wi.has(t.hostname))||t.username||t.password||t.search||t.hash))return`${t.origin}${t.pathname.replace(/\/+$/,"")}/api/v1/code`}function qo(e=process.env){let t=e[We]?.trim();return t?Wo(t):void 0}function qe(e,t=process.env){let n=qo(t);if(!n||!e)return!1;try{return new URL(e).origin===new URL(n).origin}catch{return!1}}function vn(e){return e.apiKeyEnvKey===ut||Yi(e.baseUrl)}function Yi(e){if(!e)return!0;let t=e.endsWith("/")?e.slice(0,-1):e,n=null;try{n=new URL(t).hostname.toLowerCase()}catch{n=null}return n!==null&&(he(n)||n==="localhost"||n==="127.0.0.1"||n.endsWith(".matilda")||n==="core-api.matilda")||qe(t)}var wt="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.",Ji=new Map([["UNABLE_TO_GET_ISSUER_CERT_LOCALLY",wt],["UNABLE_TO_VERIFY_LEAF_SIGNATURE",wt],["SELF_SIGNED_CERT_IN_CHAIN",wt],["DEPTH_ZERO_SELF_SIGNED_CERT",wt],["CERT_HAS_EXPIRED","its certificate has expired."],["ERR_TLS_CERT_ALTNAME_INVALID","its certificate is for another name. Check the address."]]),jo="its name does not resolve. Check the address and your network.",Vo="it refused the connection. Check the address, and that it is running.",Xi=new Map([["ENOTFOUND",jo],["EAI_AGAIN",jo],["ECONNREFUSED",Vo],["ConnectionRefused",Vo],["UND_ERR_CONNECT_TIMEOUT","it did not answer. Check your network, VPN and proxy."]]),Yo=5,Qi=/^Proxy response \((\d+)\)/,Jo=e=>e?`the proxy at ${e}`:"your proxy";function Zi(e,t){let n=Jo(t);if(e===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 e===403?`${n} blocks it (403). Ask your network team to allow it, or ${o}.`:`${n} could not connect to it (${e}). Check the address, or ${o}.`}function Ye(e,t){if(V(e)!==void 0)return;let n=Bo(t),o=e;for(let r=0;r<=Yo;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"?Qi.exec(l):null;if(u)return new me(`Could not reach ${X(t)}: ${Zi(Number(u[1]),n)}`,"UND_ERR_ABORTED");if(s===kt)return new me(`Could not reach ${X(t)}: ${Jo(n)} did not answer as a proxy. Check its address, and whether it starts with http:// or https://.`,kt);if(typeof s=="string"){let c=X(t),f=Ji.get(s);if(f)return new me(`Could not connect securely to ${c}: ${f}`,s);if($o.has(s))return new me(`Could not reach ${n?`the proxy at ${n}, for ${c}`:c}: ${Xi.get(s)??"the network cannot reach it. Check your network, VPN and proxy."}`,s)}o=a}}function Mn(e,t){let n=e;for(let o=0;o<=Yo;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 me(`${X(t)} did not answer in time. Check your network, VPN and proxy.`,"ETIMEDOUT");n=s}}function es(e=process.env){let t=e[We]?.trim();if(t&&J(t),t&&!Wo(t))throw new st(`${We} must be the HTTPS address of your Matilda deployment, such as https://matilda.example.com. HTTP is accepted only for localhost.`)}function B(e=process.env){return es(e),qo(e)??Ke}p();p();p();on();var ts=new Set(["service.version","service.instance.id","session.id"]);function de(e,t){lt.warn(e),t?.push(e)}function Xo(e,t){if(!e)return{};let n={};for(let o of e.split(",")){let r=o.trim();if(!r)continue;let i=r.indexOf("=");if(i<0){de(`Skipping malformed OTEL_RESOURCE_ATTRIBUTES entry: "${r}" (hint: percent-encode literal commas as %2C)`,t);continue}let s=r.slice(0,i).trim();if(!s)continue;let a=r.slice(i+1).trim(),l;try{l=decodeURIComponent(s)}catch{de(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,t),l=s}let u;try{u=decodeURIComponent(a)}catch{de(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${l}", using raw value`,t),u=a}n[l]=u}return n}function _n(e,t,n){for(let o of ts)o in e&&(de(`${t} cannot override reserved key "${o}"; ignoring`,n),delete e[o]);return e}function Qo(e,t){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))return de("settings.telemetry.resourceAttributes must be an object; ignoring",t),{};let n={};for(let[o,r]of Object.entries(e)){let i=o.trim();if(!i){de("settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",t);continue}typeof r=="string"?n[i]=r:de(`settings.telemetry.resourceAttributes value for "${i}" must be a string (got ${typeof r}); ignoring`,t)}return n}function Je(e){if(e!==void 0)return e==="true"||e==="1"}async function ns(e){let t=e.argv??{},n=e.env??{},o=e.settings??{},r=t.telemetry??Je(n.MATILDA_TELEMETRY_ENABLED)??o.enabled,i=t.telemetryOtlpEndpoint??n.MATILDA_TELEMETRY_OTLP_ENDPOINT??n.OTEL_EXPORTER_OTLP_ENDPOINT??o.otlpEndpoint,s=t.telemetryOtlpProtocol??n.MATILDA_TELEMETRY_OTLP_PROTOCOL??o.otlpProtocol,a=["grpc","http"].find(b=>b===s);if(s!==void 0&&a===void 0)throw new st(`Invalid telemetry OTLP protocol: ${String(s)}. Valid values are: grpc, http`);let l=t.telemetryLogPrompts??Je(n.MATILDA_TELEMETRY_LOG_PROMPTS)??o.logPrompts,u=Je(n.MATILDA_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES)??o.includeSensitiveSpanAttributes??!1,c=t.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=_n(Xo(n.OTEL_RESOURCE_ATTRIBUTES,h),"OTEL_RESOURCE_ATTRIBUTES",h),y=_n(Qo(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=Je(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();on();import*as oe from"node:fs";import*as en from"node:path";p();p();p();p();on();p();import{AsyncLocalStorage as os}from"node:async_hooks";var Zo=new os;p();import*as j from"node:path";import{promises as Ot}from"node:fs";p();p();import rs from"crypto";var It=new Uint8Array(256),xt=It.length;function kn(){return xt>It.length-16&&(rs.randomFillSync(It),xt=0),It.slice(xt,xt+=16)}p();var x=[];for(let e=0;e<256;++e)x.push((e+256).toString(16).slice(1));function er(e,t=0){return x[e[t+0]]+x[e[t+1]]+x[e[t+2]]+x[e[t+3]]+"-"+x[e[t+4]]+x[e[t+5]]+"-"+x[e[t+6]]+x[e[t+7]]+"-"+x[e[t+8]]+x[e[t+9]]+"-"+x[e[t+10]]+x[e[t+11]]+x[e[t+12]]+x[e[t+13]]+x[e[t+14]]+x[e[t+15]]}p();p();import is from"crypto";var wn={randomUUID:is.randomUUID};function ss(e,t,n){if(wn.randomUUID&&!t&&!e)return wn.randomUUID();e=e||{};let o=e.random||(e.rng||kn)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,t){n=n||0;for(let r=0;r<16;++r)t[n+r]=o[r];return t}return er(o)}var xn=ss;import*as ne from"os";var Pt=K("OPENAI_LOGGER"),as="########",ls=/^[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 us(e,t){let n=t||process.cwd();if(!e)return j.join(n,"logs","openai");let o=e;return e==="~"||e.startsWith("~/")?o=j.join(ne.homedir(),e.slice(1)):j.isAbsolute(e)||(o=j.resolve(n,e)),j.normalize(o)}function tr(e){return e&&e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function cs(e){let t=e.split("#");if(t.length!==3)return;let[,n,o]=t;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function ds(e){if(e)return Ce(e)?tr(e):tr(cs(e))}function ps(e){if(!e)return;let t=e.indexOf(as);if(t>0)return e.slice(0,t);if(ls.test(e))return e;let n=e.split("#");if(n.length>=3&&n[0])return n[0]}function fs(e){let t=e?.trim(),n=ps(t);return!t&&!n?null:{...t?{promptId:t}:{},...n?{sessionId:n}:{}}}var Xe=class{logDir;initialized=!1;constructor(t,n){this.logDir=us(t,n)}async initialize(){if(!this.initialized)try{await Ot.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(t){throw Pt.error("Failed to initialize OpenAI logger:",t),new Error(`Failed to initialize OpenAI logger: ${t}`)}}async logInteraction(t,n,o,r){this.initialized||await this.initialize();let i=new Date().toISOString().replace(/:/g,"-"),s=xn().slice(0,8),a=ds(r),l=a?`openai-${i}-${s}-${a}.json`:`openai-${i}-${s}.json`,u=j.join(this.logDir,l),c={timestamp:new Date().toISOString(),request:t,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:fs(r),system:{hostname:ne.hostname(),platform:ne.platform(),release:ne.release(),nodeVersion:process.version}};try{return await Ot.writeFile(u,JSON.stringify(c,(f,d)=>typeof d=="string"?go(d):d,2),"utf-8"),u}catch(f){throw Pt.error("Failed to write OpenAI log file:",f),new Error(`Failed to write OpenAI log file: ${f}`)}}async getLogFiles(t){this.initialized||await this.initialize();try{let o=(await Ot.readdir(this.logDir)).filter(r=>r.startsWith("openai-")&&r.endsWith(".json")).map(r=>j.join(this.logDir,r)).sort().reverse();return t?o.slice(0,t):o}catch(n){return n.code==="ENOENT"?[]:(Pt.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(t){try{let n=await Ot.readFile(t,"utf-8");return JSON.parse(n)}catch(n){throw Pt.error(`Failed to read log file ${t}:`,n),new Error(`Failed to read log file: ${n}`)}}},oc=new Xe;p();var gs="MATILDA_CODE_PROFILE_RUNTIME";function nr(e=process.env){return e[gs]==="1"}var On=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;requests=[];openaiWireRequests=[];tools=or();constructor(t={}){this.enabled=t.enabled??nr(),this.now=t.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(t={}){this.enabled=t.enabled??nr(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.tools=or()}isEnabled(){return this.enabled}recordGenerateContentRequest(t,n){this.enabled&&(this.requestIndex+=1,this.requests.push({index:this.requestIndex,timestamp:this.now(),source:n.source,model:t.model,stream:n.stream,serializedBytes:U(Ss(t)),contents:rr(t.contents),systemInstructionBytes:Cs(t.config?.systemInstruction),generationConfigBytes:U(ir(t.config)),tools:Ts(t.config?.tools)}))}recordOpenAIWireRequest(t){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...ms(t)}))}recordToolUse(t,n){if(!this.enabled)return;let o=U(n),r=this.getToolNameDiagnostics(t);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(t){if(!this.enabled)return;let n=this.getToolNameDiagnostics(t.name);n.results+=1,n.resultBytes+=t.resultBytes,n.maxResultBytes=Math.max(n.maxResultBytes,t.resultBytes),t.isError&&(n.errors+=1,this.tools.toolResultErrorCount+=1),this.tools.toolResultCount+=1,this.tools.totalToolResultBytes+=t.resultBytes,this.tools.maxToolResultBytes=Math.max(this.tools.maxToolResultBytes,t.resultBytes)}snapshot(){return{enabled:this.enabled,startedAt:this.startedAt,requests:this.requests.map(t=>({...t,contents:{...t.contents,roleCounts:{...t.contents.roleCounts}},tools:{...t.tools}})),openaiWireRequests:this.openaiWireRequests.map(t=>({...t,messageBytesByRole:{...t.messageBytesByRole},topLevelKeys:[...t.topLevelKeys]})),tools:{...this.tools,byName:Object.fromEntries(Object.entries(this.tools.byName).map(([t,n])=>[t,{...n}]))}}}getToolNameDiagnostics(t){let n=this.tools.byName[t];if(n)return n;let o=hs();return this.tools.byName[t]=o,o}},Pn=new On;function ms(e){let t=Ae(e),n=Array.isArray(t.messages)?t.messages:[],o=Array.isArray(t.tools)?t.tools:[],r={};for(let i of n){let s=Ae(i),a=typeof s.role=="string"?s.role:"unknown";r[a]=(r[a]??0)+U(s.content)}return{model:typeof t.model=="string"?t.model:"unknown",stream:t.stream===!0,bodyBytes:U(e),messageCount:n.length,messageBytesByRole:r,toolsCount:o.length,toolSchemaBytes:U(o),topLevelKeys:Object.keys(t).sort()}}function or(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function hs(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function rr(e){let t={count:0,roleCounts:{},partCount:0,textBytes:0,functionCallCount:0,functionCallArgBytes:0,functionResponseCount:0,functionResponseBytes:0,inlineDataCount:0,inlineDataBytes:0,fileDataCount:0},n=Array.isArray(e)?e:e==null?[]:[e];for(let o of n){if(t.count+=1,typeof o=="string"){t.roleCounts.user=(t.roleCounts.user??0)+1,t.partCount+=1,t.textBytes+=U(o);continue}let r=Ae(o),i=typeof r.role=="string"?r.role:"unknown";t.roleCounts[i]=(t.roleCounts[i]??0)+1;let s=Array.isArray(r.parts)?r.parts:[];ys(s,t)}return t}function Cs(e){return rr(e).textBytes}function ys(e,t){for(let n of e){if(t.partCount+=1,typeof n=="string"){t.textBytes+=U(n);continue}let o=Ae(n);typeof o.text=="string"&&(t.textBytes+=U(o.text));let r=In(o.functionCall);r&&(t.functionCallCount+=1,t.functionCallArgBytes+=U(r.args));let i=In(o.functionResponse);i&&(t.functionResponseCount+=1,t.functionResponseBytes+=U(i.response)+U(i.parts));let s=In(o.inlineData);s&&(t.inlineDataCount+=1,t.inlineDataBytes+=U(s.data)),o.fileData&&(t.fileDataCount+=1)}}function Ts(e){let t=Array.isArray(e)?e:[],n=0;for(let o of t){let r=Ae(o),i=Array.isArray(r.functionDeclarations)?r.functionDeclarations:[];n+=i.length}return{count:t.length,functionDeclarationCount:n,schemaBytes:U(t)}}function Ss(e){return{model:e.model,contents:e.contents,config:ir(e.config)}}function ir(e){if(!e)return;let t=Ae(e),n={};for(let[o,r]of Object.entries(t))o!=="abortSignal"&&(n[o]=r);return n}function U(e){return e==null?0:typeof e=="string"?Buffer.byteLength(e,"utf8"):Buffer.byteLength(Es(e),"utf8")}function Es(e){try{return JSON.stringify(e)??""}catch{return"[unserializable]"}}function Ae(e){return typeof e=="object"&&e!==null?e:{}}function In(e){return typeof e=="object"&&e!==null?e:null}p();function sr(e){let t=e.candidates?.[0]?.content?.parts;return!t||t.length===0?!1:t.some(As)}function As(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.text=="string"&&t.text.length>0||t.functionCall!==void 0||t.inlineData!==void 0||t.executableCode!==void 0||t.thought===!0}function ar(){let e=lo.getStore();return{attempt:e?.attempt??1,requestSetupMs:e?.requestSetupMs,retryTotalDelayMs:e?.retryTotalDelayMs}}var pe=K("LOGGING_CONTENT_GENERATOR"),Rs=4096,lr="...[truncated]",bs=Rs-lr.length,Qe=class{constructor(t,n,o){this.wrapped=t;this.config=n;this.modalities=o.modalities,this.splitToolMedia=o.splitToolMedia,this.generatorAuthType=o.authType,o.enableOpenAILogging&&(this.openaiLogger=new Xe(o.openAILoggingDir,n.getWorkingDir()),this.schemaCompliance=o.schemaCompliance)}openaiLogger;schemaCompliance;modalities;splitToolMedia;generatorAuthType;getWrapped(){return this.wrapped}logApiRequest(t,n,o){let r=JSON.stringify(t);sn(this.config,new un(n,o,r,Z.getStore()))}_logApiResponse(t,n,o,r,i,s){ln(this.config,new dn(t,o,n,r,this.generatorAuthType,i,s,Z.getStore()))}_logApiError(t,n,o,r,i){let s=po(o),a=Ge(o),l=o?.requestID||o?.request_id||t,u=V(o);an(this.config,new cn({responseId:l,model:r,durationMs:n,promptId:i,authType:this.generatorAuthType,errorMessage:s,errorType:a,statusCode:u,subagentName:Z.getStore()}))}safelyLogApiError(t,n,o,r,i){try{this._logApiError(t,n,o,r,i)}catch(s){pe.warn("Failed to log API error:",s)}}safelyLogApiResponse(t,n,o,r,i,s){try{this._logApiResponse(t,n,o,r,i,s)}catch(a){pe.warn("Failed to log API response:",a)}}getClientVisibleModelId(t,n){return("isManagedMatildaModel"in this.config&&typeof this.config.isManagedMatildaModel=="function"?this.config.isManagedMatildaModel(t):!1)&&"getPublicModelId"in this.config&&typeof this.config.getPublicModelId=="function"?this.config.getPublicModelId(t):n||t}async generateContent(t,n){let o=ar(),r=gt(t.model,n);try{r.setAttribute("llm_request.stream",!1)}catch{}let i=nn.setSpan(W.active(),r),s=Date.now(),a=Ce(n),l=this.startCaptureSession();try{Pn.recordGenerateContentRequest(t,{stream:!1,source:"generateContent"}),a||(dt(this.config,r,t.config?.systemInstruction),pt(this.config,r,t.config?.tools));let u=await W.with(i,async()=>{a||this.logApiRequest(this.toContents(t.contents),t.model,n);let c=await l.wrap(()=>this.wrapped.generateContent(t,n)),f=Date.now()-s,d=a?void 0:this.extractResponseText(c);a||ft(this.config,r,d),this.safelyLogApiResponse(c.responseId??"",f,this.getClientVisibleModelId(t.model,c.modelVersion),n,c.usageMetadata,d);try{await this.safelyLogOpenAIInteraction(await l.resolve(t),c,void 0,n)}catch(m){pe.warn("Failed to log OpenAI interaction:",m)}return c});return ue(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:Z.getStore()||void 0,...o}),u}catch(u){let c=Date.now()-s,f=t.config?.abortSignal?.aborted??!1;throw ue(r,{success:!1,durationMs:c,error:f?ht:mt,errorType:Ge(u),errorStatusCode:V(u),subagentName:Z.getStore()||void 0,...o}),await W.with(i,async()=>{this.safelyLogApiError("",c,u,this.getClientVisibleModelId(t.model),n);try{await this.safelyLogOpenAIInteraction(await l.resolve(t),void 0,u,n)}catch(d){pe.warn("Failed to log OpenAI interaction:",d)}}),u}}async generateContentStream(t,n){let o=ar(),r=gt(t.model,n);try{r.setAttribute("llm_request.stream",!0)}catch{}let i=nn.setSpan(W.active(),r),s=Date.now(),a=Ce(n),l=this.startCaptureSession(),u;try{Pn.recordGenerateContentRequest(t,{stream:!0,source:"generateContentStream"}),a||(dt(this.config,r,t.config?.systemInstruction),pt(this.config,r,t.config?.tools)),u=await W.with(i,async()=>(a||this.logApiRequest(this.toContents(t.contents),t.model,n),l.wrap(()=>this.wrapped.generateContentStream(t,n))))}catch(f){let d=Date.now()-s;W.with(i,()=>this.safelyLogApiError("",d,f,t.model,n));let m=t.config?.abortSignal?.aborted??!1;ue(r,{success:!1,durationMs:d,error:m?ht:mt,errorType:Ge(f),errorStatusCode:V(f),subagentName:Z.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(t),void 0,f,n)}catch(h){pe.warn("Failed to log OpenAI interaction:",h)}throw f}let c;if(this.openaiLogger)try{c=await l.resolve(t)}catch(f){pe.warn("Failed to resolve OpenAI request:",f)}return W.with(i,()=>this.loggingStreamWrapper(u,s,n,t.model,c,r,i,t.config?.abortSignal,o))}startCaptureSession(){let t,n=!this.openaiLogger;return{wrap:o=>n?o():Zo.run(r=>{t=r},o),resolve:async o=>this.openaiLogger?t??await this.buildOpenAIRequestForLogging(o):void 0}}async*loggingStreamWrapper(t,n,o,r,i,s,a,l,u){let c=Ce(o),f=!c||!!this.openaiLogger,d=[],m="",h="",g,y=!1,C,S=!1,E,M=Z.getStore(),b,_=!1,F=I=>a?W.with(a,I):I(),re=5*6e4,P,ge=s?()=>{_||(P!==void 0&&clearTimeout(P),P=setTimeout(()=>{try{s.setAttribute("stream.timed_out",!0)}catch{}ue(s,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:m||void 0,subagentName:M||void 0,...u}),_=!0},re),P.unref())}:void 0;try{for await(let D of t){!m&&D.responseId&&(m=D.responseId),!h&&D.modelVersion&&(h=D.modelVersion),f&&d.push(D),D.usageMetadata&&(g=D.usageMetadata);let Le=D.candidates?.[0];Le?.finishReason&&(C=Le.finishReason),D.functionCalls?.length&&(S=!0),b===void 0&&sr(D)&&(b=Date.now()-n),ge?.(),yield D,P!==void 0&&(clearTimeout(P),P=void 0)}P!==void 0&&(clearTimeout(P),P=void 0);let I=Date.now()-n,ie=f?this.consolidateGeminiResponsesForLogging(d):void 0,rt=c?void 0:this.extractResponseText(ie),se=!C&&!S?new Error("Model stream ended without a finish reason"):void 0;se&&(y=!0,E=se),_||(se?(F(()=>this.safelyLogApiError(m,I,se,this.getClientVisibleModelId(r,h),o)),await F(()=>this.safelyLogOpenAIInteraction(i,ie,se,o))):(F(()=>this.safelyLogApiResponse(m,I,this.getClientVisibleModelId(r,h),o,g,rt)),!c&&s&&ft(this.config,s,rt),await F(()=>this.safelyLogOpenAIInteraction(i,ie,void 0,o))))}catch(I){if(y=!0,E=I,!_){let ie=Date.now()-n;F(()=>this.safelyLogApiError(m,ie,I,this.getClientVisibleModelId(r,h),o)),await F(()=>this.safelyLogOpenAIInteraction(i,void 0,I,o))}throw I}finally{if(P!==void 0&&clearTimeout(P),s&&!_){let I=l?.aborted??!1;ue(s,{success:!y,inputTokens:g?.promptTokenCount,outputTokens:g?.candidatesTokenCount,cachedInputTokens:g?.cachedContentTokenCount,ttftMs:b,durationMs:Date.now()-n,error:y?I?ht:mt:void 0,responseId:m||void 0,finishReason:C,thoughtsTokenCount:g?.thoughtsTokenCount,subagentName:M||void 0,errorType:E?Ge(E):void 0,errorStatusCode:E?V(E):void 0,...u})}}}async buildOpenAIRequestForLogging(t){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(t.model),o=vt.convertGeminiRequestToOpenAI(t,n,{cleanOrphanToolCalls:!1}),r={model:t.model,messages:o};return t.config?.tools&&(r.tools=await vt.convertGeminiToolsToOpenAI(t.config.tools,this.schemaCompliance??"auto")),t.config?.temperature!==void 0&&(r.temperature=t.config.temperature),t.config?.topP!==void 0&&(r.top_p=t.config.topP),t.config?.maxOutputTokens!==void 0&&(r.max_tokens=t.config.maxOutputTokens),t.config?.presencePenalty!==void 0&&(r.presence_penalty=t.config.presencePenalty),t.config?.frequencyPenalty!==void 0&&(r.frequency_penalty=t.config.frequencyPenalty),r}createLoggingRequestContext(t){return{model:t,modalities:this.modalities??{},splitToolMedia:this.splitToolMedia??!0,startTime:0}}async logOpenAIInteraction(t,n,o,r){if(!this.openaiLogger||!t)return;let i=n?this.convertGeminiResponseToOpenAIForLogging(n,t):void 0;await this.openaiLogger.logInteraction(t,i,o instanceof Error?o:o?new Error(String(o)):void 0,r)}async safelyLogOpenAIInteraction(t,n,o,r){try{await this.logOpenAIInteraction(t,n,o,r)}catch(i){pe.warn("Failed to log OpenAI interaction:",i)}}convertGeminiResponseToOpenAIForLogging(t,n){let o=new le;return Object.assign(o,t),o.modelVersion=this.getClientVisibleModelId(n.model,t.modelVersion),vt.convertGeminiResponseToOpenAI(o,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(t){if(t.length===0)return;let n=new le,o=[],r=new Map,i,s;for(let u of t){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=t[t.length-1],l=a.candidates?.[0];return n.responseId=a.responseId,n.createTime=a.createTime,n.modelVersion=a.modelVersion,n.promptFeedback=a.promptFeedback,n.usageMetadata=s,n.candidates=[{content:{role:l?.content?.role||"model",parts:o},...i?{finishReason:i}:{},index:0,safetyRatings:l?.safetyRatings||[]}],n}extractResponseText(t){let n=t?.candidates?.[0]?.content?.parts;if(!n?.length)return;let o="",r=!1,i=!1,s=a=>{if(r=!0,i)return;let l=bs-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}${lr}`:o}async countTokens(t){return this.wrapped.countTokens(t)}async embedContent(t){return this.wrapped.embedContent(t)}useSummarizedThinking(){return this.wrapped.useSummarizedThinking()}toContents(t){return Array.isArray(t)?t.map(n=>this.toContent(n)):[this.toContent(t)]}toContent(t){return Array.isArray(t)?{role:"user",parts:this.toParts(t)}:typeof t=="string"?{role:"user",parts:[{text:t}]}:"parts"in t?{...t,parts:t.parts?this.toParts(t.parts.filter(n=>n!=null)):[]}:{role:"user",parts:[this.toPart(t)]}}toParts(t){return t.map(n=>this.toPart(n))}toPart(t){if(typeof t=="string")return{text:t};if("thought"in t&&t.thought){let n=`[Thought: ${t.thought}]`,o={...t};if(delete o.thought,"functionCall"in o||"functionResponse"in o||"inlineData"in o||"fileData"in o)return o;let i=o.text,s=i?String(i):"",a=s?`${s}
15
- ${n}`:n;return{...o,text:a}}return t}};p();var Un="x-matilda-organization-id",vs=/^[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 Pc(e){if(e!==void 0){if(typeof e!="string"||e.length!==36||!vs.test(e))throw new Error("--organization-id must be a single UUID.");return e.toLowerCase()}}function Dn(e){if(e)try{let t=new URL(e);if((t.origin===ct&&t.protocol==="https:"&&!t.port||t.hostname==="core-api.matilda"&&(t.protocol==="http:"||t.protocol==="https:"))&&!t.username&&!t.password&&!t.search&&!t.hash)return t}catch{}}function Ms(e){let t=Dn(e.baseUrl);return!!t&&t.pathname.replace(/\/$/,"")==="/api/v1/code"&&e.authType==="openai"}function Nn(e,t,n){if(!(t===void 0&&n===void 0)&&!Ms(e))throw new Error("Organization selection and credit spending require the first-party Matilda Core Code endpoint.")}function ur(e){for(let t of Object.keys(e??{})){let n=t.toLowerCase();if(n===Un)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 Uc(e,t,n,o,r){Nn(n,o,r);let i=Dn(n.baseUrl),s=Dn(e instanceof Request?e.url:String(e));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=t.get(Un);if(a!==null&&a!==o)throw new Error("The request organization conflicts with --organization-id.");o!==void 0&&t.set(Un,o)}p();function cr(e){switch(e){case"openai":return"OPENAI_API_KEY";default:return"API_KEY"}}function dr(e){switch(e){case"openai":return"OPENAI_MODEL";default:return"MODEL"}}var be=class extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}},Ut=class extends be{name="StrictMissingCredentialsError";code="STRICT_MISSING_CREDENTIALS";constructor(t,n,o){let r=t||"(unknown)",i=n||"(unknown)";super(`Missing credentials for modelProviders model '${i}'. `+(o?`Current configured envKey: '${o}'. Set that environment variable, or update modelProviders.${r}[].envKey.`:`Configure modelProviders.${r}[].envKey and set that environment variable.`))}},Dt=class extends be{name="StrictMissingModelIdError";code="STRICT_MISSING_MODEL_ID";constructor(t){super(`Missing model id for strict modelProviders resolution (authType: ${t}).`)}},Nt=class extends be{name="MissingApiKeyError";code="MISSING_API_KEY";constructor(t){super(`Missing API key for ${t.authType} auth. Current model: '${t.model||"(unknown)"}', baseUrl: '${t.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${t.envKey}'.`)}},Lt=class extends be{name="MissingModelError";code="MISSING_MODEL";constructor(t){super(`Missing model for ${t.authType} auth. Set the environment variable '${t.envKey}'.`)}};p();import $n from"node:process";p();function Gc(e,t,n,o=2048){let r=t-n-o;return!Number.isFinite(r)||r<=0?0:Math.min(e,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 Ft(e){let t=(e??"").toLowerCase().trim();return t=t.replace(/^.*\//,""),t=t.split("|").pop()??t,t=t.split(":").pop()??t,t=t.replace(/\s+/g,"-"),t=t.replace(/-preview/g,""),t.match(/^kimi-k2-\d{4}$/)||(t=t.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g,"")),t=t.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g,""),t}var _s=[[/^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"]]],pr=[[/^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 ks(e,t="input"){let n=Ft(e),o=t==="output"?pr:_s;for(let[r,i]of o)if(r.test(n))return i}function Kc(e){let t=Ft(e);return pr.some(([n])=>n.test(t))}function ws(e,t="input"){return ks(e,t)}function Gt(e,t="input"){return ws(e,t)??(t==="output"?32e3:131072)}p();p();var fr={image:!0,pdf:!0,audio:!0,video:!0},xs=[[/^gemini-3/,fr],[/^gemini-/,fr],[/^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 Kt(e){let t=Ft(e);for(let[n,o]of xs)if(n.test(t))return{...o};return{}}p();function gr(e,t,n={kind:"default"}){for(let o of e)if(mr(o.value))return{value:o.value,source:o.source};return{value:t,source:n}}function Ln(e){for(let t of e)if(mr(t.value))return{value:t.value,source:t.source}}function mr(e){return!(e==null||typeof e=="string"&&e.trim()==="")}function $t(e){return{kind:"cli",detail:e}}function Is(e){return{kind:"env",envKey:e}}function Ze(e){return{kind:"settings",settingsPath:e}}function ve(e,t,n){return{kind:"modelProviders",authType:e,modelId:t,detail:n}}function Fn(e){return{kind:"default",detail:e}}function Bt(e){return{kind:"computed",detail:e}}function jt(e,t,n){let o=e[t];return{value:o!==void 0?n?n(o):o:void 0,source:Is(t)}}function L(e,t){return{value:e,source:t}}p();var et=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","openAIRequestProfile"],hr=["model","apiKey","apiKeyEnvKey","baseUrl"],Gn=[...hr,...et],Cr={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","MATILDA_MODEL"]}},yr={openai:Ct};var Me="MATILDA_API_KEY",Os="matilda-code-1.0";function Ps(e,t){if(!e)return!0;try{let{hostname:n}=new URL(e);return he(n)||qe(e,t)}catch{return!1}}function Us(e,t,n,o){if(o?.timeout!==void 0)return;let r=e.MATILDA_CODE_API_TIMEOUT_MS;if(r===void 0)return;let i=Number(r);Number.isFinite(i)&&i>0&&(t.timeout=Math.floor(i),n.timeout={kind:"env",envKey:"MATILDA_CODE_API_TIMEOUT_MS"})}function rd(e){let{authType:t,cli:n,settings:o,env:r,modelProvider:i,proxy:s}=e,a=[],l={},u=t?Cr[t]:{model:[],apiKey:[],baseUrl:[]},c=[];t&&i&&c.push(L(i.id,ve(t,i.id,"model.id"))),n?.model&&c.push(L(n.model,$t("--model"))),t==="openai"&&r[Me]&&!r.OPENAI_MODEL&&!r.MATILDA_MODEL&&c.push(L(Os,{kind:"env",envKey:Me}));for(let b of u.model)c.push(jt(r,b));o?.model&&c.push(L(o.model,Ze("model.name")));let f=t?yr[t]:"",d=gr(c,f,Fn(f));l.model=d.source;let m=[];t&&i?.baseUrl&&m.push(L(i.baseUrl,ve(t,i.id,"baseUrl"))),n?.baseUrl&&m.push(L(n.baseUrl,$t("--openaiBaseUrl"))),t==="openai"&&r[Me]&&!r.OPENAI_BASE_URL&&(r[We]?.trim()||!o?.baseUrl)&&m.push(L(B(r),{kind:"env",envKey:Me}));for(let b of u.baseUrl)m.push(jt(r,b));o?.baseUrl&&m.push(L(o.baseUrl,Ze("security.auth.baseUrl")));let h=Ln(m)??(t==="openai"?{value:B(r),source:Fn("the configured Matilda endpoint")}:void 0);h&&(J(N(h.value)),l.baseUrl=h.source);let g=[];if(t&&i?.envKey){let b=r[i.envKey];b&&g.push(L(b,{kind:"env",envKey:i.envKey,via:ve(t,i.id,"envKey")}))}if(n?.apiKey&&g.push(L(n.apiKey,$t("--openaiApiKey"))),!i?.envKey){let b=r[Me];if(t==="openai"&&b&&Ps(h?.value,r)&&g.push(L(b,{kind:"env",envKey:Me})),h?.source.kind!=="default")for(let _ of u.apiKey)g.push(jt(r,_))}o?.apiKey&&g.push(L(o.apiKey,Ze("security.auth.apiKey")));let y=Ln(g);y&&(l.apiKey=y.source);let C;t&&i?.envKey&&(C=i.envKey,l.apiKeyEnvKey={...ve(t,i.id,"envKey"),envKey:i.envKey});let S=Vt(o?.generationConfig,i?.generationConfig,t,i?.id??d.value,r),E=S.config;Object.assign(l,S.sources);let M={authType:t,model:d.value||"",apiKey:y?.value,apiKeyEnvKey:C,baseUrl:h&&N(h.value),proxy:s,...E};return s&&(l.proxy=Bt("Config.getProxy()")),l.authType=Bt("provided by caller"),{config:M,sources:l,warnings:a}}function Vt(e,t,n,o,r){let i={},s=Ds(e,t,n,o,i);return Us(r,s,i,t),{config:s,sources:i}}function Ds(e,t,n,o,r){let i={};for(let s of et)n&&t&&s in t?(i[s]=t[s],r[s]=ve(n,o||"",`generationConfig.${s}`)):e&&s in e&&(i[s]=e[s],r[s]=Ze(`model.generationConfig.${s}`));return i.modalities===void 0&&o&&(i.modalities=Kt(o),r.modalities=Bt("auto-detected from model")),i}p();var zt="$runtime|";function ld(e){let t=e;for(;t.startsWith(zt);){let n=t.split("|").slice(2).join("|");if(!n)break;t=n}return t}p();p();var Tr=K("MODEL_REGISTRY");function Sr(e,t){return t?`${e}\0${N(t)}`:e}var Ht=class{constructor(t,n=!1){this.noFallbackServer=n;this.reloadModels(t)}models=new Map;registerModels(t){let n=new Map;for(let o of t){if(this.noFallbackServer&&!o.baseUrl)continue;let r=Sr(o.id,o.baseUrl);if(n.has(r)){Tr.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(t=>({id:t.id,label:t.name,description:t.description,capabilities:t.capabilities,authType:t.authType,isVision:t.capabilities?.vision??!1,contextWindowSize:t.generationConfig.contextWindowSize??Gt(t.id),modalities:t.generationConfig.modalities??Kt(t.id),baseUrl:t.baseUrl,envKey:t.envKey}))}findModel(t,n){if(n)return this.models.get(Sr(t,n));let o=this.models.get(t);if(o)return o;for(let r of this.models.values())if(r.id===t)return r}containsModel(t,n){return this.findModel(t,n)!==void 0}getDefaultModel(){return this.models.values().next().value}resolveModelConfig(t){return this.validateModelConfig(t),{...t,authType:"openai",name:t.name||t.id,baseUrl:N(t.baseUrl||B()),generationConfig:{...t.generationConfig??{}},capabilities:t.capabilities||{}}}validateModelConfig(t){if(!t.id)throw new Error("Model config in authType 'openai' missing required field: id")}reloadModels(t){this.models=new Map;for(let[n,o]of Object.entries(t??{})){if(n!=="openai"){Tr.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(Re).join(", ")}. Skipping.`);continue}this.models=this.registerModels(o)}}};var Er=class e{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;onModelChange;authTypeWasExplicitlyProvided;settingsGenerationConfig;runtimeModelSnapshots=new Map;activeRuntimeModelSnapshotId;static deepClone(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(o=>e.deepClone(o));let n={};for(let o of Object.keys(t))n[o]=e.deepClone(t[o]);return n}constructor(t={}){this.modelRegistry=new Ht(t.modelProvidersConfig,t.noFallbackServer),this.onModelChange=t.onModelChange,this._generationConfig={...t.generationConfig||{}},this.generationConfigSources=t.generationConfigSources||{},this.settingsGenerationConfig=e.deepClone(t.settingsGenerationConfig),this.authTypeWasExplicitlyProvided=t.initialAuthType!==void 0,this.currentAuthType=t.initialAuthType}createStateSnapshotForRollback(){return{currentAuthType:this.currentAuthType,generationConfig:e.deepClone(this._generationConfig),generationConfigSources:e.deepClone(this.generationConfigSources),strictModelProviderSelection:this.strictModelProviderSelection,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(t){this.currentAuthType=t.currentAuthType,this._generationConfig=t.generationConfig,this.generationConfigSources=t.generationConfigSources,this.strictModelProviderSelection=t.strictModelProviderSelection,this.activeRuntimeModelSnapshotId=t.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||Ct}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModels():[]}getAllConfiguredModels(){let t=this.getRuntimeModelOption();return[...t?[t]:[],...this.modelRegistry.getModels()]}getResolvedModel(t){let n=this.modelRegistry.findModel(t);if(n)return{...n,generationConfig:{...this.resolveEntryGenerationConfig(n).config,customHeaders:n.generationConfig.customHeaders}}}resolveEntryGenerationConfig(t){return Vt(this.settingsGenerationConfig,t.generationConfig,t.authType,t.id,$n.env)}isManagedMatildaResolvedModel(t){return t?.id===rn&&t?.envKey===ut&&t?.baseUrl===Ke&&t?.generationConfig?.openAIRequestProfile==="matilda-code"}isManagedMatildaModel(t){let n=t.trim();return!n||!this.currentAuthType?!1:this.isManagedMatildaResolvedModel(this.modelRegistry.findModel(n))}getPublicModelId(t){return this.isManagedMatildaModel(t)?rn:t}getModelDisplayName(t){return this.isManagedMatildaModel(t)?mo:this.currentAuthType?this.modelRegistry.findModel(t)?.name??t:t}async setModel(t,n){if(this.currentAuthType&&this.modelRegistry.containsModel(t)){await this.switchModel(this.currentAuthType,t);return}let o=this.createStateSnapshotForRollback();try{this.strictModelProviderSelection=!1,this._generationConfig.model=t,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.applyRawModelDerivedDefaults(t),this.onModelChange&&this.currentAuthType&&await this.onModelChange(this.currentAuthType)}catch(r){throw this.rollbackToStateSnapshot(o),r}}applyRawModelDerivedDefaults(t){let n=Vt(this.settingsGenerationConfig,void 0,this.currentAuthType,t,$n.env);this.shouldUpdateModelDerivedDefault("modalities")&&this.applyResolvedField("modalities",n),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this.applyResolvedField("contextWindowSize",n),this.fillContextWindowSize(t))}applyResolvedField(t,n){this._generationConfig[t]=e.deepClone(n.config[t]);let o=n.sources[t];o?this.generationConfigSources[t]=o:delete this.generationConfigSources[t]}fillContextWindowSize(t){this._generationConfig.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=Gt(t,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"})}shouldUpdateModelDerivedDefault(t){let n=this.generationConfigSources[t];return n===void 0||n.kind==="computed"||n.kind==="default"||n.kind==="modelProviders"||n.kind==="programmatic"||n.kind==="unknown"}async switchModel(t,n,o){let r=this.extractRuntimeModelSnapshotId(n);if(r){await this.switchToRuntimeModel(r);return}let i=this.createStateSnapshotForRollback();try{let s=t!==this.currentAuthType;this.currentAuthType=t;let a=this.modelRegistry.findModel(n,o?.baseUrl);if(!a)throw new Error(`Model '${n}' not found for authType '${t}'`);let l=i.generationConfig.model||"",u=!s&&l?this.modelRegistry.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=e.deepClone(d))),this.activeRuntimeModelSnapshotId=void 0,this.onModelChange&&await this.onModelChange(t)}catch(s){throw this.rollbackToStateSnapshot(i),s}}buildRuntimeModelSnapshotId(t,n){return`${zt}${t}|${n}`}extractRuntimeModelSnapshotId(t){if(t.startsWith(zt))return this.runtimeModelSnapshots.has(t)?t:void 0;if(this.runtimeModelSnapshots.has(t))return t}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}isStrictModelProviderSelection(){return this.strictModelProviderSelection}applyResolvedModelDefaults(t){if(this.strictModelProviderSelection=!0,this._generationConfig.model=t.id,this.generationConfigSources.model={kind:"modelProviders",authType:t.authType,modelId:t.id,detail:"model.id"},this._generationConfig.apiKey=void 0,this._generationConfig.apiKeyEnvKey=void 0,t.envKey!==void 0){let o=$n.env[t.envKey];o&&(this._generationConfig.apiKey=o,this.generationConfigSources.apiKey={kind:"env",envKey:t.envKey,via:{kind:"modelProviders",authType:t.authType,modelId:t.id,detail:"envKey"}}),this._generationConfig.apiKeyEnvKey=t.envKey,this.generationConfigSources.apiKeyEnvKey={kind:"modelProviders",authType:t.authType,modelId:t.id,detail:"envKey"}}this._generationConfig.baseUrl=t.baseUrl,this.generationConfigSources.baseUrl={kind:"modelProviders",authType:t.authType,modelId:t.id,detail:"baseUrl"};let n=this.resolveEntryGenerationConfig(t);for(let o of et)this.applyResolvedField(o,n);this.fillContextWindowSize(t.id)}syncAfterAuthRefresh(t,n,{replacesApiKey:o=!1}={}){this.strictModelProviderSelection=!1;let r=this.currentAuthType;this.currentAuthType=t;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===t&&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!==t)&&(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(t){this.onModelChange=t}detectAndCaptureRuntimeModel(){let{model:t,apiKey:n,baseUrl:o,apiKeyEnvKey:r,...i}=this._generationConfig,s=this.currentAuthType;if(!t||!s)return;if(this.modelRegistry.containsModel(t,o)){this.clearRuntimeModelSnapshotForAuthType(s);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(s,t),u={id:l,authType:s,modelId:t,apiKey:n,baseUrl:o,apiKeyEnvKey:r,generationConfig:i,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(l,u),this.activeRuntimeModelSnapshotId=l,this.cleanupOldRuntimeModelSnapshots(),l}getActiveRuntimeModelSnapshot(){if(this.activeRuntimeModelSnapshotId)return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId)}getActiveRuntimeModelSnapshotId(){return this.activeRuntimeModelSnapshotId}async switchToRuntimeModel(t){let n=this.runtimeModelSnapshots.get(t);if(!n)throw new Error(`Runtime model snapshot '${t}' not found`);let o=this.createStateSnapshotForRollback();try{this.currentAuthType=n.authType,this.activeRuntimeModelSnapshotId=t,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 t=this.getActiveRuntimeModelSnapshot();if(t)return{id:t.modelId,label:t.modelId,authType:t.authType,isVision:!1,contextWindowSize:t.generationConfig?.contextWindowSize,isRuntimeModel:!0,runtimeSnapshotId:t.id}}clearRuntimeModelSnapshotForAuthType(t){for(let[n,o]of this.runtimeModelSnapshots.entries())o.authType===t&&(this.runtimeModelSnapshots.delete(n),this.activeRuntimeModelSnapshotId===n&&(this.activeRuntimeModelSnapshotId=void 0))}cleanupOldRuntimeModelSnapshots(){let t=new Map;for(let n of this.runtimeModelSnapshots.values()){let o=t.get(n.authType);(!o||n.createdAt>o.createdAt)&&t.set(n.authType,n)}this.runtimeModelSnapshots.clear();for(let n of t.values())this.runtimeModelSnapshots.set(n.id,n);this.activeRuntimeModelSnapshotId&&!this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)&&(this.activeRuntimeModelSnapshotId=void 0)}reloadModelProvidersConfig(t){this.modelRegistry.reloadModels(t)}};p();import{randomUUID as da}from"node:crypto";import{mkdirSync as pa,readFileSync as fa}from"node:fs";import{dirname as ga,join as ma}from"node:path";p();p();import{randomBytes as Ns,createHash as Ls}from"node:crypto";import{setTimeout as Fs}from"node:timers/promises";var Gs="urn:ietf:params:oauth:grant-type:device_code";function Ar(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}function jn(){let e=Ns(32).toString("base64url"),t=Ls("sha256").update(e).digest("base64url");return{codeVerifier:e,codeChallenge:t}}function _e(e,t){let n=typeof e=="object"&&e!==null?e:{};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??t?.refreshToken,expiresAt:Date.now()+(n.expires_in??3600)*1e3,idToken:n.id_token??t?.idToken}}var Ks=15e3;async function Vn(e){let t=e.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",t);if(n.protocol!=="https:"&&!Ar(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(Ks)});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 $s=15e3,Bn="Device code expired: restart the sign-in";async function zn(e,t,n={}){let o;try{o=await fetch(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:t.clientId,scope:t.scope??"openid offline_access"}),signal:vr(AbortSignal.timeout($s),n.signal)})}catch(i){throw Mr(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 Rr(e,t,n={}){let o=await fetch(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:Gs,client_id:t.clientId,device_code:t.deviceCode}),signal:n.signal});if(o.ok)return{kind:"authorized",tokens:_e(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 br(e,t,n={}){let o=t.interval*1e3;try{for(;Date.now()<t.expiresAt;){await Fs(Math.min(o,t.expiresAt-Date.now()),void 0,{signal:n.signal});let r=t.expiresAt-Date.now();if(r<=0)break;let i=await Rr(e,t,{signal:vr(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(Bn);case"access_denied":throw new Error("User denied the authorization request");default:throw new Error(`Device flow error: ${i.error}`)}}}}catch(r){throw Mr(r,n.signal)?new Error(Bn):r}throw new Error(Bn)}function vr(e,t){return t?AbortSignal.any([e,t]):e}function Mr(e,t){return!t?.aborted&&e instanceof Error&&e.name==="TimeoutError"}p();import{randomBytes as Bs}from"node:crypto";import{promises as ke,openSync as js,closeSync as Vs,unlinkSync as kr,statSync as zs}from"node:fs";import{dirname as Hs}from"node:path";var _r=new Map,Ws=2e4,qs=3e4,Ys=50;function Hn(e,t={}){let n=async()=>{try{let s=await ke.readFile(e,"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 ke.mkdir(Hs(e),{recursive:!0});let l=`${e}.${process.pid}.${Bs(4).toString("hex")}.tmp`;try{await ke.writeFile(l,JSON.stringify(s,null,2),{mode:384}),a?.throwIfAborted(),await ke.rename(l,e)}catch(u){throw await ke.rm(l,{force:!0}).catch(()=>{}),u}await ke.chmod(e,384).catch(()=>{})},r=(s,a={})=>{let u=(_r.get(e)??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 _r.set(e,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:Js(`${e}.lock`,t.lockTimeoutMs??Ws),update:r}}function Js(e,t){let n=Promise.resolve();return o=>{let r=n.then(async()=>{await Xs(e,t);try{return await o()}finally{Qs(e)}});return n=r.then(()=>{},()=>{}),r}}async function Xs(e,t){let n=Date.now()+t;for(;;)try{Vs(js(e,"wx"));return}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-zs(e).mtimeMs>qs){kr(e);continue}}catch{continue}if(Date.now()>n)throw Object.assign(new Error(`Timed out acquiring credential lock at ${e}`),{code:"ETIMEDOUT"});await Zs(Ys)}}function Qs(e){try{kr(e)}catch{}}function Zs(e){return new Promise(t=>setTimeout(t,e))}p();var we=class extends Error{code="invalid_grant";constructor(t="Refresh token is no longer valid \u2014 sign in again."){super(t),this.name="InvalidGrantError"}};function Wn(e){let t=e.storageKey??"default",n=e.fetchImpl??fetch,o=e.expirySkewMs??6e4,r=e.refreshTimeoutMs??15e3,i=null,s=async()=>{let u=await e.store.get(t);if(!u)return null;try{let c=JSON.parse(u);return c.accessToken?c:null}catch{return null}},a=u=>u.expiresAt-Date.now()>o,l=u=>e.lock(async()=>{let c=await s()??u;if(c.accessToken!==u.accessToken&&a(c))return c.accessToken;if(!c.refreshToken)throw new we("No refresh token available \u2014 sign in again.");let f;try{let m=await n(e.tokenEndpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:c.refreshToken}),signal:AbortSignal.timeout(r)});if(!m.ok){let h=await m.text().catch(()=>"");throw m.status>=400&&m.status<500&&ea(h)==="invalid_grant"?(await e.store.remove(t),new we):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=_e(f,c);return await e.store.set(t,JSON.stringify(d)),d.accessToken});return{async getAccessToken(u){let c=await s();if(!c)throw new we("Not signed in.");return!u?.forceRefresh&&a(c)?c.accessToken:(i||(i=l(c).finally(()=>{i=null})),i)}}}function ea(e){try{return JSON.parse(e).error}catch{return}}p();import{createServer as ta}from"node:http";import{randomBytes as na}from"node:crypto";async function Wt(e){if(e.transport.kind==="device")return oa(e);if(e.transport.kind!=="loopback")throw new Error(`Unsupported login transport: ${e.transport.kind}`);if(e.signal?.aborted)throw new Error("Login aborted");let t=g=>e.onEvent?.(g),{codeVerifier:n,codeChallenge:o}=jn(),r=na(16).toString("hex"),i=e.timeoutMs??5*60*1e3,s=e.transport.successRedirect,a=e.transport.port;t({type:"state",status:"idle"});let l,u,c=new Promise((g,y)=>{l=g,u=y});c.catch(()=>{});let f=ta((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}ra(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"));e.signal?.addEventListener("abort",h,{once:!0}),e.signal?.aborted&&h();try{e.signal?.throwIfAborted();let g=`http://127.0.0.1:${d}/callback`,y=new URL(e.metadata.authorization_endpoint);y.searchParams.set("client_id",e.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",e.scope??"openid offline_access");let C=y.toString();t({type:"authorize_url",url:C}),t({type:"state",status:"awaiting_user"}),e.openBrowser&&await e.openBrowser(C);let S=await c;await wr(f),t({type:"state",status:"exchanging"});let E=await fetch(e.metadata.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:S,code_verifier:n,redirect_uri:g}),signal:e.signal});if(!E.ok){let b=await E.text().catch(()=>"");throw new Error(`Token exchange failed (${E.status}): ${b}`)}let M=_e(await E.json());return t({type:"state",status:"authenticated"}),M}catch(g){throw t({type:"state",status:"error"}),e.signal?.aborted?new Error("Login aborted"):g}finally{clearTimeout(m),e.signal?.removeEventListener("abort",h),await wr(f)}}async function oa(e){let t=e.metadata.device_authorization_endpoint;if(!t)throw new Error("The authorization server does not offer device sign-in");if(e.signal?.aborted)throw new Error("Login aborted");let n=o=>e.onEvent?.(o);n({type:"state",status:"idle"});try{let o=await zn(t,{clientId:e.clientId,scope:e.scope},{signal:e.signal});n({type:"user_code",userCode:o.userCode,verificationUri:o.verificationUri,verificationUriComplete:o.verificationUriComplete}),n({type:"state",status:"awaiting_user"});let r=await br(e.metadata.token_endpoint,{clientId:e.clientId,deviceCode:o.deviceCode,interval:o.interval,expiresAt:o.expiresAt},{signal:e.signal});return n({type:"state",status:"authenticated"}),r}catch(o){throw n({type:"state",status:"error"}),e.signal?.aborted?new Error("Login aborted"):o}}function wr(e){return e.listening?new Promise(t=>{e.close(()=>t()),e.closeAllConnections()}):Promise.resolve()}function ra(e,t,n){e.writeHead(302,{location:t}).end(n)}p();var ia=["www-browser"];function sa(e){let t=e.replace(/\\/g,"/").split("/").pop();return!!t&&ia.includes(t)}function xr(e={}){let n=process.env.BROWSER?.trim()?.match(/^\S+/)?.[0];if(!e.ignoreBrowserBlocklist&&process.platform!=="win32"&&n&&sa(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 aa}from"node:events";var la=50;function qt(e=la){let t=new AbortController;return aa(e,t.signal),t}function ua(e){if(e)return e instanceof AbortController?e.signal:e}function ap(e,t){let n=qt(t),o=ua(e);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 Ir(e,t){let n=qt(t?.maxListeners),o=e.find(l=>l?.aborted);if(o)return n.abort(o.reason),{signal:n.signal,cleanup:()=>{}};let r=[];for(let l of e){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=t?.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 Or(e,t){if(t?.throwIfAborted(),!t)return e();let n=()=>{},o=new Promise((i,s)=>{n=()=>s(t.reason),t.addEventListener("abort",n,{once:!0})});o.catch(()=>{});let r;try{r=await Promise.race([e(),o])}finally{t.removeEventListener("abort",n)}return t.throwIfAborted(),r}var Pr=5*6e4;async function qn(e,t){let n=performance.now()+Pr,o=qt(),r=()=>o.abort(new DOMException("Sign-in timed out","TimeoutError")),i=setTimeout(r,Pr),{signal:s,cleanup:a}=Ir([e,o.signal]),l=()=>{e?.throwIfAborted(),performance.now()>=n&&r(),o.signal.throwIfAborted(),s.throwIfAborted()},u;try{l(),u=await t({signal:s,check:l})}finally{clearTimeout(i),a()}return l(),u}var ca=Vn;async function Ur(e,t){J(e);let n=await Or(()=>ca(e,void 0,{signal:t}),t);if(Ee(e)){if(n.issuer!==He)throw new Error("Matilda sign-in is not ready at https://matilda.com. The server returned an unexpected issuer. Try again after the service migration completes.");for(let o of[n.authorization_endpoint,n.token_endpoint,n.device_authorization_endpoint]){if(o===void 0)continue;let r=new URL(o);if(r.origin!==He||r.username||r.password||r.hash)throw new Error("Matilda returned an unsafe sign-in endpoint. No credentials were sent. Contact support.")}}return n}var Ie="matilda-code",Dr="matilda-desktop",Nr="openid profile email offline_access",Jt="MATILDA_API_KEY",ha="matilda",Yn=3e5;function Oe(e){return X(e)}function Lr(){return ma(at.getGlobalMatildaDir(),"matilda-auth.json")}function Ue(){let e=Lr();return pa(ga(e),{recursive:!0}),Hn(e,{lockTimeoutMs:2e4})}function Ca(e){return e==="desktop"}function De(e){return e?.clientId?e.clientId:Ca(e?.channel)?Dr:Ie}function nt(e){return`matilda:${e}`}function Xt(e){return`${nt(e)}:refresh-rejected`}function fe(e){return e===Ie?[nt(e),ha]:[nt(e)]}function Qn(){try{let e=fa(Lr(),"utf8");return JSON.parse(e)}catch{return{}}}function Pe(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t?.accessToken=="string"&&typeof t?.baseUrl=="string"?t:null}catch{return null}}function Zn(e,t){return Oe(e)===Oe(t)}function ya(e){if(!e)return{};try{let t=e.split(".")[1],n=Buffer.from(t.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(n);return{sub:o.sub,email:o.email,name:o.name}}catch{return{}}}function Fr(e,t){if(H({baseUrl:t,accessToken:e.accessToken}))throw new G({reason:z});let n=ya(e.idToken);return{accessToken:e.accessToken,accessTokenExpiresAt:e.expiresAt,refreshToken:e.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:t}}var Jn=new Map;async function eo(e,t={}){let n=()=>{t.signal?.throwIfAborted(),t.check?.()};n(),J(e);let o=!t.signingIn&&Jn.get(e);if(o)return o;try{let r=await Ur(e,t.signal);return n(),Jn.set(e,r),r}catch(r){n();let i=t.signingIn&&(Ye(r,e)??Mn(r,e));if(i)throw i;if(Ee(e))throw r;return{issuer:e,authorization_endpoint:`${e}/api/auth/oauth/authorize`,token_endpoint:`${e}/api/auth/oauth/token`,device_authorization_endpoint:`${e}/api/auth/oauth/device/code`}}}function to(e){let t=Gr(e);return t&&!H(t)?t:null}function Gr(e){try{let t=Qn(),n=De(e);for(let o of fe(n)){let r=Pe(t[o]);if(r)return r}return null}catch{return null}}async function Yt(e,t){let n=De(e),o=Qn();if(!fe(n).some(a=>{let l=Pe(o[a]);return l&&H(l)}))return!1;let{store:r,lock:i,update:s}=Ue();return i(async()=>{let a={};for(let l of fe(n)){let u=Pe(await r.get(l));u&&H(u)&&(a[l]=null)}return await s(a,{signal:t}),Object.keys(a).length>0})}function Kr(e){let t=to(e);return!t||e?.baseUrl&&!Zn(t.baseUrl,e.baseUrl)?null:t}function no(e){return Kr(e)!==null}async function $r(e,t){for(let n of t){let o=await e.get(n);if(Pe(o))return o}return null}async function Ta(e,t){let n=De(e),o=fe(n),{store:r,lock:i,update:s}=Ue();await i(async()=>{let a=await $r(r,o);a!==null&&a!==t||await s({...Object.fromEntries(o.map(l=>[l,null])),[Xt(n)]:"1"})})}function Sa(e){return e instanceof Error?e.code==="invalid_grant"||e.name==="InvalidGrantError"?!0:e.message==="Token refresh failed (401)":!1}function xe(e){Xn({authStage:e.authStage,authOutcome:e.authOutcome,occurrenceCount:e.occurrenceCount},{baseUrl:e.baseUrl,token:e.token}).catch(()=>{})}async function Br(e,t,n={}){let o=De(t),r=nt(o),i={[r]:JSON.stringify(e),[Xt(o)]:null};for(let l of fe(o))l!==r&&(i[l]=null);let{lock:s,update:a}=Ue();await s(()=>(n.check?.(),a(i,{signal:n.signal})))}async function Ea(e,t){for(let n of fe(t))await e.remove(n);await e.remove(Xt(t))}var tt="matilda:api-key";function jr(){let e=Qn()[tt];if(!e)return null;try{let{apiKey:t,baseUrl:n}=JSON.parse(e);return typeof t=="string"&&t.length>0&&typeof n=="string"?{apiKey:t,baseUrl:n}:null}catch{return null}}function Qt(e){let t=jr();return t&&Zn(t.baseUrl,e)?t.apiKey:void 0}async function Aa(e){let t=da(),n=JSON.stringify(e?{...e,saveId:t}:{saveId:t}),{store:o,lock:r,update:i}=Ue(),s=await r(async()=>{let a=await o.get(tt);return(e||a!==null)&&await i({[tt]:n}),a});return()=>r(async()=>{await o.get(tt)===n&&await i({[tt]:s})})}function Ra(e){let t=to(e);return t?{authenticated:!0,userId:t.userId,email:t.email,displayName:t.displayName,baseUrl:t.baseUrl,accessTokenExpiresAt:t.accessTokenExpiresAt}:{authenticated:!1}}async function _p(e){let t={channel:e?.channel,clientId:e?.clientId},{store:n,lock:o}=Ue(),r=await o(async()=>{let s=to(t);return await Ea(n,De(t)),s}),i=jr()!==null;if(await Aa(null),r?.accessToken){let s=Oe(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:e?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}return!!r||i}function Vr(e){return!e||e===Jt}function zr(e){let{baseUrl:t,channel:n,apiKey:o,apiKeyEnvKey:r}=e;if(no({baseUrl:t,channel:n})){let i=Ra({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}:Vr(r)&&process.env[Jt]?{kind:"api-key",from:Jt}:Qt(t)!==void 0?{kind:"api-key",from:"saved"}:{kind:"none"}}async function Hr(e){e?.signal?.throwIfAborted();let t=De(e),n=Gr(e);if(n&&H(n)&&(await Yt(e,e?.signal),!e?.baseUrl||Mt(e.baseUrl)||Ee(e.baseUrl)))throw new G({channel:e?.channel,reason:z});e?.baseUrl&&J(e.baseUrl);let o=nt(t),r=Kr({baseUrl:e?.baseUrl,channel:e?.channel,clientId:t});if(!r){let f=e?.fallbackAccessToken||(Vr(e?.apiKeyEnvKey)?process.env[Jt]:void 0)||e?.baseUrl&&Qt(e.baseUrl)||"";if(e?.baseUrl&&H({baseUrl:e.baseUrl,accessToken:f}))throw new G({channel:e?.channel,reason:z});return f}let i=Oe(r.baseUrl),s=await eo(i,{signal:e?.signal}),{manager:a,startedFrom:l}=ba(Ue(),s.token_endpoint,r.baseUrl,t,o,e?.signal),u=t===Ie&&(!!e?.forceRefresh||r.accessTokenExpiresAt-Date.now()<=Yn),c;try{c=await a.getAccessToken({forceRefresh:e?.forceRefresh})}catch(f){e?.signal?.throwIfAborted(),u&&xe({baseUrl:r.baseUrl,token:r.accessToken,authStage:"refresh",authOutcome:"failed"});let d=f instanceof Error?f.code:void 0;if(d==="session_changed"||d==="no_session"){let m=await Yt(e,e?.signal);throw new G({cause:f,channel:e?.channel,...m?{reason:z}:{}})}if(!Sa(f)&&d!=="no_refresh_token")throw Jn.delete(i),Ye(f,i)??Mn(f,i)??f;if(f instanceof G){let m=await Yt(e,e?.signal);throw new G({cause:f,channel:e?.channel,...m?{reason:z}:{}})}throw t===Dr&&await Ta({channel:e?.channel,clientId:t},l()),new G({cause:f,channel:e?.channel})}if(e?.signal?.throwIfAborted(),H({baseUrl:r.baseUrl,accessToken:c}))throw await Yt(e,e?.signal),new G({channel:e?.channel,reason:z});return u&&xe({baseUrl:r.baseUrl,token:c,authStage:"refresh",authOutcome:"succeeded"}),c}function ba({store:e,lock:t,update:n},o,r,i,s,a){let l=fe(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=>$r(e,C===s?l:[C]),f=null,d,m=()=>d===void 0?f:d;return{manager:Wn({tokenEndpoint:o,clientId:i,store:{get:async C=>{let S=await c(C),E=Pe(S);if(E&&H(E))throw new G({reason:z});if(f=E&&Zn(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 G;let b=JSON.parse(S),_=Pe(M)??{},F={..._,accessToken:b.accessToken,accessTokenExpiresAt:b.expiresAt,refreshToken:b.refreshToken??_.refreshToken??"",baseUrl:_.baseUrl??r};if(H(F))throw new G({reason:z});await n({...Object.fromEntries(l.filter(re=>re!==s).map(re=>[re,null])),[s]:JSON.stringify(F),[Xt(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:t,fetchImpl:u,expirySkewMs:Yn,skewMs:Yn}),startedFrom:m}}function va(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&xr()}async function kp(e){let{openBrowser:t,onAuthorizeUrl:n,signal:o}=e,r=N(e.baseUrl);return qn(o,async i=>{let s=Oe(r),a=await eo(s,{signingIn:!0,...i}),l="",u=0,c=0,f={},d=y=>{f[y]=(f[y]??0)+1},h=await(y=>(u+=1,Wt({metadata:a,clientId:Ie,scope:y,transport:{kind:"loopback",successRedirect:`${s}/api/auth/oauth/success?client_id=${encodeURIComponent(Ie)}`},signal:i.signal,onEvent:C=>{i.check(),C.type==="authorize_url"&&(l=C.url,n?.(C.url)),C.type==="state"&&C.status==="exchanging"&&(c+=1),i.check()},openBrowser:async C=>{if(i.check(),t===!1||!va()){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()}})))(Nr).catch(y=>{throw i.check(),Ye(y,s)??y});i.check();let g=Fr(h,r);await Br(g,void 0,i),i.check(),xe({baseUrl:r,token:g.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:u});for(let[y,C]of Object.entries(f))xe({baseUrl:r,token:g.accessToken,authStage:"browser_opened",authOutcome:y,occurrenceCount:C});return c>0&&xe({baseUrl:r,token:g.accessToken,authStage:"callback_received",authOutcome:"succeeded",occurrenceCount:c}),xe({baseUrl:r,token:g.accessToken,authStage:"token_persisted",authOutcome:"succeeded"}),{...g,authorizeUrl:l}})}async function wp(e){let{onDeviceCode:t,signal:n}=e,o=N(e.baseUrl);return qn(n,async r=>{let i=Oe(o),s=await eo(i,{signingIn:!0,...r}),a=await Wt({metadata:s,clientId:Ie,scope:Nr,transport:{kind:"device"},signal:r.signal,onEvent:u=>{r.check(),u.type==="user_code"&&t({userCode:u.userCode,verificationUri:u.verificationUri,verificationUriComplete:u.verificationUriComplete}),r.check()}}).catch(u=>{throw r.check(),Ye(u,i)??u});r.check();let l=Fr(a,o);return await Br(l,void 0,r),l})}p();p();p();function Zt(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="object"&&"message"in e.error}function Wr(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}p();function qr(e){let t=Math.max(1,e.attempt),n=Math.min(e.maxDelayMs,2147483647),o=Math.min(t-1,31),r=Math.min(e.initialDelayMs*Math.pow(2,o),n),s=(e.retryAfterMode??"ignore")==="ignore"?null:Ma(e.error);if(s!==null&&s>0){let c=Math.min(e.retryAfterMaxDelayMs??e.maxDelayMs,2147483647),f=Math.min(s,c);return Math.max(r,f)}let a=e.jitterRatio??0;if(a<=0)return r;let l=e.random??Math.random,u=r*a*(l()*2-1);return Math.min(Math.max(0,r+u),n)}function Ma(e){let t=Yr(e,"retry-after")??_a(e,"retry-after");if(t===null)return null;let n=t.trim();if(/^\d+(\.\d+)?$/.test(n)){let i=Number(n);if(Number.isFinite(i)&&i>=0)return Math.min(i*1e3,2147483647)}let o=Date.parse(n);if(!Number.isFinite(o))return null;let r=o-Date.now();return r>0?Math.min(r,2147483647):0}function Yr(e,t){if(!ka(e))return null;let{headers:n}=e;if(typeof n.get=="function"){let r=n.get(t);return typeof r=="string"?r:null}if(typeof n!="object"||n===null)return null;let o=t.toLowerCase();for(let[r,i]of Object.entries(n))if(r.toLowerCase()===o)return typeof i=="string"?i:null;return null}function _a(e,t){return wa(e)?Yr(e.response,t):null}function ka(e){return typeof e=="object"&&e!==null&&"headers"in e&&e.headers!=null}function wa(e){return typeof e=="object"&&e!==null&&"response"in e&&typeof e.response=="object"&&e.response!==null&&"headers"in e.response&&e.response.headers!=null}var xa=new Set([429,503,1302,1305]);function oo(e,t){if(ro(e))return!1;let n=Oa(e);return n===null?!1:!!(xa.has(n)||t&&t.includes(n))}function ro(e){return Ia(e)==="insufficient_quota"}function Ia(e){let t=Xr(e)?.code;if(t!==void 0)return t;let n=typeof e=="object"&&e!==null&&"code"in e?e.code:void 0;return typeof n=="string"||typeof n=="number"?n:void 0}function Jr(e){let t=V(e),n=Xr(e),o=Qr(e),r=o?.includes("event:error")||o?.includes("HTTP_STATUS/")?"sse":t!==void 0?"http":"unknown";return{...t!==void 0?{statusCode:t}:{},...n?.code!==void 0?{providerCode:String(n.code)}:{},...n?.message!==void 0?{providerMessage:n.message}:{},...n?.requestId!==void 0?{requestId:n.requestId}:{},transport:r}}function Gp(e,t){return qr({attempt:e,initialDelayMs:t.initialDelayMs,maxDelayMs:t.maxDelayMs,retryAfterMode:"minimum",retryAfterMaxDelayMs:t.maxDelayMs,error:t.error})}function Oa(e){if(Zt(e)){let n=Number(e.error.code);if(Number.isFinite(n)&&n>0)return n}let t=e instanceof Error?e.message:typeof e=="string"?e:null;if(t){let n=t.indexOf("{");if(n!==-1)try{let o=JSON.parse(t.substring(n));if(Zt(o)){let r=Number(o.error.code);if(Number.isFinite(r)&&r>0)return r}}catch{}}if(Wr(e)&&typeof e.status=="number")return e.status;if(e instanceof Error&&"status"in e){let n=e.status;if(typeof n=="number")return n}return V(e)??null}function Xr(e){for(let t of Pa(e)){if(typeof t!="object"||t===null)continue;let n=t,o=t.error,i=(typeof o=="object"&&o!==null?o:void 0)??n,s=typeof i.code=="string"||typeof i.code=="number"?i.code:void 0,a=typeof i.message=="string"?i.message:void 0,l=typeof i.request_id=="string"?i.request_id:typeof i.requestId=="string"?i.requestId:typeof n.request_id=="string"?n.request_id:typeof n.requestId=="string"?n.requestId:void 0;if(s!==void 0||a!==void 0||l!==void 0)return{code:s,message:a,requestId:l}}return Zt(e)?{code:e.error.code,message:e.error.message}:null}function Pa(e){let t=Qr(e);if(!t)return[];let n=[];for(let i of t.split(/\r?\n/)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(!s||s==="[DONE]"))try{n.push(JSON.parse(s))}catch{}}if(n.length>0)return n;let o=t.indexOf("{"),r=t.lastIndexOf("}");if(o!==-1&&r>o)try{n.push(JSON.parse(t.slice(o,r+1)))}catch{}return n}function Qr(e){return e instanceof Error?e.message:typeof e=="string"?e:null}function Ua(e,t={}){if(Da(e))return{kind:"abort",diagnosis:"fail-fast",reason:"aborted"};let n=Jr(e),o=n.statusCode,r=$a(e),i=n.providerCode??r.providerCode,s=n.providerMessage??r.providerMessage,a=n.requestId??r.requestId,l={...o!==void 0?{statusCode:o}:{},...i!==void 0?{providerCode:i}:{},...s!==void 0?{providerMessage:s}:{},...a!==void 0?{requestId:a}:{}};if(Ka(i))return{kind:"provider-business",diagnosis:"fail-fast",reason:"allocated-quota-exceeded",...l};if(ro(e))return{kind:"provider-business",diagnosis:"fail-fast",reason:"insufficient-quota",...l};if(oo(e,t.extraRetryErrorCodes))return{kind:n.transport==="sse"?"sse-provider":o!==void 0?"http":"provider",diagnosis:"retryable",reason:"rate-limit",...l};let u=La(e);if(u!==void 0&&(o===void 0||o>=500))return{kind:"transport",diagnosis:"retryable",reason:"transport-error",transportCode:u,...o!==void 0?{statusCode:o}:{}};if(o!==void 0){let 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 Vp(e){let t=e.statusCode??Number(e.providerCode);return e.kind!=="transport"&&e.diagnosis!=="fail-fast"&&(t>=500&&t<600||e.kind==="sse-provider"&&e.reason==="server-error"&&e.diagnosis==="retryable")}function Zr(e,t){return oo(e,t)||Ua(e,{extraRetryErrorCodes:t}).diagnosis==="retryable"}function Da(e){return co(e)?!0:e instanceof Error&&e.name==="CanceledError"}var Na=5;function La(e){let t=e;for(let n=0;n<=Na;n++){if(typeof t!="object"||t===null)return;let o=t.code;if(typeof o=="string"&&Fa(o))return o;t=t instanceof Error?t.cause:void 0}}function Fa(e){return Ga.has(e)}var Ga=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 Ka(e){return e==="Throttling.AllocationQuota"}function $a(e){if(typeof e!="object"||e===null)return{};let t=e,n=typeof t.code=="string"||typeof t.code=="number"?String(t.code):void 0,o=typeof t.code=="number"&&t.code>=100&&t.code<600,r=e instanceof Error&&n?.startsWith("ERR_")||o?void 0:n,i=typeof t.request_id=="string"?t.request_id:typeof t.requestId=="string"?t.requestId:void 0,s=typeof t.message=="string"&&(!(e instanceof Error)||r!==void 0||i!==void 0)?t.message:void 0;return{...r!==void 0?{providerCode:r}:{},...s!==void 0?{providerMessage:s}:{},...i!==void 0?{requestId:i}:{}}}var Re=(t=>(t.USE_OPENAI="openai",t))(Re||{});function ei(e,t){if(delete e.usesMatildaSignIn,delete e.usesMatildaSavedApiKey,!vn(e))return;let n=e.baseUrl||B();no({baseUrl:n,channel:t})&&(e.usesMatildaSignIn=!0),!e.apiKey&&Qt(n)!==void 0&&(e.usesMatildaSavedApiKey=!0)}function tf(e,t={}){let n=e.apiKey?{value:e.apiKey,from:t.apiKeyFrom??"config"}:void 0;return vn(e)?zr({baseUrl:e.baseUrl||B(),channel:t.channel,apiKey:n,apiKeyEnvKey:e.apiKeyEnvKey}):n&&{kind:"api-key",from:n.from}}async function Ba(e,t){try{await Hr({baseUrl:e.baseUrl||B(),channel:t})}catch(n){if(!Zr(n))throw n}}function io(e,t,n){e[t]=n}function ja(e,t){return e?.[t]}function nf(e,t,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:t,proxy:e?.getProxy()};io(i,"authType",{kind:"computed",detail:"provided by caller"}),e?.getProxy()&&io(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=c=>ja(o,c)??{kind:"unknown"};for(let c of Gn)n&&c in n&&!i[c]&&io(i,c,l(c));ei(a,e.getChannel());let u=Kn(a,s);if(!u.valid)throw new Error(u.errors.map(c=>c.message).join(`
17
- `));return{config:a,sources:i}}function Kn(e,t=!1){let n=[];if(!e.apiKey&&!e.usesMatildaSignIn&&!e.usesMatildaSavedApiKey)if(t)n.push(new Ut(e.authType,e.model,e.apiKeyEnvKey));else{let o=e.apiKeyEnvKey||cr(e.authType);n.push(new Nt({authType:e.authType,model:e.model,baseUrl:e.baseUrl,envKey:o}))}if(!e.model)if(t)n.push(new Dt(e.authType));else{let o=dr(e.authType);n.push(new Lt({authType:e.authType,envKey:o}))}return{valid:n.length===0,errors:n}}function Va(e){let t=e;for(;t instanceof Error;){if("code"in t&&t.code==="ERR_MODULE_NOT_FOUND")return t;t=t.cause}}async function of(e,t,n){t.assertServer?.(e.baseUrl,n,t.getContentGeneratorConfig?.()?.baseUrl),Nn(e,t.getOrganizationId?.(),t.getCodeCreditLimitMinor?.()),ur(e.customHeaders),ei(e,t.getChannel()),e.usesMatildaSignIn&&await Ba(e,t.getChannel());let o=Kn(e,!1);if(!o.valid)throw new Error(o.errors.map(s=>s.message).join(`
18
- `));fo(e.apiKey);let r=e.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-PBSIX6IL.js");await s(e,t,n),i=a(e,t)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=Va(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 Qe(i,t,e)}var za=["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"],Ha=new Set([...za,...uo]),Wa=new Set(["VSCode","ACP","SDK","CI"]),Ne="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",qa="[A-Za-z][0-9A-Za-z-]{0,23}",ti="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",Ya=new RegExp(`^${Ne}(?:-${qa}(?:\\.${ti})+)?$`),Ja=63,Xa=new RegExp(`^${Ne}$`),Qa=new RegExp(`^${Ne}-preview\\.(?:0|[1-9]\\d{0,11})$`),Za=new RegExp(`^${Ne}-canary\\.(?:0|[1-9]\\d{0,11})$`),el=new RegExp(`^${Ne}-nightly\\.(?:0|[1-9]\\d{0,11})\\.[0-9A-Fa-f]{7,12}$`),tl=new RegExp(`^${Ne}-(preview|canary|nightly|development|internal)(?:\\.${ti})+$`);function nl(e){return e==="desktop"?"desktop":e===void 0||Wa.has(e)?"code_cli":"unknown"}function ol(e){if(e==="android")return"android";if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux")return"linux"}function rl(e){if(e==="x64")return"x64";if(e==="arm64")return"arm64"}function il(e){if(e===void 0)return"npm";if(e==="desktop")return"direct-download";if(e==="VSCode")return"vscode-marketplace"}function sl(e,t){if(t==="desktop")return"matilda-desktop";if(e==="VSCode")return"matilda-vscode";if(t==="code_cli")return"matilda-code"}function al(e){if(typeof e=="string"&&!(e.length>Ja||!Ya.test(e)))return e}function ll(e){if(e!==void 0)return Xa.test(e)?"stable":Qa.test(e)?"preview":Za.test(e)?"canary":el.test(e)?"nightly":tl.exec(e)?.[1]}function ni(e,t=process.platform,n=process.arch){let o=e.getChannel?.(),r=nl(o),i=al(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:e.getCliVersion?.()),s=ll(i),a=ol(t),l=rl(n),u=il(o),c=sl(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 df(e){let t=e.toLowerCase();return Ha.has(t)||t.startsWith("x-matilda-reported-")}function ul(e){let t=e??B();try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let o=n.hostname.toLowerCase();return he(o)||o==="core-api.matilda"||qe(t)}catch{return!1}}function pf(e,t=e.apiKey){return e.authType==="openai"&&(!!t||e.usesMatildaSignIn===!0||e.usesMatildaSavedApiKey===!0)&&ul(e.baseUrl)}var cl=3e3,ot=1,dl=24*60*60*1e3,oi=20,ri=999,pl=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"]),fl=new Set(["ENOTFOUND","EAI_AGAIN"]),gl=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),ml=new Set(["ABORT_ERR","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT"]),hl=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]);function Cl(e){return`${new URL(N(e)).origin}/api/client-events`}function yl(e){let t={eventType:e.eventType,platform:"cli"};return e.eventType==="network_error"&&(t.transportReason=e.transportReason,t.transportStage=e.transportStage,t.responseReceived=e.responseReceived,t.occurrenceCount=e.occurrenceCount),e.eventType==="auth_funnel"&&(t.authStage=e.authStage,t.authOutcome=e.authOutcome,t.occurrenceCount=e.occurrenceCount),e.eventType==="network_error"&&(t.reportedSurface=e.reportedSurface,t.reportedOs=e.reportedOs,t.reportedArchitecture=e.reportedArchitecture,t.reportedProcess=e.reportedProcess,t.reportedReleaseChannel=e.reportedReleaseChannel,e.reportedVersion&&(t.reportedVersion=e.reportedVersion)),t}async function so(e,t){let{baseUrl:n,token:o}=t;if(!n||!o)return!1;let r=t.fetchImpl??fetch,i=new AbortController,s=setTimeout(()=>i.abort(),t.timeoutMs??cl);try{let a=await r(Cl(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(yl(e)),signal:i.signal});return a.ok?!0:(lt.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`),!1)}catch{return!1}finally{clearTimeout(s)}}async function Xn(e,t){let n=typeof e.occurrenceCount=="number"&&Number.isFinite(e.occurrenceCount)?Math.max(1,Math.min(Math.floor(e.occurrenceCount),ri)):1;return so({eventType:"auth_funnel",authStage:e.authStage,authOutcome:e.authOutcome,occurrenceCount:n},t)}function ii(){try{let e=oe.readFileSync(li(),"utf8"),t=JSON.parse(e);return t.schemaVersion!==ot||!Array.isArray(t.failures)?void 0:{schemaVersion:ot,failures:t.failures.filter(Tl)}}catch{return}}function Tl(e){if(!e||typeof e!="object")return!1;let t=e;return t.eventType==="network_error"&&typeof t.transportReason=="string"&&typeof t.transportStage=="string"&&typeof t.responseReceived=="boolean"&&typeof t.occurrenceCount=="number"&&typeof t.reportedSurface=="string"&&typeof t.reportedOs=="string"&&typeof t.reportedArchitecture=="string"&&typeof t.reportedProcess=="string"&&typeof t.reportedReleaseChannel=="string"&&typeof t.firstObservedAtMs=="number"&&typeof t.lastObservedAtMs=="number"}function si(e){let t=li();if(e.failures.length===0){try{oe.rmSync(t,{force:!0})}catch{}return}try{oe.mkdirSync(en.dirname(t),{recursive:!0}),oe.writeFileSync(t,`${JSON.stringify(e)}
20
- `,"utf8")}catch{}}function ai(e,t){return e.filter(n=>t-n.lastObservedAtMs<=dl).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-oi)}function Sl(e){let t=ni(e);return{reportedSurface:t["x-matilda-client-name"]==="matilda-desktop"?"desktop":t["x-matilda-client-name"]==="matilda-code"||t["x-matilda-client-name"]==="matilda-vscode"?"code_cli":"unknown",reportedOs:t["x-matilda-client-operating-system"]??"unknown",reportedArchitecture:t["x-matilda-client-architecture"]??"unknown",reportedProcess:t["x-matilda-client-name"]??"unknown",reportedVersion:t["x-matilda-client-version"],reportedReleaseChannel:t["x-matilda-client-release-channel"]??"unknown"}}function El(e){if(!e||typeof e!="object")return;let t=e.code;if(typeof t=="string")return t;if(!(e instanceof Error)||!e.cause||typeof e.cause!="object")return;let n=e.cause.code;return typeof n=="string"?n:void 0}function Al(e){if(!(!e||typeof e!="object"))for(let t of["status","statusCode"]){let n=e[t];if(typeof n=="number")return n}}function Rl(e,t){let n=El(e);if(n&&pl.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&fl.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&gl.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&ml.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&hl.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=Al(e),r=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();if(r.includes("self signed")||r.includes("certificate")||r.includes("tls"))return{reason:"tls",stage:"tls",responseReceived:!1};if(o===407||n==="proxy_auth_required")return{reason:"proxy",stage:"connect",responseReceived:!0};if(t&&r.includes("proxy")&&(r.includes("407")||r.includes("connect")||r.includes("fetch failed")))return{reason:"proxy",stage:"connect",responseReceived:!1};if(r.includes("timed out")||r.includes("timeout")||r.includes("deadline exceeded"))return{reason:"timeout",stage:"request",responseReceived:!1};if(r.includes("fetch failed"))return{reason:"unknown",stage:"unknown",responseReceived:!1}}function bl(e,t){return e.findIndex(n=>n.transportReason===t.transportReason&&n.transportStage===t.transportStage&&n.responseReceived===t.responseReceived&&n.reportedSurface===t.reportedSurface&&n.reportedOs===t.reportedOs&&n.reportedArchitecture===t.reportedArchitecture&&n.reportedProcess===t.reportedProcess&&n.reportedVersion===t.reportedVersion&&n.reportedReleaseChannel===t.reportedReleaseChannel)}function Tf(e,t){let n=Sl(t.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=Rl(e,t.proxyConfigured);if(!o)return!1;let r=Date.now(),i={eventType:"network_error",transportReason:o.reason,transportStage:o.stage,responseReceived:o.responseReceived,occurrenceCount:1,...n,firstObservedAtMs:r,lastObservedAtMs:r},s=ii()??{schemaVersion:ot,failures:[]},a=ai(s.failures,r),l=bl(a,i);if(l>=0){let u=a[l];a[l]={...u,occurrenceCount:Math.min(u.occurrenceCount+1,ri),lastObservedAtMs:r}}else a.push(i);return si({schemaVersion:ot,failures:a.slice(-oi)}),!0}async function Sf(e){let t=ii();if(!t)return;let n=ai(t.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await so({eventType:i.eventType,transportReason:i.transportReason,transportStage:i.transportStage,responseReceived:i.responseReceived,occurrenceCount:i.occurrenceCount,reportedSurface:i.reportedSurface,reportedOs:i.reportedOs,reportedArchitecture:i.reportedArchitecture,reportedProcess:i.reportedProcess,reportedVersion:i.reportedVersion,reportedReleaseChannel:i.reportedReleaseChannel},e)){o.push(...n.slice(r));break}}si({schemaVersion:ot,failures:o})}function li(){return en.join(at.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var ym="http://localhost:4317";export{J as a,H as b,sa as c,xr as d,mi as e,An as f,Rt as g,Ai as h,Ri as i,vt as j,Zo as k,us as l,Pn as m,ns as n,lu as o,$o as p,du as q,Hi as r,pu as s,fu as t,We as u,X as v,Eu as w,Au as x,Ru as y,Wo as z,qo as A,qe as B,vn as C,Ye as D,es as E,B as F,ni as G,df as H,pf as I,Xn as J,Tf as K,Sf as L,ym as M,Pc as N,Dn as O,Ms as P,Nn as Q,ur as R,Uc as S,Gc as T,Kc as U,Gt as V,et as W,Cr as X,rd as Y,ld as Z,Er as _,qt as $,ap as aa,Ir as ba,Or as ca,Oe as da,to as ea,no as fa,jr as ga,Qt as ha,Aa as ia,Ra as ja,_p as ka,Hr as la,va as ma,kp as na,wp as oa,Zt as pa,Wr as qa,qr as ra,Ma as sa,oo as ta,ro as ua,Ia as va,Jr as wa,Gp as xa,Ua as ya,Vp as za,Zr as Aa,Re as Ba,tf as Ca,nf as Da,of as Ea};
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
- /** @license Copyright 2026 Maincode SPDX-License-Identifier: Apache-2.0 */
37
- /**
38
- * @license
39
- * Copyright 2026 Google LLC
40
- * SPDX-License-Identifier: Apache-2.0
41
- */
42
- /**
43
- * @license
44
- * Copyright 2026 Matilda
45
- * SPDX-License-Identifier: Apache-2.0
46
- */
47
- /**
48
- * @license
49
- * Copyright 2025 Matilda Team
50
- * SPDX-License-Identifier: Apache-2.0
51
- */
52
- /**
53
- * @license
54
- * Copyright 2026 Maincode
55
- * SPDX-License-Identifier: Apache-2.0
56
- *
57
- * Low-level OAuth primitives for core-auth's unified `/api/auth/oauth/*` flow
58
- * (ADR-029): PKCE pair generation, RFC 8414 discovery, the RFC 8628 device
59
- * grant, and refresh. Vendored (as source) from matilda-core's
60
- * `packages/client-sdk/src/auth.ts` and extended to carry the `id_token`
61
- * (display identity) that the higher-level flows need. Node built-ins only —
62
- * no third-party runtime dependencies.
63
- */
64
- /**
65
- * @license
66
- * Copyright 2026 Maincode
67
- * SPDX-License-Identifier: Apache-2.0
68
- *
69
- * File-backed token store + cross-process lock. The store persists a JSON map
70
- * (`{ [key]: value }`) at 0600 so callers can key several credentials in one
71
- * file; the lock is an O_EXCL lockfile that serialises refreshes across
72
- * processes (the guarantee a plaintext read/modify/write can't give).
73
- */
74
- /**
75
- * @license
76
- * Copyright 2026 Maincode
77
- * SPDX-License-Identifier: Apache-2.0
78
- *
79
- * Hardened access-token manager: returns a valid access token, refreshing via
80
- * core-auth's token endpoint when expired or forced. Single-flight within the
81
- * process, serialised across processes by the store's lock, carries a prior
82
- * refresh token forward when the response omits one, and evicts on a terminal
83
- * `invalid_grant` so a dead session doesn't wedge the caller in a refresh loop.
84
- */
85
- /**
86
- * @license
87
- * Copyright 2026 Maincode
88
- * SPDX-License-Identifier: Apache-2.0
89
- *
90
- * Browser login orchestration: PKCE + a loopback capture server, driven off
91
- * discovery metadata. Unlike a bare loopback helper, this emits lifecycle
92
- * events for a UI, honours an AbortSignal, and — instead of serving its own
93
- * HTML — 302-redirects the browser to an app-owned branded landing
94
- * (`successRedirect`). Returns a TokenSet including the `id_token`.
95
- */
96
- /**
97
- * @license
98
- * Copyright 2026 Maincode
99
- * SPDX-License-Identifier: Apache-2.0
100
- *
101
- * Node auth surface for `@maincode-ai/matilda-client-sdk/auth/node`.
102
- * Re-exports the OAuth primitives plus the higher-level login flow, file token
103
- * store, and hardened token manager that the CLI (`packages/core`) and the
104
- * Electron desktop app consume.
105
- */
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
- */
@@ -1,8 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{l as i}from"./chunk-SHISTILE.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
- /**
5
- * @license
6
- * Copyright 2025 Matilda Team
7
- * SPDX-License-Identifier: Apache-2.0
8
- */