@maincode-ai/matilda-code 0.21.12 → 0.21.13-nightly.20261026.e0eae1d8c

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 (194) hide show
  1. package/bundled/mainy/SKILL.md +0 -2
  2. package/bundled/mainy/docs/_meta.ts +0 -2
  3. package/bundled/mainy/docs/configuration/auth.md +5 -10
  4. package/bundled/mainy/docs/configuration/model-providers.md +31 -217
  5. package/bundled/mainy/docs/configuration/settings.md +32 -4
  6. package/bundled/mainy/docs/features/auto-mode.md +1 -1
  7. package/bundled/mainy/docs/features/channels/_meta.ts +0 -3
  8. package/bundled/mainy/docs/features/channels/overview.md +8 -16
  9. package/bundled/mainy/docs/features/commands.md +4 -4
  10. package/bundled/mainy/docs/features/hooks.md +9 -7
  11. package/bundled/mainy/docs/features/language.md +2 -29
  12. package/bundled/mainy/docs/features/sub-agents.md +1 -1
  13. package/bundled/mainy/docs/features/worktree.md +3 -5
  14. package/bundled/mainy/docs/integration-github-action.md +3 -3
  15. package/bundled/mainy/docs/matilda-serve.md +1 -1
  16. package/bundled/mainy/docs/quickstart.md +2 -2
  17. package/bundled/mainy/docs/support/troubleshooting.md +3 -10
  18. package/chunks/agent-4FTU3WN6.js +3 -0
  19. package/chunks/agent-headless-QJUVHPFC.js +3 -0
  20. package/chunks/{askUserQuestion-2QI4NSFJ.js → askUserQuestion-QKX4NEFX.js} +1 -1
  21. package/chunks/{ca-I2HEEIL7.js → ca-C2V7I65K.js} +6 -6
  22. package/chunks/{chunk-6E766NPX.js → chunk-2ONZZ46N.js} +2 -2
  23. package/chunks/chunk-36K4HBVM.js +7 -0
  24. package/chunks/{chunk-EQGA7LH7.js → chunk-3B2HABK7.js} +1 -1
  25. package/chunks/{chunk-MCQUPLRE.js → chunk-5NMK4Y7C.js} +1 -1
  26. package/chunks/chunk-5YT4GCK7.js +14 -0
  27. package/chunks/{chunk-27Q5KW3A.js → chunk-62AFAL4I.js} +10 -10
  28. package/chunks/chunk-75KP2FVD.js +81 -0
  29. package/chunks/chunk-7ZODGQO6.js +4 -0
  30. package/chunks/chunk-BZB7HYRC.js +37 -0
  31. package/chunks/{chunk-YRQP3SLC.js → chunk-EXNHJQCD.js} +1 -1
  32. package/chunks/chunk-FCGYRGV4.js +9 -0
  33. package/chunks/chunk-G4YMVWG4.js +8 -0
  34. package/chunks/{chunk-6T2GIM76.js → chunk-HDARIAVM.js} +1 -1
  35. package/chunks/{chunk-YJAKOETP.js → chunk-HM5LCKDB.js} +2 -2
  36. package/chunks/chunk-IIQ5YERM.js +120 -0
  37. package/chunks/{chunk-CSJTA7NE.js → chunk-JGJ7BVZN.js} +18 -18
  38. package/chunks/{chunk-GTVCJCHR.js → chunk-JIKQI4MZ.js} +1 -1
  39. package/chunks/{chunk-WV3IUPZS.js → chunk-LHDCAN7Z.js} +1 -1
  40. package/chunks/chunk-LZDHANXA.js +89 -0
  41. package/chunks/{chunk-PGXQZVLX.js → chunk-NOE4UNQN.js} +1 -1
  42. package/chunks/chunk-OEZS5R3S.js +207 -0
  43. package/chunks/{chunk-OOEH6ZSV.js → chunk-PTMCLADZ.js} +1 -1
  44. package/chunks/{chunk-2HTPVSGT.js → chunk-PYZNGIIR.js} +1 -1
  45. package/chunks/chunk-QJJTUDDA.js +56 -0
  46. package/chunks/{chunk-LUNDTQ3G.js → chunk-R34HYLL4.js} +1 -1
  47. package/chunks/{chunk-QVCGLQCI.js → chunk-RK4LPGBV.js} +3 -3
  48. package/chunks/{chunk-DE3HKC2W.js → chunk-RYHMPK5G.js} +1 -1
  49. package/chunks/chunk-SR7ARGUY.js +13 -0
  50. package/chunks/{chunk-JRECUFB3.js → chunk-SY6JRCN3.js} +636 -654
  51. package/chunks/chunk-TUKNB5CQ.js +33 -0
  52. package/chunks/{chunk-VTGICC67.js → chunk-TZ4FRU6B.js} +1 -1
  53. package/chunks/chunk-U7V7APDV.js +9 -0
  54. package/chunks/{chunk-CZGZ3KK7.js → chunk-UVWZ44ZW.js} +1 -1
  55. package/chunks/{chunk-HYVP4472.js → chunk-V6UPUMP3.js} +1 -1
  56. package/chunks/{chunk-DOOFGSRV.js → chunk-VLDZBRTL.js} +1 -1
  57. package/chunks/{computer-use-WKDNUTLD.js → computer-use-OXAMR75N.js} +1 -1
  58. package/chunks/contextCommand-ERLW5VWL.js +3 -0
  59. package/chunks/{cron-create-F2LXM2OA.js → cron-create-AUDQ6STP.js} +1 -1
  60. package/chunks/{cron-delete-DE6Q2S2L.js → cron-delete-P5HE3PDD.js} +1 -1
  61. package/chunks/{cron-list-IAQEJVV7.js → cron-list-NR5FZBK2.js} +1 -1
  62. package/chunks/{de-AQXFJYZI.js → de-KOUI2CEW.js} +5 -5
  63. package/chunks/{devtools-5JRKK3E7.js → devtools-G5DWLP2N.js} +1 -1
  64. package/chunks/dist-XXTQNTKQ.js +42 -0
  65. package/chunks/dist-ZFZZLIQU.js +3 -0
  66. package/chunks/{edit-QQNJZ55P.js → edit-REFR5ROS.js} +1 -1
  67. package/chunks/{en-EJLDYIBM.js → en-RMYRLXC2.js} +4 -4
  68. package/chunks/{enter-worktree-5X5SAMBJ.js → enter-worktree-WO3DT2G7.js} +1 -1
  69. package/chunks/{enterPlanMode-HP35SPLN.js → enterPlanMode-PLRHEU5A.js} +1 -1
  70. package/chunks/{exit-worktree-SRKZBEYF.js → exit-worktree-J5PW6DCV.js} +1 -1
  71. package/chunks/{exitPlanMode-WSPTGGVN.js → exitPlanMode-KXUPNLCJ.js} +2 -2
  72. package/chunks/{fr-6TDHK7F2.js → fr-R3QF3LA2.js} +5 -5
  73. package/chunks/glob-ZVTVRDQO.js +22 -0
  74. package/chunks/{goal-tools-C6BSBHCF.js → goal-tools-XVKQJL5I.js} +1 -1
  75. package/chunks/{grep-MVCOBUYW.js → grep-R7CWUNNE.js} +1 -1
  76. package/chunks/{ja-GGNJR7AR.js → ja-A5OQLXUZ.js} +5 -5
  77. package/chunks/{keychain-token-storage-KQK6MNOJ.js → keychain-token-storage-IM4UB4P4.js} +1 -1
  78. package/chunks/{ls-JYJXFSXN.js → ls-DEAFYDVV.js} +1 -1
  79. package/chunks/{lsp-DYDK6XCS.js → lsp-DL7W47VY.js} +1 -1
  80. package/chunks/matildaAgentContentGenerator-57EIU5XE.js +8 -0
  81. package/chunks/mcp-client-X7LEGSP3.js +3 -0
  82. package/chunks/monitor-KPWTMH3V.js +32 -0
  83. package/chunks/{multipart-parser-JI75T2O5.js → multipart-parser-FKHYAVGR.js} +1 -1
  84. package/chunks/notebook-edit-3ZH5M2TC.js +17 -0
  85. package/chunks/openaiContentGenerator-6PXSD3T7.js +37 -0
  86. package/chunks/{pt-D6L2QTDM.js → pt-RG3S3KA7.js} +5 -5
  87. package/chunks/read-file-JNS7WRUP.js +3 -0
  88. package/chunks/ripGrep-ICJDGIIV.js +3 -0
  89. package/chunks/{ru-BNJCHDYO.js → ru-5S5HLRT7.js} +5 -5
  90. package/chunks/scheduler-QC2PPMFP.js +8 -0
  91. package/chunks/{send-message-P3SMWNEE.js → send-message-V2WYLN5X.js} +1 -1
  92. package/chunks/{serve-FXH6EBQ6.js → serve-NUVQULZJ.js} +59 -48
  93. package/chunks/shell-5LNI7URE.js +3 -0
  94. package/chunks/{skill-HZPFEAPF.js → skill-QFATRHQW.js} +1 -1
  95. package/chunks/src-6UPZ7TVB.js +3 -0
  96. package/chunks/src-LZEU4AYF.js +5 -0
  97. package/chunks/{symbol-search-EAIZPWN7.js → symbol-search-WL6ZHUUN.js} +1 -1
  98. package/chunks/{syntheticOutput-432LXITX.js → syntheticOutput-3KW6SQAF.js} +1 -1
  99. package/chunks/task-create-PNW5SN27.js +3 -0
  100. package/chunks/{task-detach-XMSJ3HBM.js → task-detach-B7PDPFBA.js} +1 -1
  101. package/chunks/task-list-GGZATGK5.js +9 -0
  102. package/chunks/{task-stop-NTS62FLG.js → task-stop-UKBBE2KG.js} +1 -1
  103. package/chunks/{task-update-AR26UFYZ.js → task-update-4RHVUBUV.js} +1 -1
  104. package/chunks/{team-create-PYXFVIR5.js → team-create-2TJC3X57.js} +1 -1
  105. package/chunks/team-delete-4UJ7SU65.js +8 -0
  106. package/chunks/todoWrite-NEBVKOSG.js +3 -0
  107. package/chunks/{tool-search-RKZDSRYS.js → tool-search-R5GS64YR.js} +1 -1
  108. package/chunks/{web-fetch-VW3SVDQ6.js → web-fetch-H3XJMAEF.js} +17 -17
  109. package/chunks/{web-search-XQUIZARL.js → web-search-Q6RWPEIB.js} +1 -1
  110. package/chunks/{workflow-YXNXDRWZ.js → workflow-3A7KN3E3.js} +2 -2
  111. package/chunks/write-file-O7Q6SKZC.js +15 -0
  112. package/cli.js +502 -498
  113. package/locales/ca.js +1 -28
  114. package/locales/de.js +1 -28
  115. package/locales/en.js +1 -30
  116. package/locales/fr.js +1 -30
  117. package/locales/ja.js +1 -28
  118. package/locales/pt.js +1 -28
  119. package/locales/ru.js +1 -28
  120. package/package.json +2 -2
  121. package/sandbox-macos-permissive-closed.sb +0 -1
  122. package/sandbox-macos-permissive-open.sb +0 -1
  123. package/sandbox-macos-permissive-proxied.sb +0 -1
  124. package/sandbox-macos-restrictive-closed.sb +0 -1
  125. package/sandbox-macos-restrictive-open.sb +0 -1
  126. package/sandbox-macos-restrictive-proxied.sb +0 -1
  127. package/bundled/mainy/docs/features/channels/dingtalk.md +0 -134
  128. package/bundled/mainy/docs/features/channels/feishu.md +0 -186
  129. package/bundled/mainy/docs/features/channels/weixin.md +0 -106
  130. package/bundled/mainy/docs/integration-jetbrains.md +0 -81
  131. package/bundled/mainy/docs/integration-zed.md +0 -72
  132. package/chunks/agent-WM63A6NK.js +0 -3
  133. package/chunks/agent-headless-QIUBDKPW.js +0 -3
  134. package/chunks/anthropicContentGenerator-VKFTAIU3.js +0 -39
  135. package/chunks/chunk-2MOGYHWM.js +0 -8
  136. package/chunks/chunk-3IRGBRSP.js +0 -113
  137. package/chunks/chunk-3YLXGE6T.js +0 -8
  138. package/chunks/chunk-4F4DA5UI.js +0 -8
  139. package/chunks/chunk-4J6DC24J.js +0 -59
  140. package/chunks/chunk-4Q2SNBUH.js +0 -18
  141. package/chunks/chunk-5C2RJ5RR.js +0 -37
  142. package/chunks/chunk-6EQMZNIY.js +0 -8
  143. package/chunks/chunk-6GBNB5Z2.js +0 -3
  144. package/chunks/chunk-6Z2MV7ZY.js +0 -186
  145. package/chunks/chunk-BVOCFLC4.js +0 -56
  146. package/chunks/chunk-FPO57O66.js +0 -39
  147. package/chunks/chunk-G7R2XEEF.js +0 -7
  148. package/chunks/chunk-GOJCMVJJ.js +0 -8
  149. package/chunks/chunk-JCE3JAVC.js +0 -25
  150. package/chunks/chunk-KHHJYBR5.js +0 -9
  151. package/chunks/chunk-LJR4RZZ2.js +0 -3
  152. package/chunks/chunk-MO2HXJG5.js +0 -9
  153. package/chunks/chunk-O44XK65C.js +0 -8
  154. package/chunks/chunk-OA56BXPD.js +0 -3
  155. package/chunks/chunk-PA6532AY.js +0 -6
  156. package/chunks/chunk-QN6Y6NPA.js +0 -3
  157. package/chunks/chunk-S3CWEVTS.js +0 -15
  158. package/chunks/chunk-SDTWBD62.js +0 -8
  159. package/chunks/chunk-U347OO7S.js +0 -9
  160. package/chunks/chunk-UIRBHC5X.js +0 -3
  161. package/chunks/chunk-VI74YQQO.js +0 -8
  162. package/chunks/chunk-VYZOOSMP.js +0 -30
  163. package/chunks/chunk-WC2VTVCE.js +0 -27
  164. package/chunks/chunk-WVY2P6WH.js +0 -26
  165. package/chunks/chunk-WZ75OGYY.js +0 -14
  166. package/chunks/chunk-XMZIY7XX.js +0 -13
  167. package/chunks/chunk-YV3PUOBU.js +0 -65
  168. package/chunks/contextCommand-DAB3HOHY.js +0 -3
  169. package/chunks/dist-7UYRLSLE.js +0 -3
  170. package/chunks/dist-ME6647DQ.js +0 -195
  171. package/chunks/dist-P6SLWL5V.js +0 -42
  172. package/chunks/dist-VG3ZDJ2A.js +0 -28
  173. package/chunks/dist-YTCHM57U.js +0 -23
  174. package/chunks/fileFromPath-7UCWPD4W.js +0 -3
  175. package/chunks/geminiContentGenerator-RJ73DQAP.js +0 -8
  176. package/chunks/glob-QQ6LGKDX.js +0 -22
  177. package/chunks/matildaAgentContentGenerator-YUYS4336.js +0 -8
  178. package/chunks/matildaContentGenerator-O4Z2QPCP.js +0 -8
  179. package/chunks/matildaOAuth2-7COTQQR2.js +0 -3
  180. package/chunks/mcp-client-RXVQU5VI.js +0 -3
  181. package/chunks/monitor-77KXDXPR.js +0 -32
  182. package/chunks/notebook-edit-TKJD2EQZ.js +0 -17
  183. package/chunks/openaiContentGenerator-2EALAM3U.js +0 -3
  184. package/chunks/read-file-3KUAH6ND.js +0 -3
  185. package/chunks/ripGrep-U2PLKXMY.js +0 -3
  186. package/chunks/scheduler-J7VU2V5Y.js +0 -8
  187. package/chunks/shell-PXR2AXDD.js +0 -3
  188. package/chunks/src-RFAEPLY7.js +0 -3
  189. package/chunks/src-WZTRMETQ.js +0 -5
  190. package/chunks/task-create-Z3QRCMX4.js +0 -3
  191. package/chunks/task-list-GXAJW3JP.js +0 -9
  192. package/chunks/team-delete-OMYVUAQU.js +0 -8
  193. package/chunks/todoWrite-5NZ7CHTC.js +0 -3
  194. package/chunks/write-file-XDDLTGSG.js +0 -15
@@ -0,0 +1,120 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{a as zn,b as Ht,c as Vn,d as Wn}from"./chunk-DC7LAFZZ.js";import{b as M,e as se}from"./chunk-LZDHANXA.js";import{a as Ln,d as Un,o as Kn,r as jn}from"./chunk-SR7ARGUY.js";import{$a as tt,Eb as Ie,Oc as Vt,Pb as Kt,Pc as Wt,Qa as Lr,Rb as jt,Rc as qt,Sa as Ur,Ta as ge,Tb as zt,Za as Ze,_a as et,a as I,db as Bt,f as J,hb as nt,ib as ae,oa as $t,wb as ot,xb as rt}from"./chunk-OEZS5R3S.js";import{Q as Xe,U as Bn,W as Gt,ba as $,c as Fn,d as Gn,e as Y,f as we,k as Lt}from"./chunk-62AFAL4I.js";import{b as Ut,c as U,f as Ft,g as xe,h as D,i as Qe,k as $n,l as G,n as fe}from"./chunk-FWDMPRKU.js";import{b as f}from"./chunk-GZPNIYVZ.js";import{f as Nr}from"./chunk-OWGSC52X.js";f();var Fr=["www-browser"];function Gr(e){let t=e.replace(/\\/g,"/").split("/").pop();return!!t&&Fr.includes(t)}function qn(e={}){let n=process.env.BROWSER?.trim()?.match(/^\S+/)?.[0];if(!e.ignoreBrowserBlocklist&&process.platform!=="win32"&&n&&Gr(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")}f();function me(e){return!Number.isFinite(e)||e<=0?0:Math.ceil(e/4)}function it(e){let t=e.candidates||0,n=e.thoughts||0;return n>t?t+n:Math.max(t,n)}function $r(e){return e.total&&e.total>0?Math.max(e.total,(e.prompt||0)+it(e)):(e.prompt||0)+it(e)}function Br(e){let t=Math.max(0,e.thoughtsTokens||0),n=it({candidates:e.outputTokens||0,thoughts:t}),o=Math.max(e.totalTokens||0,(e.inputTokens||0)+n);return{...e,outputTokens:n,thoughtsTokens:t,totalTokens:o}}f();f();f();f();f();var z=class extends Error{constructor(t,n){super(`${t} at position ${n}`),this.position=n}};f();function Hn(e){return/^[0-9A-Fa-f]$/.test(e)}function Q(e){return e>="0"&&e<="9"}function Yn(e){return e>=" "}function Oe(e){return`,:[]/{}()
4
+ +`.includes(e)}function Yt(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"||e==="$"}function Jt(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"||e==="$"||e>="0"&&e<="9"}var Xt=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,Qt=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function Zt(e){return`,[]/{}
5
+ +`.includes(e)}function en(e){return Pe(e)||Kr.test(e)}var Kr=/^[[{\w-]$/;function Jn(e){return e===`
6
+ `||e==="\r"||e===" "||e==="\b"||e==="\f"}function X(e,t){let n=e.charCodeAt(t);return n===32||n===10||n===9||n===13}function Xn(e,t){let n=e.charCodeAt(t);return n===32||n===9||n===13}function Qn(e,t){let n=e.charCodeAt(t);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function Pe(e){return tn(e)||st(e)}function tn(e){return e==='"'||e==="\u201C"||e==="\u201D"}function nn(e){return e==='"'}function st(e){return e==="'"||e==="\u2018"||e==="\u2019"||e==="`"||e==="\xB4"}function on(e){return e==="'"}function he(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 B(e,t){let n=e.length;if(!X(e,n-1))return e+t;for(;X(e,n-1);)n--;return e.substring(0,n)+t+e.substring(n)}function Zn(e,t,n){return e.substring(0,t)+e.substring(t+n)}function eo(e){return/[,\n][ \t\r]*$/.test(e)}var jr={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},zr={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
7
+ `,r:"\r",t:" "};function at(e){let t=0,n="";c(["```","[```","{```"]),i()||re(),c(["```","```]","```}"]);let r=p(",");for(r&&s(),en(e[t])&&eo(n)?(r||(n=B(n,",")),T()):r&&(n=he(n,","));e[t]==="}"||e[t]==="]";)t++,s();if(t>=e.length)return n;Ye();function i(){s();let y=m()||C()||S()||O()||F()||K(!1)||Dt();return s(),y}function s(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,E=t,b=a(y);do b=d(),b&&(b=a(y));while(b);return t>E}function a(y){let E=y?X:Xn,b="";for(;;)if(E(e,t))b+=e[t],t++;else if(Qn(e,t))b+=" ",t++;else break;return b.length>0?(n+=b,!0):!1}function d(){if(e[t]==="/"&&e[t+1]==="*"){for(;t<e.length&&!Vr(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 c(y){if(l(y)){if(Yt(e[t]))for(;t<e.length&&Jt(e[t]);)t++;return s(),!0}return!1}function l(y){a(!0);for(let E of y){let b=t+E.length;if(e.slice(t,b)===E)return t=b,!0}return!1}function p(y){return e[t]===y?(n+=e[t],t++,!0):!1}function u(y){return e[t]===y?(t++,!0):!1}function g(){return u("\\")}function h(){return s(),e[t]==="."&&e[t+1]==="."&&e[t+2]==="."?(t+=3,s(),u(","),!0):!1}function m(){if(e[t]==="{"){n+="{",t++,s(),u(",")&&s();let y=!0;for(;t<e.length&&e[t]!=="}";){let E;if(y?(E=!0,y=!1):(E=p(","),E||(n=B(n,",")),s()),h(),!(S()||K(!0))){e[t]==="}"||e[t]==="{"||e[t]==="]"||e[t]==="["||e[t]===void 0?n=he(n,","):L();break}s();let Je=p(":"),ie=t>=e.length;Je||(en(e[t])||ie?n=B(n,":"):ke()),i()||(Je||ie?n+="null":ke())}return e[t]==="}"?(n+="}",t++):n=B(n,"}"),!0}return!1}function C(){if(e[t]==="["){n+="[",t++,s(),u(",")&&s();let y=!0;for(;t<e.length&&e[t]!=="]";)if(y?y=!1:p(",")||(n=B(n,",")),h(),!i()){n=he(n,",");break}return e[t]==="]"?(n+="]",t++):n=B(n,"]"),!0}return!1}function T(){let y=!0,E=!0;for(;E;)y?y=!1:p(",")||(n=B(n,",")),E=i();E||(n=he(n,",")),n=`[
9
+ ${n}
10
+ ]`}function S(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,E=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,b=e[t]==="\\";if(b&&(t++,b=!0),Pe(e[t])){let Je=nn(e[t])?nn:on(e[t])?on:st(e[t])?st:tn,ie=t,_e=n.length,v='"';for(t++;;){if(t>=e.length){let x=P(t-1);return!y&&Oe(e.charAt(x))?(t=ie,n=n.substring(0,_e),S(!0)):(v=B(v,'"'),n+=v,!0)}if(t===E)return v=B(v,'"'),n+=v,!0;if(Je(e[t])){let x=t,Nt=v.length;if(v+='"',t++,n+=v,s(!1),y||t>=e.length||Oe(e[t])||Pe(e[t])||Q(e[t]))return R(),!0;let H=P(x-1),Nn=e.charAt(H);if(Nn===",")return t=ie,n=n.substring(0,_e),S(!1,H);if(Oe(Nn))return t=ie,n=n.substring(0,_e),S(!0);n=n.substring(0,_e),t=x+1,v=`${v.substring(0,Nt)}\\${v.substring(Nt)}`}else if(y&&Zt(e[t])){if(e[t-1]===":"&&Xt.test(e.substring(ie+1,t+2)))for(;t<e.length&&Qt.test(e[t]);)v+=e[t],t++;return v=B(v,'"'),n+=v,R(),!0}else if(e[t]==="\\"){let x=e.charAt(t+1);if(zr[x]!==void 0)v+=e.slice(t,t+2),t+=2;else if(x==="u"){let H=2;for(;H<6&&Hn(e[t+H]);)H++;H===6?(v+=e.slice(t,t+6),t+=6):t+H>=e.length?t=e.length:Dr()}else v+=x,t+=2}else{let x=e.charAt(t);x==='"'&&e[t-1]!=="\\"?(v+=`\\${x}`,t++):Jn(x)?(v+=jr[x],t++):(Yn(x)||oe(x),v+=x,t++)}b&&g()}}return!1}function R(){let y=!1;for(s();e[t]==="+";){y=!0,t++,s(),n=he(n,'"',!0);let E=n.length;S()?n=Zn(n,E,1):n=B(n,'"')}return y}function O(){let y=t;if(e[t]==="-"){if(t++,pe())return w(y),!0;if(!Q(e[t]))return t=y,!1}for(;Q(e[t]);)t++;if(e[t]==="."){if(t++,pe())return w(y),!0;if(!Q(e[t]))return t=y,!1;for(;Q(e[t]);)t++}if(e[t]==="e"||e[t]==="E"){if(t++,(e[t]==="-"||e[t]==="+")&&t++,pe())return w(y),!0;if(!Q(e[t]))return t=y,!1;for(;Q(e[t]);)t++}if(!pe())return t=y,!1;if(t>y){let E=e.slice(y,t),b=/^0\d/.test(E);return n+=b?`"${E}"`:E,!0}return!1}function F(){return _("true","true")||_("false","false")||_("null","null")||_("True","true")||_("False","false")||_("None","null")}function _(y,E){return e.slice(t,t+y.length)===y?(n+=E,t+=y.length,!0):!1}function K(y){let E=t;if(Yt(e[t])){for(;t<e.length&&Jt(e[t]);)t++;let b=t;for(;X(e,b);)b++;if(e[b]==="(")return t=b+1,i(),e[t]===")"&&(t++,e[t]===";"&&t++),!0}for(;t<e.length&&!Zt(e[t])&&!Pe(e[t])&&(!y||e[t]!==":");)t++;if(e[t-1]===":"&&Xt.test(e.substring(E,t+2)))for(;t<e.length&&Qt.test(e[t]);)t++;if(t>E){for(;X(e,t-1)&&t>0;)t--;let b=e.slice(E,t);return n+=b==="undefined"?"null":JSON.stringify(b),e[t]==='"'&&t++,!0}}function Dt(){if(e[t]==="/"){let y=t;for(t++;t<e.length&&(e[t]!=="/"||e[t-1]==="\\");)t++;return t++,n+=`"${e.substring(y,t)}"`,!0}}function P(y){let E=y;for(;E>0&&X(e,E);)E--;return E}function pe(){return t>=e.length||Oe(e[t])||X(e,t)}function w(y){n+=`${e.slice(y,t)}0`}function oe(y){throw new z(`Invalid character ${JSON.stringify(y)}`,t)}function Ye(){throw new z(`Unexpected character ${JSON.stringify(e[t])}`,t)}function re(){throw new z("Unexpected end of json string",e.length)}function L(){throw new z("Object key expected",t)}function ke(){throw new z("Colon expected",t)}function Dr(){let y=e.slice(t,t+6);throw new z(`Invalid unicode character "${y}"`,t)}}function Vr(e,t){return e[t]==="*"&&e[t+1]==="/"}var Wr=$("JSON_PARSE");function qr(e,t={}){if(!e||typeof e!="string")return t;try{return JSON.parse(e)}catch(n){let o=Hr(e);if(o!==void 0)return o;try{let r=at(e);return JSON.parse(r)}catch(r){let i=oo(e);if(i&&i!==e)try{return JSON.parse(at(i))}catch{}return Wr.error("Failed to parse JSON even with jsonrepair:",{originalError:n,repairError:r,jsonString:e}),t}}}var to=Symbol("tool-args-parse-failed");function no(e){if(e==null)return{};let t=typeof e=="string"?e.trim():"";if(!t)return{};let n=qr(t,to);return n===to?null:n&&typeof n=="object"&&!Array.isArray(n)?n:null}function Hr(e){let t=oo(e);if(t&&t!==e.trim())try{return JSON.parse(t)}catch{return}}function oo(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}f();var Yr=/[A-Za-z\u00C0-\u024F]/g;function Jr(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 rn(e){let t=e.codePointAt(0);return t!==void 0&&Jr(t)}function Xr(e){let t=e.match(Yr)?.length??0;if(t<24)return!1;let n=0;for(let o of e)rn(o)&&n++;return n===0||t>=n*8}function lt(e){if(!e||!Xr(e))return e;let t="",n=0,o=[...e];for(;n<o.length;){if(!rn(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&&rn(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," ")}f();var Ce=$("TAGGED_THINKING_PARSER"),Ne=["<think>","<thinking>"],Le=["</think>","</thinking>"],Qr=Math.max(...Ne.map(e=>e.length),...Le.map(e=>e.length));function De(e,t,n){t&&e.push(n==="thought"?{text:t,thought:!0}:{text:t})}function ut(e,t,n){let o=e.length-t;return o<=0||o>Qr?!1:n.some(r=>r.startsWith(e.slice(t,t+o)))}function ct(e,t,n){return n.find(o=>e.startsWith(o,t))}function an(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 ro(e){let t=[];for(let n of e){if(n.thought===!0||typeof n.text!="string"){t.push(n);continue}let o=lt(an(n.text));(o.length>0||/^\s+$/.test(n.text))&&t.push({text:o.length>0?o:n.text})}return t}var sn=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=ct(o,s,Ne);if(a){Ce.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),De(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let d=ct(o,s,Le);if(d){Ce.debug(`taggedThinking: dropping orphan close tag "${d}" at offset ${s}`),De(r,i,this.mode),i="",s+=d.length;continue}if(!n&&(ut(o,s,Ne)||ut(o,s,Le)))break}else{let a=ct(o,s,Le);if(a){Ce.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),De(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let d=ct(o,s,Ne);if(d){s+=d.length;continue}if(!n&&(ut(o,s,Le)||ut(o,s,Ne)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(De(r,i,this.mode),this.buffer=this.buffer.slice(s),Ce.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),ro(r)):(this.buffer="",this.mode==="thought"&&i&&Ce.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),De(r,i,this.mode),Ce.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),ro(r))}};function io(e){return new sn().parse(e,!0)}f();function so(e,t="auto"){return t==="openapi_30"?Zr(e):e}function Zr(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)}var V=$("CONVERTER"),go="(attached media from previous tool call)";function mo(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,d=a?.reasoning_tokens??a?.reasoningTokens??e.reasoning_tokens??0,c=Math.max(0,t.estimatedReasoningTokens??0),l=Math.max(0,t.estimatedContentTokens??0),p=d>0?d:c,u=o;p>0&&(o>=p?u=o:u=o+p),(l>0||c>0)&&(u=Math.max(u,l+(d>0?0:c),l+p)),r>n&&(n>0||o>0||p>0)&&(u=Math.max(u,r-n)),p===0&&c>0&&(p=c),p>u&&(p=u);let g=e.usage_is_incomplete===!0||o>0&&n===0||r>0&&n===0&&o===0,h=n,m=r;return(m===0&&(h>0||u>0)||m>0&&h>0&&m<h+u)&&(m=h+u),{promptTokenCount:h,candidatesTokenCount:u,totalTokenCount:m,cachedContentTokenCount:s,thoughtsTokenCount:p,...g?{usageIsIncomplete:!0}:{}}}var ei=64,ao=1024;function lo(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)?(V.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${t.emittedText.length}b, chunk=${e.length}b)`),""):(V.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>=ao&&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,V.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${e.length}b)`),i}}return e===t.emittedText?e.length>=ei?(t.cumulativeMode=!0,V.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${e.length}b)`),""):(t.emittedLength+=e.length,e):(t.emittedText.length<ao&&(t.emittedText+=e),t.emittedLength+=e.length,e)}function ho(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 ti(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=ho(i.parameters)),s&&(s=so(s,t)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function ni(e,t,n={cleanOrphanToolCalls:!0}){let o=[];return ri(e,o),ii(e.contents,o,t),o=fo(o),n.cleanOrphanToolCalls&&(o=mi(o),o=fo(o)),o}function oi(e,t){let n=e.candidates?.[0],o=n?.content?.parts||[],r=[],i=[],s=[],a=0;for(let m of o)typeof m=="string"?i.push(m):"text"in m&&m.text?"thought"in m&&m.thought?r.push(m.text):i.push(m.text):"functionCall"in m&&m.functionCall&&(s.push({id:m.functionCall.id||`call_${a}`,type:"function",function:{name:m.functionCall.name||"",arguments:JSON.stringify(m.functionCall.args||{})}}),a+=1);let d={role:"assistant",content:i.join("")||null,refusal:null},c=r.join("");c&&(d.reasoning_content=c),s.length>0&&(d.tool_calls=s);let l=gi(n?.finishReason),p=e.usageMetadata,u={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(u.prompt_tokens_details={cached_tokens:p.cachedContentTokenCount});let g=e.createTime?Number(e.createTime):Date.now(),h=Number.isFinite(g)?Math.floor(g/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:d,finish_reason:l,logprobs:null}],usage:u}}function ri(e,t){if(!e.config?.systemInstruction)return;let n=yo(e.config.systemInstruction);n&&t.push({role:"system",content:n})}function ii(e,t,n){if(Array.isArray(e))for(let o of e)uo(o,t,n);else e&&uo(e,t,n)}function uo(e,t,n){if(typeof e=="string"){t.push({role:"user",content:e});return}if(!ui(e))return;let o=e.parts||[],r=e.role==="model"?"assistant":"user",i=[],s=[],a=[],d=0,c=new Set,l=new Set,p=[];for(let u of o){if(typeof u=="string"){i.push({type:"text",text:u});continue}"text"in u&&"thought"in u&&u.thought&&r==="assistant"&&u.text&&s.push(u.text),"text"in u&&u.text&&!("thought"in u&&u.thought)&&i.push({type:"text",text:u.text});let g=Co(u,n);if(g&&r==="user"&&i.push(g),"functionCall"in u&&u.functionCall&&r==="assistant"){let h=u.functionCall.id;if(h){if(c.has(h)){V.debug(`Dropping duplicate functionCall id=${h} while converting content`);continue}c.add(h)}a.push({id:h||`call_${d}`,type:"function",function:{name:u.functionCall.name||"",arguments:JSON.stringify(u.functionCall.args||{})}}),d+=1}if(u.functionResponse&&r==="user"){let h=u.functionResponse.id;if(h){if(l.has(h))continue;l.add(h)}let m=ai(u.functionResponse,n);if(m){if(n.splitToolMedia&&Array.isArray(m.content)){let C=[],T=[];for(let S of m.content)S&&(S.type==="image_url"||S.type==="input_audio"||S.type==="video_url"||S.type==="file")?C.push(S):S&&S.type==="text"&&T.push(S);if(C.length>0){let S=T.map(R=>R.text).join(`
11
+ `);m.content=S||"[media attached in following user message]",p.push(...C)}}t.push(m)}}}if(p.length>0&&t.push({role:"user",content:[{type:"text",text:go},...p]}),r==="assistant"){if(i.length===0&&a.length===0&&s.length===0)return;let g={role:"assistant",content:i.filter(m=>m.type==="text").map(m=>m.text).join("")||(s.length>0?"":null)};a.length>0&&(g.tool_calls=a);let h=s.join("");h&&(g.reasoning_content=h),t.push(g);return}i.length>0&&t.push({role:"user",content:i})}function si(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 ai(e,t){let n=si(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=Co(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 Co(e,t){let{modalities:n}=t;if(e.inlineData?.mimeType&&e.inlineData?.data){let o=e.inlineData.mimeType,r=co(o),i=e.inlineData.displayName||o;if(r==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${e.inlineData.data}`}}:le("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}`}}:le("pdf",i,t);if(r==="audio"){if(!n.audio)return le("audio",i,t);let s=li(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}`}}:le("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=co(i);if(s==="image")return n.image?{type:"image_url",image_url:{url:r}}:le("image",o,t);if(i==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:r}}:le("pdf",o,t);if(s==="video")return n.video?{type:"video_url",video_url:{url:r}}:le("video",o,t);let a=e.fileData.displayName?` (${e.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${i}${a}.`}}return null}function le(e,t,n){V.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 co(e){return e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":e.startsWith("video/")?"video":"file"}function li(e){return e.includes("wav")?"wav":e.includes("mp3")||e.includes("mpeg")?"mp3":null}function ui(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&Array.isArray(e.parts)}function yo(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>yo(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 dt(e,t,n=!0){if(t.taggedThinkingParser)return t.taggedThinkingParser.parse(e,n);if(t.responseParsingOptions?.taggedThinkingTags)return io(e);if(!e)return[];let o=lt(an(e));return o?[{text:o}]:[]}function ci(e,t){let n=e.choices?.[0],o=new se;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(...dt(n.message.content,t)),n.message.tool_calls){for(let i of n.message.tool_calls)if(i.function){let s=no(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:To(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=mo(e.usage,{estimatedReasoningTokens:me(i.length),estimatedContentTokens:me(s.length)})}return o}function di(e,t){let n=e.choices?.[0],o=new se,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 c=n.delta?.reasoning_content??n.delta?.reasoning;if(c){let l=lo(c,t.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});l&&i.push({text:l,thought:!0})}}if(typeof n.delta?.content=="string"){let c=lo(n.delta.content,t.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(c||n.finish_reason)&&i.push(...dt(c,t,!!n.finish_reason))}else n.finish_reason&&i.push(...dt("",t,!0));if(n.delta?.tool_calls)for(let c of n.delta.tool_calls){let l=c.index??0;c.function?.arguments?r.addChunk(l,c.function.arguments,c.id,c.function.name):r.addChunk(l,"",c.id,c.function?.name)}let s=!1;if(n.finish_reason){s=r.hasIncompleteToolCalls();let c=r.getCompletedToolCalls();for(let l of c)l.name&&i.push({functionCall:{id:l.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:l.name,args:l.args}})}let a=s&&n.finish_reason!=="length"?"length":n.finish_reason,d={content:{parts:i,role:"model"},index:0,safetyRatings:[]};a&&(d.finishReason=To(a)),o.candidates=[d]}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=mo(e.usage,fi(t))),o}function pi(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(...dt("",e,!0)),n.length===0&&!r)return null;let i=new se;return i.candidates=[{content:{parts:n,role:"model"},index:0,safetyRatings:[],finishReason:r?M.MAX_TOKENS:M.STOP}],i.responseId=`stream-flush-${Date.now()}`,i.createTime=new Date().getTime().toString(),i.modelVersion=e.model,i.promptFeedback={safetyRatings:[]},i}function fi(e){return{estimatedReasoningTokens:me(e.reasoningDeltaState?.emittedLength??0),estimatedContentTokens:me(e.textDeltaState?.emittedLength??0)}}function To(e){return e?{stop:M.STOP,length:M.MAX_TOKENS,content_filter:M.SAFETY,function_call:M.STOP,tool_calls:M.STOP}[e]||M.FINISH_REASON_UNSPECIFIED:M.FINISH_REASON_UNSPECIFIED}function gi(e){if(!e)return"stop";switch(e){case M.STOP:return"stop";case M.MAX_TOKENS:return"length";case M.SAFETY:case M.RECITATION:case M.BLOCKLIST:case M.PROHIBITED_CONTENT:case M.SPII:case M.IMAGE_SAFETY:case M.IMAGE_RECITATION:case M.IMAGE_PROHIBITED_CONTENT:case M.IMAGE_OTHER:return"content_filter";case M.NO_IMAGE:return"stop";default:return"stop"}}function ln(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===go}function mi(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 d=e[a];if(ln(d)){let c=[],l=new Set;for(let C of d.tool_calls){let T=C.id;!T||s.has(T)||l.has(T)||(l.add(T),c.push(C))}let p=new Set,u=[],g=[],h=!1;for(let C=a+1;C<e.length;C+=1){let T=e[C];if(T.role==="tool"&&"tool_call_id"in T){if(!T.tool_call_id){h=!1;continue}l.has(T.tool_call_id)&&!p.has(T.tool_call_id)?(p.add(T.tool_call_id),u.push(C),h=!0):h=!1;continue}if(po(T)){h&&g.push(C);continue}if(!(T.role==="assistant"&&!ln(T)))break}let m=c.filter(C=>p.has(C.id));for(let C of m)s.add(C.id);n.set(a,m),o.set(a,u),r.set(a,g)}}for(let a=0;a<e.length;a+=1){if(i.has(a))continue;let d=e[a];if(ln(d)){let c=d.reasoning_content,l=n.get(a)??[];if(l.length>0){let p={...d};p.tool_calls=l,t.push(p);for(let u of o.get(a)??[]){let g=e[u];g&&(t.push(g),i.add(u))}for(let u of r.get(a)??[]){let g=e[u];g&&(t.push(g),i.add(u))}}else if(typeof d.content=="string"&&d.content.trim()||c){let p={...d};delete p.tool_calls,t.push(p)}else V.debug(`cleanOrphanedToolCalls: dropping assistant with ${d.tool_calls.length} orphaned tool call(s) and no text/reasoning content`)}else d.role==="tool"&&"tool_call_id"in d?V.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${d.tool_call_id||"<empty>"}`):po(d)?V.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):t.push(d)}return t}function fo(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,d=Array.isArray(s)||Array.isArray(a),c;if(d){let p=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[],u=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[];c=[...p,...u]}else c=[typeof s=="string"?s:"",typeof a=="string"?a:""].filter(Boolean).join("")||null;let l=[...r,...i];o.content=c||null,l.length>0&&(o.tool_calls=l);continue}}t.push(n)}return t}var pt={convertGeminiToolParametersToOpenAI:ho,convertGeminiToolsToOpenAI:ti,convertGeminiRequestToOpenAI:ni,convertGeminiResponseToOpenAI:oi,convertOpenAIResponseToGemini:ci,convertOpenAIChunkToGemini:di,flushOpenAIStreamToGemini:pi};f();import*as j from"node:path";import{promises as mt}from"node:fs";f();f();import hi from"crypto";var gt=new Uint8Array(256),ft=gt.length;function un(){return ft>gt.length-16&&(hi.randomFillSync(gt),ft=0),gt.slice(ft,ft+=16)}f();var k=[];for(let e=0;e<256;++e)k.push((e+256).toString(16).slice(1));function Ao(e,t=0){return k[e[t+0]]+k[e[t+1]]+k[e[t+2]]+k[e[t+3]]+"-"+k[e[t+4]]+k[e[t+5]]+"-"+k[e[t+6]]+k[e[t+7]]+"-"+k[e[t+8]]+k[e[t+9]]+"-"+k[e[t+10]]+k[e[t+11]]+k[e[t+12]]+k[e[t+13]]+k[e[t+14]]+k[e[t+15]]}f();f();import Ci from"crypto";var cn={randomUUID:Ci.randomUUID};function yi(e,t,n){if(cn.randomUUID&&!t&&!e)return cn.randomUUID();e=e||{};let o=e.random||(e.rng||un)();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 Ao(o)}var dn=yi;import*as Z from"os";var ht=$("OPENAI_LOGGER"),Ti="########",Ai=/^[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 Ei(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(Z.homedir(),e.slice(1)):j.isAbsolute(e)||(o=j.resolve(n,e)),j.normalize(o)}function Eo(e){return e&&e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function Si(e){let t=e.split("#");if(t.length!==3)return;let[,n,o]=t;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function bi(e){if(e)return ge(e)?Eo(e):Eo(Si(e))}function Ri(e){if(!e)return;let t=e.indexOf(Ti);if(t>0)return e.slice(0,t);if(Ai.test(e))return e;let n=e.split("#");if(n.length>=3&&n[0])return n[0]}function vi(e){let t=e?.trim(),n=Ri(t);return!t&&!n?null:{...t?{promptId:t}:{},...n?{sessionId:n}:{}}}var Ue=class{logDir;initialized=!1;constructor(t,n){this.logDir=Ei(t,n)}async initialize(){if(!this.initialized)try{await mt.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(t){throw ht.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=dn().slice(0,8),a=bi(r),d=a?`openai-${i}-${s}-${a}.json`:`openai-${i}-${s}.json`,c=j.join(this.logDir,d),l={timestamp:new Date().toISOString(),request:t,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:vi(r),system:{hostname:Z.hostname(),platform:Z.platform(),release:Z.release(),nodeVersion:process.version}};try{return await mt.writeFile(c,JSON.stringify(l,null,2),"utf-8"),c}catch(p){throw ht.error("Failed to write OpenAI log file:",p),new Error(`Failed to write OpenAI log file: ${p}`)}}async getLogFiles(t){this.initialized||await this.initialize();try{let o=(await mt.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"?[]:(ht.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(t){try{let n=await mt.readFile(t,"utf-8");return JSON.parse(n)}catch(n){throw ht.error(`Failed to read log file ${t}:`,n),new Error(`Failed to read log file: ${n}`)}}},mu=new Ue;f();var Mi="MATILDA_CODE_PROFILE_RUNTIME";function So(e=process.env){return e[Mi]==="1"}var fn=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;requests=[];openaiWireRequests=[];tools=bo();constructor(t={}){this.enabled=t.enabled??So(),this.now=t.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(t={}){this.enabled=t.enabled??So(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.tools=bo()}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:N(Oi(t)),contents:Ro(t.contents),systemInstructionBytes:wi(t.config?.systemInstruction),generationConfigBytes:N(vo(t.config)),tools:Ii(t.config?.tools)}))}recordOpenAIWireRequest(t){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...ki(t)}))}recordToolUse(t,n){if(!this.enabled)return;let o=N(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=_i();return this.tools.byName[t]=o,o}},gn=new fn;function ki(e){let t=ye(e),n=Array.isArray(t.messages)?t.messages:[],o=Array.isArray(t.tools)?t.tools:[],r={};for(let i of n){let s=ye(i),a=typeof s.role=="string"?s.role:"unknown";r[a]=(r[a]??0)+N(s.content)}return{model:typeof t.model=="string"?t.model:"unknown",stream:t.stream===!0,bodyBytes:N(e),messageCount:n.length,messageBytesByRole:r,toolsCount:o.length,toolSchemaBytes:N(o),topLevelKeys:Object.keys(t).sort()}}function bo(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function _i(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function Ro(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+=N(o);continue}let r=ye(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:[];xi(s,t)}return t}function wi(e){return Ro(e).textBytes}function xi(e,t){for(let n of e){if(t.partCount+=1,typeof n=="string"){t.textBytes+=N(n);continue}let o=ye(n);typeof o.text=="string"&&(t.textBytes+=N(o.text));let r=pn(o.functionCall);r&&(t.functionCallCount+=1,t.functionCallArgBytes+=N(r.args));let i=pn(o.functionResponse);i&&(t.functionResponseCount+=1,t.functionResponseBytes+=N(i.response)+N(i.parts));let s=pn(o.inlineData);s&&(t.inlineDataCount+=1,t.inlineDataBytes+=N(s.data)),o.fileData&&(t.fileDataCount+=1)}}function Ii(e){let t=Array.isArray(e)?e:[],n=0;for(let o of t){let r=ye(o),i=Array.isArray(r.functionDeclarations)?r.functionDeclarations:[];n+=i.length}return{count:t.length,functionDeclarationCount:n,schemaBytes:N(t)}}function Oi(e){return{model:e.model,contents:e.contents,config:vo(e.config)}}function vo(e){if(!e)return;let t=ye(e),n={};for(let[o,r]of Object.entries(t))o!=="abortSignal"&&(n[o]=r);return n}function N(e){return e==null?0:typeof e=="string"?Buffer.byteLength(e,"utf8"):Buffer.byteLength(Pi(e),"utf8")}function Pi(e){try{return JSON.stringify(e)??""}catch{return"[unserializable]"}}function ye(e){return typeof e=="object"&&e!==null?e:{}}function pn(e){return typeof e=="object"&&e!==null?e:null}f();f();fe();Ur();f();fe();var Mo=Nr(Lr(),1);import{createHash as Di}from"node:crypto";var Te="matilda.telemetry.traceparent",Ct="matilda.telemetry.tracestate",Ni="matilda-code.daemon.request",ko="matilda-code.daemon.bridge",Li="matilda-code.daemon.error";function Ui(e){return e instanceof Error?e.message:String(e)}function Fi(e){return e instanceof Error?e.name||"Error":typeof e}var Gi="0".repeat(32),$i="0".repeat(16);function Bi(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e;if(!(Te in t)&&!(Ct in t))return{...t};let n={...t};return delete n[Te],delete n[Ct],n}function Ki(e){return Di("sha256").update(e).digest("hex").slice(0,16)}async function mn(e,t,n,o={}){if(!Ie())return await n(void 0);let r=o.autoOkOnSuccess??!0;return await G.getTracer(I).startActiveSpan(e,{kind:Ft.INTERNAL,attributes:t},async s=>{try{let a=await n(s);return r&&s.setStatus({code:xe.OK}),a}catch(a){throw wo(s,a),a}finally{s.end()}})}async function ji(e,t){return await mn(Ni,{"http.request.method":e.method,"http.route":e.route,"matilda-code.daemon.operation":"http_request",...e.workspaceHash?{"matilda-code.workspace.hash":e.workspaceHash}:{},...e.sessionId?{"session.id":e.sessionId}:{},...e.clientId?{"matilda-code.client_id":e.clientId}:{},...e.permissionRequestId?{"matilda-code.daemon.permission.request_id":e.permissionRequestId}:{}},t,{autoOkOnSuccess:!1})}async function _o(e,t,n){return await mn(ko,{"matilda-code.daemon.operation":e,...t},async()=>await n())}function zi(e,t){try{e?.setAttribute("http.response.status_code",t)}catch{}}function Vi(e,t){try{G.getSpan(D.active())?.setAttribute(e,t)}catch{}}function wo(e,t,n={}){let o=e??G.getSpan(D.active());if(o)try{let r=Bt(Ui(t));o.recordException(t instanceof Error?t:new Error(r)),o.setAttributes({"error.type":Fi(t),"error.message":r,...n}),o.setStatus({code:xe.ERROR,message:r})}catch{}}function Wi(e,t={},n){if(Ie())try{Mo.logs.getLogger(I).emit({body:e,timestamp:new Date,attributes:{"event.name":n?.eventName??Li,...t},...n?.severityNumber!=null?{severityNumber:n.severityNumber}:{}})}catch{}}function xo(){return{context:D.active()}}async function Io(e,t){let n=e&&typeof e=="object"&&"context"in e&&e.context?e.context:void 0;return n?await D.with(n,t):await t()}function Oo(e){let t=e._meta,n=Bi(t);try{let o=Bn();o&&(n[Te]=Gt(o))}catch{}return!t&&!n[Te]?e:{...e,_meta:n}}function qi(e){let t=e?._meta;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t,o=n[Te];if(typeof o!="string"||o.length===0)return;let r={traceparent:o},i=n[Ct];typeof i=="string"&&i.length>0&&(r.tracestate=i);let s=$n.extract(Ut,r);if(G.getSpanContext(s))return s;let a=o.split("-"),d=a[1],c=a[2],l=a[3];if(!(a[0]!=="00"||!d?.match(/^[0-9a-f]{32}$/)||!c?.match(/^[0-9a-f]{16}$/)||!l?.match(/^[0-9a-f]{2}$/)||d===Gi||c===$i))return G.setSpan(Ut,G.wrapSpanContext({traceId:d,spanId:c,traceFlags:Number.parseInt(l,16),isRemote:!0}))}function Hi(){return{captureContext:xo,runWithContext:Io,withSpan:_o,event(e,t){if(Ie())try{let n=G.getSpan(D.active());if(n){n.addEvent(e,t);return}let o=G.getTracer(I).startSpan(ko,{kind:Ft.INTERNAL,attributes:{"event.name":e,"matilda-code.daemon.operation":`event.${e}`,...t}});o.addEvent(e,t),o.setStatus({code:xe.OK}),o.end()}catch{}},injectPromptContext:Oo}}f();fe();var Yi=`${I}.daemon.http.request.count`,Ji=`${I}.daemon.http.request.duration`,Xi=`${I}.daemon.session.active`,Qi=`${I}.daemon.session.lifecycle`,Zi=`${I}.daemon.channel.lifecycle`,es=`${I}.daemon.prompt.queue_wait`,ts=`${I}.daemon.prompt.duration`,ns=`${I}.daemon.bridge.error.count`,os=`${I}.daemon.cancel.count`,rs=`${I}.daemon.sse.active`,is=`${I}.daemon.process.heap_used`,ss=new Set(["SessionNotFoundError","WorkspaceMismatchError","InvalidClientIdError","SessionLimitExceededError","RestoreInProgressError","InvalidSessionScopeError","TrustGateError","WorkspaceInitConflictError","WorkspaceInitPathEscapeError","WorkspaceInitSymlinkError","WorkspaceInitRaceError","McpServerNotFoundError","McpServerRestartFailedError","PromptDeadlineExceededError","InvalidSessionMetadataError","SubscriberLimitExceededError","BridgeChannelClosedError","BridgeTimeoutError","PermissionForbiddenError"]),W=!1,Do,No,Lo,Uo,Fo,Go,$o,Bo;function as(e){let t=e instanceof Error?e.name:typeof e;return ss.has(t)?t:"unknown"}function ls(){if(W)return;let e=$t();e&&(Do=e.createCounter(Yi,{description:"Daemon HTTP request count by route and status class.",valueType:U.INT}),No=e.createHistogram(Ji,{description:"Daemon HTTP request duration in milliseconds.",unit:"ms",valueType:U.DOUBLE,advice:{explicitBucketBoundaries:[1,2,5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4]}}),Lo=e.createCounter(Qi,{description:"Daemon session lifecycle events (spawn, close, die).",valueType:U.INT}),Uo=e.createCounter(Zi,{description:"Daemon ACP channel lifecycle events (spawn, exit).",valueType:U.INT}),Fo=e.createHistogram(es,{description:"Time a prompt waited in the per-session FIFO queue.",unit:"ms",valueType:U.DOUBLE,advice:{explicitBucketBoundaries:[1,5,10,50,100,500,1e3,5e3,1e4,3e4,6e4]}}),Go=e.createHistogram(ts,{description:"End-to-end prompt duration from dispatch to completion.",unit:"ms",valueType:U.DOUBLE,advice:{explicitBucketBoundaries:[100,500,1e3,2500,5e3,1e4,3e4,6e4,12e4,3e5,6e5]}}),$o=e.createCounter(ns,{description:"Daemon bridge error count by normalized error type.",valueType:U.INT}),Bo=e.createCounter(os,{description:"Daemon cancel request count.",valueType:U.INT}),W=!0)}var Po=!1;function us(e){if(Po)return;let t=$t();t&&(t.createObservableGauge(Xi,{description:"Current number of active daemon sessions.",valueType:U.INT}).addCallback(n=>{try{n.observe(e.sessionCount())}catch{}}),t.createObservableGauge(rs,{description:"Current number of active SSE connections.",valueType:U.INT}).addCallback(n=>{try{n.observe(e.sseCount())}catch{}}),t.createObservableGauge(is,{description:"Daemon process heap memory usage in bytes.",unit:"bytes",valueType:U.INT}).addCallback(n=>{try{n.observe(e.heapUsed())}catch{}}),Po=!0)}function cs(e,t,n){if(!W)return;let o=`${Math.floor(n/100)}xx`;Do?.add(1,{route:t,status_class:o}),No?.record(e,{route:t})}function ds(e){W&&Lo?.add(1,{action:e})}function ps(e,t){W&&Uo?.add(1,{action:e,...t!=null?{expected:t}:{}})}function fs(e){W&&Fo?.record(e)}function gs(e){W&&Go?.record(e)}function ms(e){W&&$o?.add(1,{error_type:as(e)})}function hs(){W&&Bo?.add(1)}f();fe();import*as ne from"node:fs";import*as Pt from"node:path";f();f();f();f();fe();f();import{AsyncLocalStorage as Cs}from"node:async_hooks";var Ko=new Cs;f();function jo(e){let t=e.candidates?.[0]?.content?.parts;return!t||t.length===0?!1:t.some(ys)}function ys(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 zo(){let e=Ln.getStore();return{attempt:e?.attempt??1,requestSetupMs:e?.requestSetupMs,retryTotalDelayMs:e?.retryTotalDelayMs}}var ue=$("LOGGING_CONTENT_GENERATOR"),Ts=4096,Vo="...[truncated]",As=Ts-Vo.length,Fe=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 Ue(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);Kt(this.config,new Vt(n,o,r,J.getStore()))}_logApiResponse(t,n,o,r,i,s){zt(this.config,new qt(t,o,n,r,this.generatorAuthType,i,s,J.getStore()))}_logApiError(t,n,o,r,i){let s=Gn(o),a=we(o),d=o?.requestID||o?.request_id||t,c=Y(o);jt(this.config,new Wt({responseId:d,model:r,durationMs:n,promptId:i,authType:this.generatorAuthType,errorMessage:s,errorType:a,statusCode:c,subagentName:J.getStore()}))}safelyLogApiError(t,n,o,r,i){try{this._logApiError(t,n,o,r,i)}catch(s){ue.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){ue.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=zo(),r=nt(t.model,n);try{r.setAttribute("llm_request.stream",!1)}catch{}let i=G.setSpan(D.active(),r),s=Date.now(),a=ge(n),d=this.startCaptureSession();try{gn.recordGenerateContentRequest(t,{stream:!1,source:"generateContent"}),a||(Ze(this.config,r,t.config?.systemInstruction),et(this.config,r,t.config?.tools));let c=await D.with(i,async()=>{a||this.logApiRequest(this.toContents(t.contents),t.model,n);let l=await d.wrap(()=>this.wrapped.generateContent(t,n)),p=Date.now()-s,u=a?void 0:this.extractResponseText(l);a||tt(this.config,r,u),this.safelyLogApiResponse(l.responseId??"",p,this.getClientVisibleModelId(t.model,l.modelVersion),n,l.usageMetadata,u);try{await this.safelyLogOpenAIInteraction(await d.resolve(t),l,void 0,n)}catch(g){ue.warn("Failed to log OpenAI interaction:",g)}return l});return ae(r,{success:!0,inputTokens:c.usageMetadata?.promptTokenCount,outputTokens:c.usageMetadata?.candidatesTokenCount,cachedInputTokens:c.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-s,responseId:c.responseId||void 0,finishReason:c.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:c.usageMetadata?.thoughtsTokenCount,subagentName:J.getStore()||void 0,...o}),c}catch(c){let l=Date.now()-s,p=t.config?.abortSignal?.aborted??!1;throw ae(r,{success:!1,durationMs:l,error:p?rt:ot,errorType:we(c),errorStatusCode:Y(c),subagentName:J.getStore()||void 0,...o}),await D.with(i,async()=>{this.safelyLogApiError("",l,c,this.getClientVisibleModelId(t.model),n);try{await this.safelyLogOpenAIInteraction(await d.resolve(t),void 0,c,n)}catch(u){ue.warn("Failed to log OpenAI interaction:",u)}}),c}}async generateContentStream(t,n){let o=zo(),r=nt(t.model,n);try{r.setAttribute("llm_request.stream",!0)}catch{}let i=G.setSpan(D.active(),r),s=Date.now(),a=ge(n),d=this.startCaptureSession(),c;try{gn.recordGenerateContentRequest(t,{stream:!0,source:"generateContentStream"}),a||(Ze(this.config,r,t.config?.systemInstruction),et(this.config,r,t.config?.tools)),c=await D.with(i,async()=>(a||this.logApiRequest(this.toContents(t.contents),t.model,n),d.wrap(()=>this.wrapped.generateContentStream(t,n))))}catch(p){let u=Date.now()-s;D.with(i,()=>this.safelyLogApiError("",u,p,t.model,n));let g=t.config?.abortSignal?.aborted??!1;ae(r,{success:!1,durationMs:u,error:g?rt:ot,errorType:we(p),errorStatusCode:Y(p),subagentName:J.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await d.resolve(t),void 0,p,n)}catch(h){ue.warn("Failed to log OpenAI interaction:",h)}throw p}let l;if(this.openaiLogger)try{l=await d.resolve(t)}catch(p){ue.warn("Failed to resolve OpenAI request:",p)}return D.with(i,()=>this.loggingStreamWrapper(c,s,n,t.model,l,r,i,t.config?.abortSignal,o))}startCaptureSession(){let t,n=!this.openaiLogger;return{wrap:o=>n?o():Ko.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,d,c){let l=ge(o),p=!l||!!this.openaiLogger,u=[],g="",h="",m,C=!1,T,S=!1,R,O=J.getStore(),F,_=!1,K=w=>a?D.with(a,w):w(),Dt=5*6e4,P,pe=s?()=>{_||(P!==void 0&&clearTimeout(P),P=setTimeout(()=>{try{s.setAttribute("stream.timed_out",!0)}catch{}ae(s,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:g||void 0,subagentName:O||void 0,...c}),_=!0},Dt),P.unref())}:void 0;try{for await(let L of t){!g&&L.responseId&&(g=L.responseId),!h&&L.modelVersion&&(h=L.modelVersion),p&&u.push(L),L.usageMetadata&&(m=L.usageMetadata);let ke=L.candidates?.[0];ke?.finishReason&&(T=ke.finishReason),L.functionCalls?.length&&(S=!0),F===void 0&&jo(L)&&(F=Date.now()-n),pe?.(),yield L,P!==void 0&&(clearTimeout(P),P=void 0)}P!==void 0&&(clearTimeout(P),P=void 0);let w=Date.now()-n,oe=p?this.consolidateGeminiResponsesForLogging(u):void 0,Ye=l?void 0:this.extractResponseText(oe),re=!T&&!S?new Error("Model stream ended without a finish reason"):void 0;re&&(C=!0,R=re),_||(re?(K(()=>this.safelyLogApiError(g,w,re,this.getClientVisibleModelId(r,h),o)),await K(()=>this.safelyLogOpenAIInteraction(i,oe,re,o))):(K(()=>this.safelyLogApiResponse(g,w,this.getClientVisibleModelId(r,h),o,m,Ye)),!l&&s&&tt(this.config,s,Ye),await K(()=>this.safelyLogOpenAIInteraction(i,oe,void 0,o))))}catch(w){if(C=!0,R=w,!_){let oe=Date.now()-n;K(()=>this.safelyLogApiError(g,oe,w,this.getClientVisibleModelId(r,h),o)),await K(()=>this.safelyLogOpenAIInteraction(i,void 0,w,o))}throw w}finally{if(P!==void 0&&clearTimeout(P),s&&!_){let w=d?.aborted??!1;ae(s,{success:!C,inputTokens:m?.promptTokenCount,outputTokens:m?.candidatesTokenCount,cachedInputTokens:m?.cachedContentTokenCount,ttftMs:F,durationMs:Date.now()-n,error:C?w?rt:ot:void 0,responseId:g||void 0,finishReason:T,thoughtsTokenCount:m?.thoughtsTokenCount,subagentName:O||void 0,errorType:R?we(R):void 0,errorStatusCode:R?Y(R):void 0,...c})}}}async buildOpenAIRequestForLogging(t){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(t.model),o=pt.convertGeminiRequestToOpenAI(t,n,{cleanOrphanToolCalls:!1}),r={model:t.model,messages:o};return t.config?.tools&&(r.tools=await pt.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){ue.warn("Failed to log OpenAI interaction:",i)}}convertGeminiResponseToOpenAIForLogging(t,n){let o=new se;return Object.assign(o,t),o.modelVersion=this.getClientVisibleModelId(n.model,t.modelVersion),pt.convertGeminiResponseToOpenAI(o,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(t){if(t.length===0)return;let n=new se,o=[],r=new Map,i,s;for(let c of t){c.usageMetadata&&(s=c.usageMetadata);let l=c.candidates?.[0];l?.finishReason&&(i=l.finishReason);let p=l?.content?.parts??[];for(let u of p){if(typeof u=="string"){o.push({text:u});continue}if("text"in u){u.text&&o.push({text:u.text,...u.thought?{thought:!0}:{},...u.thoughtSignature?{thoughtSignature:u.thoughtSignature}:{}});continue}if("functionCall"in u&&u.functionCall){let g=u.functionCall.id||u.functionCall.name||"tool_call",h=r.get(g),m={functionCall:u.functionCall};h!==void 0?o[h]=m:(r.set(g,o.length),o.push(m));continue}if("functionResponse"in u&&u.functionResponse){o.push({functionResponse:u.functionResponse});continue}o.push(u)}}let a=t[t.length-1],d=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:d?.content?.role||"model",parts:o},...i?{finishReason:i}:{},index:0,safetyRatings:d?.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 d=As-o.length;if(a.length<=d){o+=a;return}o+=a.slice(0,Math.max(0,d)),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}${Vo}`: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}};f();var hn="x-matilda-organization-id",Es=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function sc(e){if(e!==void 0){if(typeof e!="string"||e.length!==36||!Es.test(e))throw new Error("--organization-id must be a single UUID.");return e.toLowerCase()}}function Cn(e){if(e)try{let t=new URL(e);if((t.hostname==="matilda.maincode.com"&&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 yn(e,t,n){if(t===void 0&&n===void 0)return;let o=Cn(e.baseUrl);if(!o||o.pathname.replace(/\/$/,"")!=="/api/v1/code"||e.authType!=="openai"||e.matildaAgentSdk||process.env.MATILDA_AGENT_SDK==="1")throw new Error("Organization selection and credit spending require the first-party Matilda Core Code endpoint.")}function Wo(e){for(let t of Object.keys(e??{})){let n=t.toLowerCase();if(n===hn)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 ac(e,t,n,o,r){yn(n,o,r);let i=Cn(n.baseUrl),s=Cn(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(hn);if(a!==null&&a!==o)throw new Error("The request organization conflicts with --organization-id.");o!==void 0&&t.set(hn,o)}f();function qo(e){switch(e){case"openai":return"OPENAI_API_KEY";default:return"API_KEY"}}function Ho(e){switch(e){case"openai":return"OPENAI_MODEL";default:return"MODEL"}}var Ae=class extends Error{constructor(t){super(t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},yt=class extends Ae{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.`))}},Tt=class extends Ae{code="STRICT_MISSING_MODEL_ID";constructor(t){super(`Missing model id for strict modelProviders resolution (authType: ${t}).`)}},At=class extends Ae{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}'.`)}},Et=class extends Ae{code="MISSING_MODEL";constructor(t){super(`Missing model for ${t.authType} auth. Set the environment variable '${t.envKey}'.`)}};f();import Ms from"node:process";f();var pc=131072,fc=32e3,gc=8e3,mc=64e3,hc=2048;function Cc(e,t,n,o=2048){let r=t-n-o;return!Number.isFinite(r)||r<=0?0:Math.min(e,r)}var A={"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 St(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(/^matilda-(?:plus|flash|vl-max)-latest$/)&&!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 Ss=[[/^gemini-3/,A["1m"]],[/^gemini-/,A["1m"]],[/^gpt-5/,A["272k"]],[/^gpt-/,A["128k"]],[/^o\d/,A["200k"]],[/^claude-/,A["200k"]],[/^matilda3-coder-plus/,A["1m"]],[/^matilda3-coder-flash/,A["1m"]],[/^matilda3\.\d/,A["1m"]],[/^matilda-plus-latest$/,A["1m"]],[/^matilda-flash-latest$/,A["1m"]],[/^coder-model$/,A["1m"]],[/^matilda-code$/,A["1m"]],[/^matilda3-max/,A["256k"]],[/^matilda3-coder-/,A["256k"]],[/^matilda/,A["256k"]],[/^glm-5(\.[01])?(-|$)/,202752],[/^glm-(?:[5-9]|\d{2,})/,A["1m"]],[/^glm-/,202752],[/^matilda/,A["256k"]],[/^ornith/,A["64k"]],[/^kimi-/,A["256k"]],[/^seed-oss/,A["512k"]]],Yo=[[/^gemini-3/,A["64k"]],[/^gemini-/,A["8k"]],[/^gpt-5/,A["128k"]],[/^gpt-/,A["16k"]],[/^o\d/,A["128k"]],[/^claude-opus-4-6/,A["128k"]],[/^claude-sonnet-4-6/,A["64k"]],[/^claude-/,A["64k"]],[/^matilda3\.\d/,A["64k"]],[/^coder-model$/,A["64k"]],[/^matilda-code$/,A["64k"]],[/^matilda$/,A["64k"]],[/^matilda-core$/,A["64k"]],[/^matilda/,A["32k"]],[/^glm-5\.2/,A["64k"]],[/^glm-5/,A["64k"]],[/^glm-4\.7/,A["16k"]],[/^ornith/,A["32k"]],[/^kimi-k2\.5/,A["32k"]]];function bs(e,t="input"){let n=St(e),o=t==="output"?Yo:Ss;for(let[r,i]of o)if(r.test(n))return i}function yc(e){let t=St(e);return Yo.some(([n])=>n.test(t))}function Rs(e,t="input"){return bs(e,t)}function Ge(e,t="input"){return Rs(e,t)??(t==="output"?32e3:131072)}f();var Jo={image:!0,pdf:!0,audio:!0,video:!0},vs=[[/^gemini-3/,Jo],[/^gemini-/,Jo],[/^gpt-5/,{image:!0}],[/^gpt-/,{image:!0}],[/^o\d/,{image:!0}],[/^claude-/,{image:!0,pdf:!0}],[/^matilda3\.5-plus/,{image:!0,video:!0}],[/^matilda3\.6-plus/,{image:!0,video:!0}],[/^matilda3\.7-plus/,{image:!0,video:!0}],[/^coder-model$/,{image:!0,video:!0}],[/^matilda-vl-/,{image:!0,video:!0}],[/^matilda3-vl-/,{image:!0,video:!0}],[/^matilda-code$/,{}],[/^matilda3-coder-/,{}],[/^matilda3\.6-35b/,{image:!0,video:!0}],[/^matilda/,{}],[/^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 $e(e){let t=St(e);for(let[n,o]of vs)if(n.test(t))return{...o};return{}}f();var bt="$runtime|";function Rc(e){let t=e;for(;t.startsWith(bt);){let n=t.split("|").slice(2).join("|");if(!n)break;t=n}return t}f();f();var Xo="https://api.openai.com/v1",Qo="https://matilda.maincode.com/api/v1/code",kc=process.env.MATILDA_COMPAT_PROXY_BASE_URL;f();var Tn=$("MODEL_REGISTRY");function Zo(e){if(Object.values(q).includes(e))return e}function er(e,t){return t?`${e}\0${t}`:e}var Rt=class{modelsByAuthType;getDefaultBaseUrl(t){switch(t){case"openai":return Xo;default:return""}}constructor(t){if(this.modelsByAuthType=new Map,t)for(let[n,o]of Object.entries(t)){let r=Zo(n);if(!r){Tn.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(q).join(", ")}. Skipping.`);continue}this.registerAuthTypeModels(r,o)}}registerAuthTypeModels(t,n){let o=new Map;for(let r of n){let i=er(r.id,r.baseUrl);if(o.has(i)){Tn.warn(`Duplicate model id "${r.id}"${r.baseUrl?` with baseUrl "${r.baseUrl}"`:""} for authType "${t}". Using the first registered config.`);continue}let s=this.resolveModelConfig(r,t);o.set(i,s)}this.modelsByAuthType.set(t,o)}getModelsForAuthType(t){let n=this.modelsByAuthType.get(t);return n?Array.from(n.values()).map(o=>({id:o.id,label:o.name,description:o.description,capabilities:o.capabilities,authType:o.authType,isVision:o.capabilities?.vision??!1,contextWindowSize:o.generationConfig.contextWindowSize??Ge(o.id),modalities:o.generationConfig.modalities,baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(t,n,o){let r=this.modelsByAuthType.get(t);if(!r)return;if(o)return r.get(er(n,o));let i=r.get(n);if(i)return i;for(let s of r.values())if(s.id===n)return s}hasModel(t,n,o){return this.getModel(t,n,o)!==void 0}getDefaultModelForAuthType(t){let n=this.modelsByAuthType.get(t);if(!(!n||n.size===0))return Array.from(n.values())[0]}resolveModelConfig(t,n){this.validateModelConfig(t,n);let o={...t.generationConfig??{}};return o.modalities===void 0&&(o.modalities=$e(t.id)),{...t,authType:n,name:t.name||t.id,baseUrl:t.baseUrl||this.getDefaultBaseUrl(n),generationConfig:o,capabilities:t.capabilities||{}}}validateModelConfig(t,n){if(!t.id)throw new Error(`Model config in authType '${n}' missing required field: id`)}reloadModels(t){if(this.modelsByAuthType.clear(),t)for(let[n,o]of Object.entries(t)){let r=Zo(n);if(!r){Tn.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(q).join(", ")}. Skipping.`);continue}this.registerAuthTypeModels(r,o)}}};f();var vt=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],tr=["model","apiKey","apiKeyEnvKey","baseUrl"],Mt=[...tr,...vt],$c={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","MATILDA_MODEL"]}},Bc={openai:jn};var nr=class e{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;hasManualCredentials=!1;onModelChange;authTypeWasExplicitlyProvided;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 Rt(t.modelProvidersConfig),this.onModelChange=t.onModelChange,this._generationConfig={...t.generationConfig||{}},this.generationConfigSources=t.generationConfigSources||{},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,hasManualCredentials:this.hasManualCredentials,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(t){this.currentAuthType=t.currentAuthType,this._generationConfig=t.generationConfig,this.generationConfigSources=t.generationConfigSources,this.strictModelProviderSelection=t.strictModelProviderSelection,this.hasManualCredentials=t.hasManualCredentials,this.activeRuntimeModelSnapshotId=t.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||Kn}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModelsForAuthType(this.currentAuthType):[]}getAvailableModelsForAuthType(t){return this.modelRegistry.getModelsForAuthType(t)}getAllConfiguredModels(t){let n=t&&t.length>0?t:Object.values(q),o=new Set,r=[];for(let a of n)o.has(a)||(o.add(a),r.push(a));let i=this.getRuntimeModelOption(),s=[];for(let a of r)i&&i.authType===a&&s.push(i),s.push(...this.modelRegistry.getModelsForAuthType(a));return s}hasModel(t,n){return this.modelRegistry.hasModel(t,n)}getResolvedModel(t,n){return this.modelRegistry.getModel(t,n)}isManagedMatildaResolvedModel(t){return t?.id===Ht&&t?.envKey===zn&&t?.baseUrl===Wn&&t?.generationConfig?.openAIRequestProfile==="matilda-code"}isManagedMatildaModel(t){let n=t.trim();return!n||!this.currentAuthType?!1:this.isManagedMatildaResolvedModel(this.modelRegistry.getModel(this.currentAuthType,n))}getPublicModelId(t){return this.isManagedMatildaModel(t)?Ht:t}getModelDisplayName(t){return this.isManagedMatildaModel(t)?Vn:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,t)?.name??t:t}async setModel(t,n){if(this.currentAuthType&&this.modelRegistry.hasModel(this.currentAuthType,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){this.shouldUpdateModelDerivedDefault("modalities")&&(this._generationConfig.modalities=$e(t),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=Ge(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.getModel(t,n,o?.baseUrl);if(!a)throw new Error(`Model '${n}' not found for authType '${t}'`);let d=i.generationConfig.model||"",c=!s&&d?this.modelRegistry.getModel(t,d,i.generationConfig.baseUrl)??this.modelRegistry.getModel(t,d):void 0,l=!s&&!!i.generationConfig.apiKey&&!!a.envKey&&c?.envKey===a.envKey&&c.baseUrl===a.baseUrl,p=l?i.generationConfig.apiKey:void 0,u=l?i.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(a),!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,u&&(this.generationConfigSources.apiKey=e.deepClone(u))),this.activeRuntimeModelSnapshotId=void 0,this.onModelChange&&await this.onModelChange(t)}catch(s){throw this.rollbackToStateSnapshot(i),s}}buildRuntimeModelSnapshotId(t,n){return`${bt}${t}|${n}`}extractRuntimeModelSnapshotId(t){if(t.startsWith(bt))return this.runtimeModelSnapshots.has(t)?t:void 0;if(this.runtimeModelSnapshots.has(t))return t}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}mergeSettingsGenerationConfig(t){if(t)for(let n of vt)!(n in this._generationConfig)&&n in t&&(this._generationConfig[n]=t[n],this.generationConfigSources[n]={kind:"settings",detail:`model.generationConfig.${n}`})}updateCredentials(t,n){(t.apiKey||t.baseUrl||t.model)&&(this.hasManualCredentials=!0,this.clearProviderSourcedConfig()),t.apiKey&&(this._generationConfig.apiKey=t.apiKey,this.generationConfigSources.apiKey={kind:"programmatic",detail:"updateCredentials"}),t.baseUrl&&(this._generationConfig.baseUrl=t.baseUrl,this.generationConfigSources.baseUrl={kind:"programmatic",detail:"updateCredentials"}),t.model&&(this._generationConfig.model=t.model,this.generationConfigSources.model={kind:"programmatic",detail:"updateCredentials"}),this.strictModelProviderSelection=!1,this._generationConfig.apiKeyEnvKey=void 0,n&&this.mergeSettingsGenerationConfig(n),this.syncRuntimeModelSnapshotWithCredentials()}syncRuntimeModelSnapshotWithCredentials(){let t=this.currentAuthType,{model:n,apiKey:o,baseUrl:r}=this._generationConfig;if(!(!n||!t||!o||!r)&&!this.modelRegistry.hasModel(t,n,r))if(this.activeRuntimeModelSnapshotId&&this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)){let i=this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);i.apiKey=o,i.baseUrl=r,i.modelId=n;let s=this.buildRuntimeModelSnapshotId(i.authType,i.modelId);s!==i.id&&(this.runtimeModelSnapshots.delete(i.id),i.id=s,this.runtimeModelSnapshots.set(s,i),this.activeRuntimeModelSnapshotId=s),i.createdAt=Date.now()}else this.detectAndCaptureRuntimeModel()}clearProviderSourcedConfig(){for(let t of Mt)this.generationConfigSources[t]?.kind==="modelProviders"&&(delete this._generationConfig[t],delete this.generationConfigSources[t])}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=!1}applyResolvedModelDefaults(t){if(this.strictModelProviderSelection=!0,this.hasManualCredentials=!1,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=Ms.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=t.generationConfig;for(let o of vt)this._generationConfig[o]=n[o],this.generationConfigSources[o]={kind:"modelProviders",authType:t.authType,modelId:t.id,detail:`generationConfig.${o}`};n.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=Ge(t.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=$e(t.id),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"})}syncAfterAuthRefresh(t,n){this.strictModelProviderSelection=!1;let o=this.currentAuthType;this.currentAuthType=t;let r=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,i=n?this.modelRegistry.getModel(t,n,r)??this.modelRegistry.getModel(t,n):void 0;if(i){let g=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==i.envKey||this._generationConfig.baseUrl!==i.baseUrl),h=o===t&&this._generationConfig.model===n&&!g,m=h?this._generationConfig.apiKey:void 0,C=h&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,T=this.generationConfigSources.baseUrl,S=h&&!!this._generationConfig.baseUrl&&(T?.kind==="cli"||T?.kind==="env"||T?.kind==="settings"),R=S?this._generationConfig.baseUrl:void 0,O=S&&T?{...T}:void 0;this.applyResolvedModelDefaults(i),h&&!this._generationConfig.apiKey&&m&&(this._generationConfig.apiKey=m,C&&(this.generationConfigSources.apiKey=C)),R&&(this._generationConfig.baseUrl=R,O&&(this.generationConfigSources.baseUrl=O)),this.strictModelProviderSelection=!0,this.activeRuntimeModelSnapshotId=void 0;return}let s=this.generationConfigSources.apiKey,a=this.generationConfigSources.baseUrl,d=this._generationConfig.apiKey&&s?.kind!=="modelProviders"||this._generationConfig.baseUrl&&a?.kind!=="modelProviders";if(!(o!==t)&&(n===void 0||!this.modelRegistry.hasModel(t,n))&&(this.hasManualCredentials||d)){n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (preserved credentials)"}));return}let p=this.modelRegistry.getDefaultModelForAuthType(t);if(p){this.applyResolvedModelDefaults(p),this.activeRuntimeModelSnapshotId=void 0;return}n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (no default model)"}))}setOnModelChange(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.hasModel(s,t,o)){this.clearRuntimeModelSnapshotForAuthType(s);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let d=this.buildRuntimeModelSnapshotId(s,t),c={id:d,authType:s,modelId:t,apiKey:n,baseUrl:o,apiKeyEnvKey:r,generationConfig:i,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(d,c),this.activeRuntimeModelSnapshotId=d,this.cleanupOldRuntimeModelSnapshots(),d}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.hasManualCredentials=!0,this._generationConfig.model=n.modelId,this.generationConfigSources.model={kind:"programmatic",detail:"runtimeModelSwitch"},n.apiKey&&(this._generationConfig.apiKey=n.apiKey,this.generationConfigSources.apiKey=n.sources.apiKey||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.baseUrl&&(this._generationConfig.baseUrl=n.baseUrl,this.generationConfigSources.baseUrl=n.sources.baseUrl||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.apiKeyEnvKey&&(this._generationConfig.apiKeyEnvKey=n.apiKeyEnvKey),n.generationConfig&&Object.assign(this._generationConfig,n.generationConfig),this.onModelChange&&await this.onModelChange(n.authType)}catch(r){throw this.rollbackToStateSnapshot(o),r}}getRuntimeModelOption(){let 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)}};f();import{readFileSync as Js}from"node:fs";import{join as Xs}from"node:path";f();f();import{randomBytes as ks,createHash as _s}from"node:crypto";import{setTimeout as ws}from"node:timers/promises";var xs="urn:ietf:params:oauth:grant-type:device_code";function or(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}function En(){let e=ks(32).toString("base64url"),t=_s("sha256").update(e).digest("base64url");return{codeVerifier:e,codeChallenge:t}}function Ee(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 Is=15e3;async function Sn(e){let t=e.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",t);if(n.protocol!=="https:"&&!or(n.hostname))throw new Error(`Refusing OAuth discovery over insecure transport: ${n.origin}`);let o=await fetch(n,{headers:{accept:"application/json"},signal:AbortSignal.timeout(Is)});if(!o.ok)throw new Error(`OAuth discovery failed (${o.status}) for ${n.origin}`);let r=await o.json();if(!r.issuer||!r.authorization_endpoint||!r.token_endpoint)throw new Error(`OAuth discovery document missing required fields for ${n.origin}`);return{issuer:r.issuer,authorization_endpoint:r.authorization_endpoint,token_endpoint:r.token_endpoint,device_authorization_endpoint:r.device_authorization_endpoint}}var Os=15e3,An="Device code expired: restart the sign-in";async function Be(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:ir(AbortSignal.timeout(Os),n.signal)})}catch(i){throw sr(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 kt(e,t,n={}){let o=await fetch(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:xs,client_id:t.clientId,device_code:t.deviceCode}),signal:n.signal});if(o.ok)return{kind:"authorized",tokens:Ee(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 rr(e,t,n={}){let o=t.interval*1e3;try{for(;Date.now()<t.expiresAt;){await ws(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 kt(e,t,{signal:ir(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(An);case"access_denied":throw new Error("User denied the authorization request");default:throw new Error(`Device flow error: ${i.error}`)}}}}catch(r){throw sr(r,n.signal)?new Error(An):r}throw new Error(An)}function ir(e,t){return t?AbortSignal.any([e,t]):e}function sr(e,t){return!t?.aborted&&e instanceof Error&&e.name==="TimeoutError"}f();import{randomBytes as Ps}from"node:crypto";import{promises as Se,openSync as Ds,closeSync as Ns,unlinkSync as lr,statSync as Ls}from"node:fs";import{dirname as Us}from"node:path";var ar=new Map,Fs=2e4,Gs=3e4,$s=50;function bn(e,t={}){let n=async()=>{try{let s=await Se.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 Se.mkdir(Us(e),{recursive:!0});let d=`${e}.${process.pid}.${Ps(4).toString("hex")}.tmp`;try{await Se.writeFile(d,JSON.stringify(s,null,2),{mode:384}),a?.throwIfAborted(),await Se.rename(d,e)}catch(c){throw await Se.rm(d,{force:!0}).catch(()=>{}),c}await Se.chmod(e,384).catch(()=>{})},r=(s,a={})=>{let c=(ar.get(e)??Promise.resolve()).then(async()=>{a.signal?.throwIfAborted();let l=await n(),p=!1;for(let[u,g]of Object.entries(s)){if(g===null){if(!(u in l))continue;delete l[u]}else{if(l[u]===g)continue;l[u]=g}p=!0}p&&await o(l,a.signal),a.onCommit?.()});return ar.set(e,c.catch(()=>{})),c};return{store:{async get(s){return(await n())[s]??null},set:(s,a,d)=>r({[s]:a},d),remove:(s,a)=>r({[s]:null},a)},lock:Bs(`${e}.lock`,t.lockTimeoutMs??Fs),update:r}}function Bs(e,t){let n=Promise.resolve();return o=>{let r=n.then(async()=>{await Ks(e,t);try{return await o()}finally{js(e)}});return n=r.then(()=>{},()=>{}),r}}async function Ks(e,t){let n=Date.now()+t;for(;;)try{Ns(Ds(e,"wx"));return}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-Ls(e).mtimeMs>Gs){lr(e);continue}}catch{continue}if(Date.now()>n)throw Object.assign(new Error(`Timed out acquiring credential lock at ${e}`),{code:"ETIMEDOUT"});await zs($s)}}function js(e){try{lr(e)}catch{}}function zs(e){return new Promise(t=>setTimeout(t,e))}f();var be=class extends Error{code="invalid_grant";constructor(t="Refresh token is no longer valid \u2014 sign in again."){super(t),this.name="InvalidGrantError"}};function Rn(e){let t=e.storageKey??"default",n=e.fetchImpl??fetch,o=e.expirySkewMs??6e4,r=e.refreshTimeoutMs??15e3,i=null,s=async()=>{let c=await e.store.get(t);if(!c)return null;try{let l=JSON.parse(c);return l.accessToken?l:null}catch{return null}},a=c=>c.expiresAt-Date.now()>o,d=c=>e.lock(async()=>{let l=await s()??c;if(l.accessToken!==c.accessToken&&a(l))return l.accessToken;if(!l.refreshToken)throw new be("No refresh token available \u2014 sign in again.");let p;try{let g=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:l.refreshToken}),signal:AbortSignal.timeout(r)});if(!g.ok){let h=await g.text().catch(()=>"");throw g.status>=400&&g.status<500&&Vs(h)==="invalid_grant"?(await e.store.remove(t),new be):Object.assign(new Error(`Token refresh failed (${g.status})`),{status:g.status})}p=await g.json()}catch(g){throw g?.name==="TimeoutError"?Object.assign(new Error(`Token refresh timed out after ${r} ms`),{code:"ETIMEDOUT",cause:g}):g}let u=Ee(p,l);return await e.store.set(t,JSON.stringify(u)),u.accessToken});return{async getAccessToken(c){let l=await s();if(!l)throw new be("Not signed in.");return!c?.forceRefresh&&a(l)?l.accessToken:(i||(i=d(l).finally(()=>{i=null})),i)}}}function Vs(e){try{return JSON.parse(e).error}catch{return}}f();import{createServer as Ws}from"node:http";import{randomBytes as qs}from"node:crypto";async function _t(e){if(e.transport.kind==="device")return Hs(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=m=>e.onEvent?.(m),{codeVerifier:n,codeChallenge:o}=En(),r=qs(16).toString("hex"),i=e.timeoutMs??5*60*1e3,s=e.transport.successRedirect,a=e.transport.port;t({type:"state",status:"idle"});let d,c,l=new Promise((m,C)=>{d=m,c=C});l.catch(()=>{});let p=Ws((m,C)=>{let T=new URL(m.url??"/","http://127.0.0.1");if(T.pathname!=="/callback"){C.writeHead(404).end();return}let S=T.searchParams.get("error"),R=T.searchParams.get("state"),O=T.searchParams.get("code");if(S){let F=T.searchParams.get("error_description"),_=F?`OAuth error: ${S} (${F})`:`OAuth error: ${S}`;C.writeHead(400,{"content-type":"text/plain; charset=utf-8"}).end(`Sign-in failed: ${S}
16
+ `,()=>c(new Error(_)));return}if(R!==r){C.writeHead(400).end("State mismatch"),c(new Error("OAuth state mismatch"));return}if(!O){C.writeHead(400).end("Missing authorization code");return}Ys(C,s,()=>d(O))}),u=await new Promise((m,C)=>{p.once("error",C),p.listen(a??0,"127.0.0.1",()=>{m(p.address().port)})}),g=setTimeout(()=>c(new Error("Login timed out \u2014 the browser never reached the local callback. The hosted success page is not a completed sign-in.")),i),h=()=>c(new Error("Login aborted"));e.signal?.addEventListener("abort",h,{once:!0}),e.signal?.aborted&&h();try{e.signal?.throwIfAborted();let m=`http://127.0.0.1:${u}/callback`,C=new URL(e.metadata.authorization_endpoint);C.searchParams.set("client_id",e.clientId),C.searchParams.set("response_type","code"),C.searchParams.set("redirect_uri",m),C.searchParams.set("code_challenge",o),C.searchParams.set("code_challenge_method","S256"),C.searchParams.set("state",r),C.searchParams.set("prompt","select_account"),C.searchParams.set("scope",e.scope??"openid offline_access");let T=C.toString();t({type:"authorize_url",url:T}),t({type:"state",status:"awaiting_user"}),e.openBrowser&&await e.openBrowser(T);let S=await l;await ur(p),t({type:"state",status:"exchanging"});let R=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:m}),signal:e.signal});if(!R.ok){let F=await R.text().catch(()=>"");throw new Error(`Token exchange failed (${R.status}): ${F}`)}let O=Ee(await R.json());return t({type:"state",status:"authenticated"}),O}catch(m){throw t({type:"state",status:"error"}),e.signal?.aborted?new Error("Login aborted"):m}finally{clearTimeout(g),e.signal?.removeEventListener("abort",h),await ur(p)}}async function Hs(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 Be(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 rr(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 ur(e){return e.listening?new Promise(t=>{e.close(()=>t()),e.closeAllConnections()}):Promise.resolve()}function Ys(e,t,n){e.writeHead(302,{location:t}).end(n)}var ee="matilda-code",dr="matilda-desktop",kn="openid profile email offline_access",Ke="MATILDA_API_KEY",Qs="matilda";function te(e){return e.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function pr(){return Xs(Xe.getGlobalMatildaDir(),"matilda-auth.json")}function wt(){return bn(pr())}function Zs(e){return e==="desktop"}function ze(e){return e?.clientId?e.clientId:Zs(e?.channel)?dr:ee}function je(e){return`matilda:${e}`}function xt(e){return`${je(e)}:refresh-rejected`}function Ve(e){return e===ee?[je(e),Qs]:[je(e)]}function ea(){try{let e=Js(pr(),"utf8");return JSON.parse(e)}catch{return{}}}function vn(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 ta(e,t){return te(e)===te(t)}function na(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 _n(e,t){let n=na(e.idToken);return{accessToken:e.accessToken,accessTokenExpiresAt:e.expiresAt,refreshToken:e.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:t}}var cr=new Map;async function We(e){let t=cr.get(e);if(t)return t;try{let n=await Sn(e);return cr.set(e,n),n}catch{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 ce(e){try{let t=ea(),n=ze(e);for(let o of Ve(n)){let r=vn(t[o]);if(r)return r}return null}catch{return null}}function fr(e){let t=ce(e);return!t||e?.baseUrl&&!ta(t.baseUrl,e.baseUrl)?null:t}function Dd(e){return fr(e)!==null}async function oa(e){let t=ze(e),n=wt().store;for(let o of Ve(t))await n.remove(o);await n.set(xt(t),"1"),delete process.env[Ke]}function ra(e){return e instanceof Error?e.code==="invalid_grant"||e.name==="InvalidGrantError"?!0:e.message==="Token refresh failed (401)":!1}function Re(e){Mn({authStage:e.authStage,authOutcome:e.authOutcome,occurrenceCount:e.occurrenceCount},{baseUrl:e.baseUrl,token:e.token}).catch(()=>{})}async function gr(e,t,n={}){let o=ze(t),r=je(o),i={[r]:JSON.stringify(e),[xt(o)]:null};for(let s of Ve(o))s!==r&&(i[s]=null);await wt().update(i,{signal:n.signal,onCommit:()=>{process.env[Ke]=e.accessToken}})}async function ia(e){let t=ze(e),n=wt().store;for(let o of Ve(t))await n.remove(o);await n.remove(xt(t)),delete process.env[Ke]}function Nd(e){let t=ce(e);return t?{authenticated:!0,userId:t.userId,email:t.email,displayName:t.displayName,baseUrl:t.baseUrl,accessTokenExpiresAt:t.accessTokenExpiresAt}:{authenticated:!1}}async function Ld(e){let t={channel:e?.channel,clientId:e?.clientId},n=ce(t);if(n?.accessToken){let o=te(n.baseUrl);await fetch(`${o}/api/auth/logout`,{method:"POST",headers:{authorization:`Bearer ${n.accessToken}`,"content-type":"application/json"},body:JSON.stringify(n.refreshToken?{refreshToken:n.refreshToken}:{}),signal:e?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}await ia(t)}async function wn(e){let t=ze(e),n=je(t),o=fr({baseUrl:e?.baseUrl,channel:e?.channel,clientId:t});if(!o)return e?.fallbackAccessToken??process.env[Ke]??"";let r=te(o.baseUrl),i=await We(r),{store:s,lock:a}=wt(),d=sa(s,a,i.token_endpoint,o.baseUrl,t,n,e?.signal),c=t===ee&&(!!e?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=3e5),l;try{l=await d.getAccessToken({forceRefresh:e?.forceRefresh})}catch(p){throw c&&Re({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"}),t===dr&&ra(p)&&await oa({channel:e?.channel,clientId:t}),p}return c&&Re({baseUrl:o.baseUrl,token:l,authStage:"refresh",authOutcome:"succeeded"}),process.env[Ke]=l,l}async function Ud(e){await wn(e);let t=ce(e);if(!t)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return t}function sa(e,t,n,o,r,i,s){let a=Ve(r);return Rn({tokenEndpoint:n,clientId:r,store:{get:async l=>{let p=l===i?a:[l],u=null;for(let h of p)if(u=vn(await e.get(h)),u)break;if(!u?.accessToken)return null;let g={accessToken:u.accessToken,refreshToken:u.refreshToken,expiresAt:u.accessTokenExpiresAt};return JSON.stringify(g)},set:async(l,p)=>{let u=JSON.parse(p),g=l===i?a:[l],h={};for(let C of g){let T=vn(await e.get(C));if(T){h=T;break}}let m={...h,accessToken:u.accessToken,accessTokenExpiresAt:u.expiresAt,refreshToken:u.refreshToken??h.refreshToken??"",baseUrl:h.baseUrl??o};await e.set(i,JSON.stringify(m)),await e.remove(xt(r));for(let C of a)C!==i&&await e.remove(C)},remove:async l=>{let p=l===i?a:[l];for(let u of p)await e.remove(u)}},storageKey:i,lock:t,fetchImpl:(l,p)=>{let u=[p?.signal,s].filter(g=>g instanceof AbortSignal);return fetch(l,{...p,signal:u.length>1?AbortSignal.any(u):u[0]})},expirySkewMs:3e5})}function aa(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&qn()}async function Fd(e){let t=te(e.baseUrl),n=await We(t),o="",r=0,i=0,s={},a=p=>{s[p]=(s[p]??0)+1},c=await(p=>(r+=1,_t({metadata:n,clientId:ee,scope:p,transport:{kind:"loopback",successRedirect:`${t}/api/auth/oauth/success?client_id=${encodeURIComponent(ee)}`},signal:e.signal,onEvent:u=>{u.type==="authorize_url"&&(o=u.url,e.onAuthorizeUrl?.(u.url)),u.type==="state"&&u.status==="exchanging"&&(i+=1)},openBrowser:async u=>{if(e.openBrowser===!1||!aa()){a("skipped");return}try{let{default:g}=await import("./open-QQ7FWG4A.js");(await g(u)).once("error",()=>{}),a("succeeded")}catch{a("failed")}}})))(kn),l=_n(c,e.baseUrl);await gr(l),Re({baseUrl:e.baseUrl,token:l.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:r});for(let[p,u]of Object.entries(s))Re({baseUrl:e.baseUrl,token:l.accessToken,authStage:"browser_opened",authOutcome:p,occurrenceCount:u});return i>0&&Re({baseUrl:e.baseUrl,token:l.accessToken,authStage:"callback_received",authOutcome:"succeeded",occurrenceCount:i}),Re({baseUrl:e.baseUrl,token:l.accessToken,authStage:"token_persisted",authOutcome:"succeeded"}),{...l,authorizeUrl:o}}async function Gd(e){let t=te(e.baseUrl),n=await We(t),o=await _t({metadata:n,clientId:ee,scope:kn,transport:{kind:"device"},signal:e.signal,onEvent:i=>{i.type==="user_code"&&e.onDeviceCode({userCode:i.userCode,verificationUri:i.verificationUri,verificationUriComplete:i.verificationUriComplete})}}),r=_n(o,e.baseUrl);return await gr(r),r}async function $d(e){let t=await We(te(e.baseUrl));if(!t.device_authorization_endpoint)throw new Error("The authorization server does not offer device sign-in");return Be(t.device_authorization_endpoint,{clientId:ee,scope:kn},{signal:e.signal})}async function Bd(e){let t=await We(te(e.baseUrl)),n=await kt(t.token_endpoint,{clientId:ee,deviceCode:e.deviceCode},{signal:e.signal});return n.kind==="authorized"?{kind:"authorized",credentials:_n(n.tokens,e.baseUrl)}:n}f();f();f();function ve(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="object"&&"message"in e.error}function It(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}function zd(e){let t=n=>n.includes("Quota exceeded for quota metric 'Gemini")&&n.includes("Pro Requests'");if(typeof e=="string")return t(e);if(It(e))return t(e.message);if(ve(e))return t(e.error.message);if(e&&typeof e=="object"&&"response"in e){let n=e;if(n.response&&n.response.data){if(typeof n.response.data=="string")return t(n.response.data);if(typeof n.response.data=="object"&&n.response.data!==null&&"error"in n.response.data){let o=n.response.data;return t(o.error?.message||"")}}}return!1}function Vd(e){return typeof e=="string"?e.includes("Quota exceeded for quota metric"):It(e)?e.message.includes("Quota exceeded for quota metric"):ve(e)?e.error.message.includes("Quota exceeded for quota metric"):!1}f();function mr(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:la(e.error);if(s!==null&&s>0){let l=Math.min(e.retryAfterMaxDelayMs??e.maxDelayMs,2147483647),p=Math.min(s,l);return Math.max(r,p)}let a=e.jitterRatio??0;if(a<=0)return r;let d=e.random??Math.random,c=r*a*(d()*2-1);return Math.min(Math.max(0,r+c),n)}function la(e){let t=hr(e,"retry-after")??ua(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 hr(e,t){if(!ca(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 ua(e,t){return da(e)?hr(e.response,t):null}function ca(e){return typeof e=="object"&&e!==null&&"headers"in e&&e.headers!=null}function da(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 pa=new Set([429,503,1302,1305]);function xn(e,t){if(In(e))return!1;let n=ga(e);return n===null?!1:!!(pa.has(n)||t&&t.includes(n))}function In(e){return fa(e)==="insufficient_quota"}function fa(e){let t=yr(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 Cr(e){let t=Y(e),n=yr(e),o=Tr(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 Zd(e,t){return mr({attempt:e,initialDelayMs:t.initialDelayMs,maxDelayMs:t.maxDelayMs,retryAfterMode:"minimum",retryAfterMaxDelayMs:t.maxDelayMs,error:t.error})}function ga(e){if(ve(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(ve(o)){let r=Number(o.error.code);if(Number.isFinite(r)&&r>0)return r}}catch{}}if(It(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 Y(e)??null}function yr(e){for(let t of ma(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,d=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||d!==void 0)return{code:s,message:a,requestId:d}}return ve(e)?{code:e.error.code,message:e.error.message}:null}function ma(e){let t=Tr(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 Tr(e){return e instanceof Error?e.message:typeof e=="string"?e:null}function ha(e,t={}){if(Ca(e))return{kind:"abort",diagnosis:"fail-fast",reason:"aborted"};let n=Cr(e),o=n.statusCode,r=ba(e),i=n.providerCode??r.providerCode,s=n.providerMessage??r.providerMessage,a=n.requestId??r.requestId,d={...o!==void 0?{statusCode:o}:{},...i!==void 0?{providerCode:i}:{},...s!==void 0?{providerMessage:s}:{},...a!==void 0?{requestId:a}:{}};if(Sa(i))return{kind:"provider-business",diagnosis:"fail-fast",reason:"allocated-quota-exceeded",...d};if(In(e))return{kind:"provider-business",diagnosis:"fail-fast",reason:"insufficient-quota",...d};if(xn(e,t.extraRetryErrorCodes))return{kind:n.transport==="sse"?"sse-provider":o!==void 0?"http":"provider",diagnosis:"retryable",reason:"rate-limit",...d};let c=Ta(e);if(c!==void 0&&(o===void 0||o>=500))return{kind:"transport",diagnosis:"retryable",reason:"transport-error",transportCode:c,...o!==void 0?{statusCode:o}:{}};if(o!==void 0){let l=n.transport==="sse"?"sse-provider":"http";return o===529?{kind:l,diagnosis:"retryable",reason:"capacity-overload",...d}:o===401||o===403?{kind:l,diagnosis:"fail-fast",reason:"auth-error",...d}:o>=400&&o<500?{kind:l,diagnosis:"fail-fast",reason:"client-error",...d}:o>=500&&o<600?{kind:l,diagnosis:"retryable",reason:"server-error",...d}:{kind:l,diagnosis:"unknown",reason:"http-status",...d}}return i==="upstream_unavailable"||i==="upstream_timeout"||i==="incomplete_stream"?{kind:"sse-provider",diagnosis:"retryable",reason:"server-error",...d}:{kind:"unknown",diagnosis:"unknown",reason:"unclassified",...d}}function rp(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 Ar(e,t){return xn(e,t)||ha(e,{extraRetryErrorCodes:t}).diagnosis==="retryable"}function Ca(e){return Fn(e)?!0:e instanceof Error&&e.name==="CanceledError"}var ya=5;function Ta(e){let t=e;for(let n=0;n<=ya;n++){if(typeof t!="object"||t===null)return;let o=t.code;if(typeof o=="string"&&Aa(o))return o;t=t instanceof Error?t.cause:void 0}}function Aa(e){return Ea.has(e)}var Ea=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 Sa(e){return e==="Throttling.AllocationQuota"}function ba(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 q=(t=>(t.USE_OPENAI="openai",t))(q||{}),Ra="MATILDA_AGENT_SDK",Ot="MATILDA_API_KEY";function va(e,t){if(e.apiKey||e.apiKeyEnvKey!==Ot)return;let n=ce({channel:t});n?.accessToken&&(e.apiKey=n.accessToken,process.env[Ot]=n.accessToken)}async function Ma(e,t){if(e.apiKeyEnvKey!==Ot)return;let n=ce({channel:t});if(!n?.accessToken)return;let o;try{o=await wn({baseUrl:e.baseUrl,fallbackAccessToken:n.accessToken,channel:t})}catch(r){if(!Ar(r))throw r;o=n.accessToken}o&&(e.apiKey=o,process.env[Ot]=o)}function ka(e){return e.matildaAgentSdk===!0||process.env[Ra]==="1"}function On(e,t,n){e[t]=n}function _a(e,t){return e?.[t]}function wa(e,t,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:t,proxy:e?.getProxy()};On(i,"authType",{kind:"computed",detail:"provided by caller"}),e?.getProxy()&&On(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let d=l=>_a(o,l)??{kind:"unknown"};for(let l of Mt)n&&l in n&&!i[l]&&On(i,l,d(l));va(a,e.getChannel());let c=Er(a,s);if(!c.valid)throw new Error(c.errors.map(l=>l.message).join(`
17
+ `));return{config:a,sources:i}}function Er(e,t=!1){let n=[];if(!e.apiKey)if(t)n.push(new yt(e.authType,e.model,e.apiKeyEnvKey));else{let o=e.apiKeyEnvKey||qo(e.authType);n.push(new At({authType:e.authType,model:e.model,baseUrl:e.baseUrl,envKey:o}))}if(!e.model)if(t)n.push(new Tt(e.authType));else{let o=Ho(e.authType);n.push(new Et({authType:e.authType,envKey:o}))}return{valid:n.length===0,errors:n}}function fp(e,t,n){return wa(e,t,n).config}function xa(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 gp(e,t){yn(e,t.getOrganizationId?.(),t.getCodeCreditLimitMinor?.()),Wo(e.customHeaders),await Ma(e,t.getChannel());let n=Er(e,!1);if(!n.valid)throw new Error(n.errors.map(i=>i.message).join(`
18
+ `));let o=e.authType;if(!o)throw new Error("ContentGeneratorConfig must have an authType");let r;try{if(o==="openai")if(ka(e)){let{createMatildaAgentContentGenerator:i}=await import("./matildaAgentContentGenerator-57EIU5XE.js");r=i(e,t)}else{let{createOpenAIContentGenerator:i}=await import("./openaiContentGenerator-6PXSD3T7.js");r=i(e,t)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${o}`)}catch(i){let s=xa(i);throw s?new Error(`Matilda was updated in the background and needs to be restarted.
19
+ Please exit and restart Matilda to use the '${o}' provider.`,{cause:s}):i}return new Fe(r,t,e)}var Ia=["x-matilda-client-name","x-matilda-client-version","x-matilda-client-operating-system","x-matilda-client-architecture","x-matilda-client-distribution-channel","x-matilda-client-release-channel"],Oa=new Set([...Ia,...Un]),Pa=new Set(["VSCode","ACP","SDK","CI"]),Me="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",Da="[A-Za-z][0-9A-Za-z-]{0,23}",Sr="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",Na=new RegExp(`^${Me}(?:-${Da}(?:\\.${Sr})+)?$`),La=63,Ua=new RegExp(`^${Me}$`),Fa=new RegExp(`^${Me}-preview\\.(?:0|[1-9]\\d{0,11})$`),Ga=new RegExp(`^${Me}-canary\\.(?:0|[1-9]\\d{0,11})$`),$a=new RegExp(`^${Me}-nightly\\.(?:0|[1-9]\\d{0,11})\\.[0-9A-Fa-f]{7,12}$`),Ba=new RegExp(`^${Me}-(preview|canary|nightly|development|internal)(?:\\.${Sr})+$`);function Ka(e){return e==="desktop"?"desktop":e===void 0||Pa.has(e)?"code_cli":"unknown"}function ja(e){if(e==="android")return"android";if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux")return"linux"}function za(e){if(e==="x64")return"x64";if(e==="arm64")return"arm64"}function Va(e){if(e===void 0)return"npm";if(e==="desktop")return"direct-download";if(e==="VSCode")return"vscode-marketplace"}function Wa(e,t){if(t==="desktop")return"matilda-desktop";if(e==="VSCode")return"matilda-vscode";if(t==="code_cli")return"matilda-code"}function qa(e){if(typeof e=="string"&&!(e.length>La||!Na.test(e)))return e}function Ha(e){if(e!==void 0)return Ua.test(e)?"stable":Fa.test(e)?"preview":Ga.test(e)?"canary":$a.test(e)?"nightly":Ba.exec(e)?.[1]}function br(e,t=process.platform,n=process.arch){let o=e.getChannel?.(),r=Ka(o),i=qa(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:e.getCliVersion?.()),s=Ha(i),a=ja(t),d=za(n),c=Va(o),l=Wa(o,r);return{...l?{"x-matilda-client-name":l}:{},...i?{"x-matilda-client-version":i}:{},...a?{"x-matilda-client-operating-system":a}:{},...d?{"x-matilda-client-architecture":d}:{},...c?{"x-matilda-client-distribution-channel":c}:{},...s?{"x-matilda-client-release-channel":s}:{}}}function Ap(e){let t=e.toLowerCase();return Oa.has(t)||t.startsWith("x-matilda-reported-")}function Ya(e){let t=e??Qo;try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let o=n.hostname.toLowerCase();return o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="core-api.matilda"}catch{return!1}}function Ep(e,t=e.apiKey){return e.authType==="openai"&&!!t&&Ya(e.baseUrl)}var Ja=3e3,qe=1,Xa=24*60*60*1e3,Rr=20,vr=999,Qa=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"]),Za=new Set(["ENOTFOUND","EAI_AGAIN"]),el=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),tl=new Set(["ABORT_ERR","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT"]),nl=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]);function ol(e){return`${new URL(e).origin}/api/client-events`}function rl(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 Pn(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??Ja);try{let a=await r(ol(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(rl(e)),signal:i.signal});return a.ok?!0:(Qe.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`),!1)}catch{return!1}finally{clearTimeout(s)}}async function Mn(e,t){let n=typeof e.occurrenceCount=="number"&&Number.isFinite(e.occurrenceCount)?Math.max(1,Math.min(Math.floor(e.occurrenceCount),vr)):1;return Pn({eventType:"auth_funnel",authStage:e.authStage,authOutcome:e.authOutcome,occurrenceCount:n},t)}function Mr(){try{let e=ne.readFileSync(wr(),"utf8"),t=JSON.parse(e);return t.schemaVersion!==qe||!Array.isArray(t.failures)?void 0:{schemaVersion:qe,failures:t.failures.filter(il)}}catch{return}}function il(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 kr(e){let t=wr();if(e.failures.length===0){try{ne.rmSync(t,{force:!0})}catch{}return}try{ne.mkdirSync(Pt.dirname(t),{recursive:!0}),ne.writeFileSync(t,`${JSON.stringify(e)}
20
+ `,"utf8")}catch{}}function _r(e,t){return e.filter(n=>t-n.lastObservedAtMs<=Xa).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-Rr)}function sl(e){let t=br(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 al(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 ll(e){if(!(!e||typeof e!="object"))for(let t of["status","statusCode"]){let n=e[t];if(typeof n=="number")return n}}function ul(e,t){let n=al(e);if(n&&Qa.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&Za.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&el.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&tl.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&nl.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=ll(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 cl(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 kp(e,t){let n=sl(t.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=ul(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=Mr()??{schemaVersion:qe,failures:[]},a=_r(s.failures,r),d=cl(a,i);if(d>=0){let c=a[d];a[d]={...c,occurrenceCount:Math.min(c.occurrenceCount+1,vr),lastObservedAtMs:r}}else a.push(i);return kr({schemaVersion:qe,failures:a.slice(-Rr)}),!0}async function _p(e){let t=Mr();if(!t)return;let n=_r(t.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await Pn({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}}kr({schemaVersion:qe,failures:o})}function wr(){return Pt.join(Xe.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var Ir=(n=>(n.GCP="gcp",n.LOCAL="local",n))(Ir||{}),Dg="local",Ng="http://localhost:4317";f();fe();var pl=new Set(["service.version","service.instance.id","session.id"]);function de(e,t){Qe.warn(e),t?.push(e)}function Or(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(),d;try{d=decodeURIComponent(s)}catch{de(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,t),d=s}let c;try{c=decodeURIComponent(a)}catch{de(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${d}", using raw value`,t),c=a}n[d]=c}return n}function Dn(e,t,n){for(let o of pl)o in e&&(de(`${t} cannot override reserved key "${o}"; ignoring`,n),delete e[o]);return e}function Pr(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 He(e){if(e!==void 0)return e==="true"||e==="1"}function xr(e){if(e!==void 0){if(e==="local"||e==="local")return"local";if(e==="gcp"||e==="gcp")return"gcp"}}async function dl(e){let t=e.argv??{},n=e.env??{},o=e.settings??{},r=t.telemetry??He(n.MATILDA_TELEMETRY_ENABLED)??o.enabled,i=t.telemetryTarget??n.MATILDA_TELEMETRY_TARGET??o.target,s=xr(i);if(i!==void 0&&s===void 0)throw new Lt(`Invalid telemetry target: ${String(i)}. Valid values are: local, gcp`);let a=t.telemetryOtlpEndpoint??n.MATILDA_TELEMETRY_OTLP_ENDPOINT??n.OTEL_EXPORTER_OTLP_ENDPOINT??o.otlpEndpoint,d=t.telemetryOtlpProtocol??n.MATILDA_TELEMETRY_OTLP_PROTOCOL??o.otlpProtocol,c=["grpc","http"].find(K=>K===d);if(d!==void 0&&c===void 0)throw new Lt(`Invalid telemetry OTLP protocol: ${String(d)}. Valid values are: grpc, http`);let l=t.telemetryLogPrompts??He(n.MATILDA_TELEMETRY_LOG_PROMPTS)??o.logPrompts,p=He(n.MATILDA_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES)??o.includeSensitiveSpanAttributes??!1,u=t.telemetryOutfile??n.MATILDA_TELEMETRY_OUTFILE??o.outfile,g=n.MATILDA_TELEMETRY_OTLP_TRACES_ENDPOINT??n.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT??o.otlpTracesEndpoint,h=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,C=[],T=Dn(Or(n.OTEL_RESOURCE_ATTRIBUTES,C),"OTEL_RESOURCE_ATTRIBUTES",C),S=Dn(Pr(o.resourceAttributes,C),"settings.telemetry.resourceAttributes",C),R={...T,...S},O=n.OTEL_SERVICE_NAME?.trim();O&&(R["service.name"]=O);let F=Object.keys(R).length?R:void 0,_=He(n.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??o.metrics?.includeSessionId??!1;return{enabled:r,target:s,otlpEndpoint:a,otlpProtocol:c,otlpTracesEndpoint:g,otlpLogsEndpoint:h,otlpMetricsEndpoint:m,logPrompts:l,includeSensitiveSpanAttributes:p,outfile:u,resourceAttributes:F,metrics:{includeSessionId:_},resourceAttributeWarnings:C.length?C:void 0}}export{Gr as a,qn as b,qr as c,sn as d,me as e,it as f,$r as g,Br as h,mo as i,pt as j,Ko as k,Ei as l,Ue as m,mu as n,So as o,fn as p,gn as q,ki as r,He as s,xr as t,dl as u,Te as v,Ct as w,Ki as x,mn as y,ji as z,_o as A,zi as B,Vi as C,wo as D,Wi as E,xo as F,Io as G,Oo as H,qi as I,Hi as J,ls as K,us as L,cs as M,ds as N,ps as O,fs as P,gs as Q,ms as R,hs as S,Qo as T,kc as U,br as V,Ap as W,Ep as X,Pn as Y,Mn as Z,kp as _,_p as $,Ir as aa,Dg as ba,Ng as ca,sc as da,yn as ea,Wo as fa,ac as ga,pc as ha,fc as ia,gc as ja,mc as ka,hc as la,Cc as ma,St as na,yc as oa,Rs as pa,Ge as qa,$e as ra,bt as sa,Rc as ta,er as ua,Rt as va,vt as wa,$c as xa,Bc as ya,nr as za,pr as Aa,ce as Ba,Dd as Ca,ra as Da,gr as Ea,ia as Fa,Nd as Ga,Ld as Ha,wn as Ia,Ud as Ja,aa as Ka,Fd as La,Gd as Ma,$d as Na,Bd as Oa,ve as Pa,It as Qa,zd as Ra,Vd as Sa,mr as Ta,la as Ua,xn as Va,In as Wa,fa as Xa,Cr as Ya,Zd as Za,ha as _a,rp as $a,Ar as ab,q as bb,wa as cb,Er as db,fp as eb,gp as fb};
21
+ /**
22
+ * @license
23
+ * Copyright 2025 Google LLC
24
+ * SPDX-License-Identifier: Apache-2.0
25
+ */
26
+ /**
27
+ * @license
28
+ * Copyright 2026 Matilda Team
29
+ * SPDX-License-Identifier: Apache-2.0
30
+ */
31
+ /**
32
+ * @license
33
+ * Copyright 2025 Matilda
34
+ * SPDX-License-Identifier: Apache-2.0
35
+ */
36
+ /**
37
+ * @license
38
+ * Copyright 2026 Matilda
39
+ * SPDX-License-Identifier: Apache-2.0
40
+ */
41
+ /**
42
+ * @license
43
+ * Copyright 2025 Matilda Team
44
+ * SPDX-License-Identifier: Apache-2.0
45
+ */
46
+ /**
47
+ * @license
48
+ * Copyright 2026 Maincode
49
+ * SPDX-License-Identifier: Apache-2.0
50
+ *
51
+ * Low-level OAuth primitives for core-auth's unified `/api/auth/oauth/*` flow
52
+ * (ADR-029): PKCE pair generation, RFC 8414 discovery, the RFC 8628 device
53
+ * grant, and refresh. Vendored (as source) from matilda-core's
54
+ * `packages/client-sdk/src/auth.ts` and extended to carry the `id_token`
55
+ * (display identity) that the higher-level flows need. Node built-ins only —
56
+ * no third-party runtime dependencies.
57
+ */
58
+ /**
59
+ * @license
60
+ * Copyright 2026 Maincode
61
+ * SPDX-License-Identifier: Apache-2.0
62
+ *
63
+ * File-backed token store + cross-process lock. The store persists a JSON map
64
+ * (`{ [key]: value }`) at 0600 so callers can key several credentials in one
65
+ * file; the lock is an O_EXCL lockfile that serialises refreshes across
66
+ * processes (the guarantee a plaintext read/modify/write can't give).
67
+ */
68
+ /**
69
+ * @license
70
+ * Copyright 2026 Maincode
71
+ * SPDX-License-Identifier: Apache-2.0
72
+ *
73
+ * Hardened access-token manager: returns a valid access token, refreshing via
74
+ * core-auth's token endpoint when expired or forced. Single-flight within the
75
+ * process, serialised across processes by the store's lock, carries a prior
76
+ * refresh token forward when the response omits one, and evicts on a terminal
77
+ * `invalid_grant` so a dead session doesn't wedge the caller in a refresh loop.
78
+ */
79
+ /**
80
+ * @license
81
+ * Copyright 2026 Maincode
82
+ * SPDX-License-Identifier: Apache-2.0
83
+ *
84
+ * Browser login orchestration: PKCE + a loopback capture server, driven off
85
+ * discovery metadata. Unlike a bare loopback helper, this emits lifecycle
86
+ * events for a UI, honours an AbortSignal, and — instead of serving its own
87
+ * HTML — 302-redirects the browser to an app-owned branded landing
88
+ * (`successRedirect`). Returns a TokenSet including the `id_token`.
89
+ */
90
+ /**
91
+ * @license
92
+ * Copyright 2026 Maincode
93
+ * SPDX-License-Identifier: Apache-2.0
94
+ *
95
+ * Node auth surface for `@maincode-ai/matilda-client-sdk/auth/node`.
96
+ * Re-exports the OAuth primitives plus the higher-level login flow, file token
97
+ * store, and hardened token manager that the CLI (`packages/core`) and the
98
+ * Electron desktop app consume.
99
+ */
100
+ /**
101
+ * @license
102
+ * Copyright 2026 Maincode
103
+ * SPDX-License-Identifier: Apache-2.0
104
+ *
105
+ * Matilda account auth for the CLI, backed by the shared client SDK.
106
+ *
107
+ * The OAuth dance (PKCE, loopback capture, code exchange, refresh, cross-process
108
+ * token locking) is owned by `@maincode-ai/matilda-client-sdk/auth/node` — the
109
+ * auth team's tested implementation of ADR-029's unified `/api/auth/oauth/*`
110
+ * flow. This module keeps ONLY the CLI-specific concerns: which endpoint, the
111
+ * on-disk credential shape the rest of the CLI already reads, and surfacing the
112
+ * authorize URL to the Ink UI. No PKCE crypto, no loopback server, no token
113
+ * exchange lives here anymore (replaced the 391-line hand-rolled beta that hit
114
+ * the divergent `/api/auth/cli/*` endpoints and stored tokens in plaintext).
115
+ */
116
+ /**
117
+ * @license
118
+ * Copyright 2026 Google LLC
119
+ * SPDX-License-Identifier: Apache-2.0
120
+ */