@maincode-ai/matilda-code 0.21.12 → 0.21.13-nightly.20261027.e00306cd3

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 (269) hide show
  1. package/chunks/agent-H5JE3RJQ.js +3 -0
  2. package/chunks/agent-headless-H2JZZ7UV.js +3 -0
  3. package/chunks/{askUserQuestion-2QI4NSFJ.js → askUserQuestion-L3WDL2T4.js} +3 -3
  4. package/chunks/ca-UBWUTZVZ.js +25 -0
  5. package/chunks/chunk-4CVGYUEL.js +3 -0
  6. package/chunks/{chunk-RNKDFE2S.js → chunk-5B2QERWR.js} +1 -1
  7. package/chunks/chunk-62GTGPTP.js +8 -0
  8. package/chunks/chunk-6365AZBW.js +56 -0
  9. package/chunks/chunk-6PFK4XTH.js +207 -0
  10. package/chunks/chunk-7ZODGQO6.js +4 -0
  11. package/chunks/chunk-DB5LMKXU.js +31 -0
  12. package/chunks/chunk-EYZPVR7N.js +13 -0
  13. package/chunks/chunk-FKHUEFMK.js +8 -0
  14. package/chunks/{chunk-6T2GIM76.js → chunk-GILXFDEG.js} +1 -1
  15. package/chunks/{chunk-VTGICC67.js → chunk-GKEUZTOB.js} +1 -1
  16. package/chunks/chunk-GSRXW64P.js +120 -0
  17. package/chunks/chunk-GT6MSEK4.js +3 -0
  18. package/chunks/chunk-HEJO7OBH.js +3 -0
  19. package/chunks/chunk-HPO2YWG4.js +78 -0
  20. package/chunks/chunk-I3CV4LOD.js +8 -0
  21. package/chunks/{chunk-DOOFGSRV.js → chunk-J3AMKDX6.js} +1 -1
  22. package/chunks/chunk-JU7QTSKS.js +14 -0
  23. package/chunks/chunk-LBQNFSZ2.js +9 -0
  24. package/chunks/chunk-LOB42ODE.js +9 -0
  25. package/chunks/chunk-LVDDFAK4.js +89 -0
  26. package/chunks/{chunk-27Q5KW3A.js → chunk-NK2QMGCC.js} +13 -13
  27. package/chunks/{chunk-YRQP3SLC.js → chunk-O7VPFJ3R.js} +1 -1
  28. package/chunks/chunk-OBE5S4GG.js +9 -0
  29. package/chunks/{chunk-CZGZ3KK7.js → chunk-ONANBLIE.js} +1 -1
  30. package/chunks/chunk-QXSBPCBA.js +8 -0
  31. package/chunks/chunk-TUKNB5CQ.js +33 -0
  32. package/chunks/chunk-UM6CLO7D.js +7 -0
  33. package/chunks/chunk-V4D3LER3.js +2615 -0
  34. package/chunks/{chunk-HYVP4472.js → chunk-V6UPUMP3.js} +1 -1
  35. package/chunks/chunk-VUJRLLGL.js +8 -0
  36. package/chunks/{chunk-MCQUPLRE.js → chunk-WTU6GSZH.js} +1 -1
  37. package/chunks/chunk-XBTBZHRC.js +8 -0
  38. package/chunks/{chunk-WV3IUPZS.js → chunk-YTB3OFTT.js} +1 -1
  39. package/chunks/chunk-ZQKABJBB.js +8 -0
  40. package/chunks/chunk-ZSGBDQXU.js +11 -0
  41. package/chunks/{computer-use-WKDNUTLD.js → computer-use-N6KGNST6.js} +1 -1
  42. package/chunks/{cron-create-F2LXM2OA.js → cron-create-4XBY5RVI.js} +1 -1
  43. package/chunks/cron-delete-BH4VP3LX.js +3 -0
  44. package/chunks/cron-list-XXRFKNGM.js +5 -0
  45. package/chunks/de-LEEHWWJ2.js +25 -0
  46. package/chunks/{devtools-5JRKK3E7.js → devtools-7YNCRYZV.js} +1 -1
  47. package/chunks/{chunk-OOEH6ZSV.js → dist-UWUWLWTO.js} +2 -2
  48. package/chunks/{edit-QQNJZ55P.js → edit-6ULTLTJQ.js} +1 -1
  49. package/chunks/{en-EJLDYIBM.js → en-LNOIHFSQ.js} +4 -4
  50. package/chunks/{enter-worktree-5X5SAMBJ.js → enter-worktree-V2VANZYJ.js} +1 -1
  51. package/chunks/enterPlanMode-75H54S3Z.js +18 -0
  52. package/chunks/{exit-worktree-SRKZBEYF.js → exit-worktree-KPB32K6P.js} +1 -1
  53. package/chunks/{exitPlanMode-WSPTGGVN.js → exitPlanMode-K7JRP22Y.js} +2 -2
  54. package/chunks/fr-4TA2AIU6.js +25 -0
  55. package/chunks/{getMachineId-bsd-ZYBNK2JG.js → getMachineId-bsd-ETKQTB6C.js} +1 -1
  56. package/chunks/{getMachineId-darwin-CM2MQGUI.js → getMachineId-darwin-AKNRWOWB.js} +1 -1
  57. package/chunks/{getMachineId-linux-SYE2KMCW.js → getMachineId-linux-2QSD7FTP.js} +1 -1
  58. package/chunks/{getMachineId-unsupported-6IHVG2XO.js → getMachineId-unsupported-UXSV7I24.js} +1 -1
  59. package/chunks/{getMachineId-win-S3J3JSUM.js → getMachineId-win-4MTFXGP3.js} +1 -1
  60. package/chunks/glob-ACAIHWST.js +22 -0
  61. package/chunks/{goal-tools-C6BSBHCF.js → goal-tools-VPFXBI6M.js} +3 -3
  62. package/chunks/{grep-MVCOBUYW.js → grep-R4K75RXS.js} +1 -1
  63. package/chunks/{ja-GGNJR7AR.js → ja-VXDMQKRW.js} +5 -5
  64. package/chunks/keychain-token-storage-7VYNARRB.js +3 -0
  65. package/chunks/ls-4ZEICYPK.js +15 -0
  66. package/chunks/{lsp-DYDK6XCS.js → lsp-4US2RIIV.js} +1 -1
  67. package/chunks/mcp-client-ZKQFYCFN.js +3 -0
  68. package/chunks/monitor-KSNFIY54.js +32 -0
  69. package/chunks/{multipart-parser-JI75T2O5.js → multipart-parser-FKHYAVGR.js} +1 -1
  70. package/chunks/notebook-edit-655ZNV6Q.js +17 -0
  71. package/chunks/openaiContentGenerator-BG3OM453.js +52 -0
  72. package/chunks/pt-WEIMCOKI.js +25 -0
  73. package/chunks/read-file-4VSUKSRB.js +3 -0
  74. package/chunks/ripGrep-PNALN2GG.js +3 -0
  75. package/chunks/ru-WFLK34ZL.js +25 -0
  76. package/chunks/scheduler-AVYCIBEK.js +8 -0
  77. package/chunks/send-message-ND2SRKX5.js +8 -0
  78. package/chunks/shell-GUHQNOMZ.js +3 -0
  79. package/chunks/{skill-HZPFEAPF.js → skill-AB2X2DTC.js} +1 -1
  80. package/chunks/src-LZEU4AYF.js +5 -0
  81. package/chunks/symbol-search-VICSUEZH.js +19 -0
  82. package/chunks/{syntheticOutput-432LXITX.js → syntheticOutput-Z7DQKMRI.js} +1 -1
  83. package/chunks/task-create-BQ73FRTH.js +3 -0
  84. package/chunks/{task-detach-XMSJ3HBM.js → task-detach-JCHSLUOR.js} +1 -1
  85. package/chunks/task-list-6ESRFO5F.js +9 -0
  86. package/chunks/{task-stop-NTS62FLG.js → task-stop-74H2CPAJ.js} +1 -1
  87. package/chunks/{task-update-AR26UFYZ.js → task-update-R3BN6KPQ.js} +1 -1
  88. package/chunks/{team-create-PYXFVIR5.js → team-create-UTKRPUPZ.js} +3 -3
  89. package/chunks/team-delete-PCCGTLGL.js +8 -0
  90. package/chunks/todoWrite-BZI75DFV.js +3 -0
  91. package/chunks/{tool-search-RKZDSRYS.js → tool-search-FJ5MAPQ6.js} +1 -1
  92. package/chunks/{web-fetch-VW3SVDQ6.js → web-fetch-DEUGZQZS.js} +17 -17
  93. package/chunks/{web-search-XQUIZARL.js → web-search-PUUIEFJO.js} +3 -3
  94. package/chunks/{workflow-YXNXDRWZ.js → workflow-CBADL3IM.js} +2 -2
  95. package/chunks/write-file-QGCL2AJL.js +15 -0
  96. package/cli.js +644 -679
  97. package/examples/starter/README.md +0 -3
  98. package/locales/ca.js +1 -37
  99. package/locales/de.js +1 -42
  100. package/locales/en.js +1 -43
  101. package/locales/fr.js +1 -39
  102. package/locales/ja.js +1 -42
  103. package/locales/pt.js +1 -42
  104. package/locales/ru.js +1 -42
  105. package/package.json +2 -2
  106. package/sandbox-macos-permissive-closed.sb +0 -1
  107. package/sandbox-macos-permissive-open.sb +0 -1
  108. package/sandbox-macos-permissive-proxied.sb +1 -2
  109. package/sandbox-macos-restrictive-closed.sb +14 -2
  110. package/sandbox-macos-restrictive-open.sb +14 -2
  111. package/sandbox-macos-restrictive-proxied.sb +15 -3
  112. package/bundled/mainy/SKILL.md +0 -157
  113. package/bundled/mainy/docs/_meta.ts +0 -32
  114. package/bundled/mainy/docs/common-workflow.md +0 -571
  115. package/bundled/mainy/docs/configuration/_meta.ts +0 -7
  116. package/bundled/mainy/docs/configuration/auth.md +0 -82
  117. package/bundled/mainy/docs/configuration/matilda-ignore.md +0 -55
  118. package/bundled/mainy/docs/configuration/model-providers.md +0 -598
  119. package/bundled/mainy/docs/configuration/settings.md +0 -790
  120. package/bundled/mainy/docs/configuration/themes.md +0 -199
  121. package/bundled/mainy/docs/configuration/trusted-folders.md +0 -67
  122. package/bundled/mainy/docs/extension/_meta.ts +0 -9
  123. package/bundled/mainy/docs/extension/extension-releasing.md +0 -204
  124. package/bundled/mainy/docs/extension/getting-started-extensions.md +0 -299
  125. package/bundled/mainy/docs/extension/introduction.md +0 -338
  126. package/bundled/mainy/docs/features/_meta.ts +0 -27
  127. package/bundled/mainy/docs/features/approval-mode.md +0 -388
  128. package/bundled/mainy/docs/features/arena.md +0 -219
  129. package/bundled/mainy/docs/features/auto-mode.md +0 -308
  130. package/bundled/mainy/docs/features/channels/_meta.ts +0 -8
  131. package/bundled/mainy/docs/features/channels/dingtalk.md +0 -134
  132. package/bundled/mainy/docs/features/channels/feishu.md +0 -186
  133. package/bundled/mainy/docs/features/channels/overview.md +0 -336
  134. package/bundled/mainy/docs/features/channels/plugins.md +0 -87
  135. package/bundled/mainy/docs/features/channels/telegram.md +0 -120
  136. package/bundled/mainy/docs/features/channels/weixin.md +0 -106
  137. package/bundled/mainy/docs/features/code-review.md +0 -291
  138. package/bundled/mainy/docs/features/commands.md +0 -528
  139. package/bundled/mainy/docs/features/dual-output.md +0 -627
  140. package/bundled/mainy/docs/features/followup-suggestions.md +0 -109
  141. package/bundled/mainy/docs/features/headless.md +0 -448
  142. package/bundled/mainy/docs/features/hooks.md +0 -1306
  143. package/bundled/mainy/docs/features/language.md +0 -171
  144. package/bundled/mainy/docs/features/lsp.md +0 -496
  145. package/bundled/mainy/docs/features/markdown-rendering.md +0 -183
  146. package/bundled/mainy/docs/features/mcp.md +0 -423
  147. package/bundled/mainy/docs/features/memory.md +0 -185
  148. package/bundled/mainy/docs/features/sandbox.md +0 -249
  149. package/bundled/mainy/docs/features/scheduled-tasks.md +0 -139
  150. package/bundled/mainy/docs/features/skills.md +0 -347
  151. package/bundled/mainy/docs/features/status-line.md +0 -397
  152. package/bundled/mainy/docs/features/structured-output.md +0 -309
  153. package/bundled/mainy/docs/features/sub-agents.md +0 -737
  154. package/bundled/mainy/docs/features/tips.md +0 -54
  155. package/bundled/mainy/docs/features/token-caching.md +0 -29
  156. package/bundled/mainy/docs/features/tool-use-summaries.md +0 -178
  157. package/bundled/mainy/docs/features/worktree.md +0 -345
  158. package/bundled/mainy/docs/ide-integration/_meta.ts +0 -4
  159. package/bundled/mainy/docs/ide-integration/ide-companion-spec.md +0 -182
  160. package/bundled/mainy/docs/ide-integration/ide-integration.md +0 -144
  161. package/bundled/mainy/docs/integration-github-action.md +0 -241
  162. package/bundled/mainy/docs/integration-jetbrains.md +0 -81
  163. package/bundled/mainy/docs/integration-vscode.md +0 -39
  164. package/bundled/mainy/docs/integration-zed.md +0 -72
  165. package/bundled/mainy/docs/matilda-serve-deploy-local.md +0 -221
  166. package/bundled/mainy/docs/matilda-serve.md +0 -661
  167. package/bundled/mainy/docs/overview.md +0 -64
  168. package/bundled/mainy/docs/quickstart.md +0 -234
  169. package/bundled/mainy/docs/reference/_meta.ts +0 -3
  170. package/bundled/mainy/docs/reference/keyboard-shortcuts.md +0 -91
  171. package/bundled/mainy/docs/support/Uninstall.md +0 -65
  172. package/bundled/mainy/docs/support/_meta.ts +0 -6
  173. package/bundled/mainy/docs/support/tos-privacy.md +0 -94
  174. package/bundled/mainy/docs/support/troubleshooting.md +0 -127
  175. package/chunks/agent-WM63A6NK.js +0 -3
  176. package/chunks/agent-headless-QIUBDKPW.js +0 -3
  177. package/chunks/anthropicContentGenerator-VKFTAIU3.js +0 -39
  178. package/chunks/ca-I2HEEIL7.js +0 -25
  179. package/chunks/chunk-2HTPVSGT.js +0 -3
  180. package/chunks/chunk-2MOGYHWM.js +0 -8
  181. package/chunks/chunk-3IRGBRSP.js +0 -113
  182. package/chunks/chunk-3YLXGE6T.js +0 -8
  183. package/chunks/chunk-47XR7IMP.js +0 -8
  184. package/chunks/chunk-4F4DA5UI.js +0 -8
  185. package/chunks/chunk-4J6DC24J.js +0 -59
  186. package/chunks/chunk-4Q2SNBUH.js +0 -18
  187. package/chunks/chunk-5C2RJ5RR.js +0 -37
  188. package/chunks/chunk-6E766NPX.js +0 -31
  189. package/chunks/chunk-6EQMZNIY.js +0 -8
  190. package/chunks/chunk-6GBNB5Z2.js +0 -3
  191. package/chunks/chunk-6Z2MV7ZY.js +0 -186
  192. package/chunks/chunk-BVOCFLC4.js +0 -56
  193. package/chunks/chunk-CSJTA7NE.js +0 -101
  194. package/chunks/chunk-DC7LAFZZ.js +0 -8
  195. package/chunks/chunk-DE3HKC2W.js +0 -9
  196. package/chunks/chunk-EQGA7LH7.js +0 -30
  197. package/chunks/chunk-FPO57O66.js +0 -39
  198. package/chunks/chunk-FWDMPRKU.js +0 -3
  199. package/chunks/chunk-G7R2XEEF.js +0 -7
  200. package/chunks/chunk-GOJCMVJJ.js +0 -8
  201. package/chunks/chunk-GTVCJCHR.js +0 -8
  202. package/chunks/chunk-JCE3JAVC.js +0 -25
  203. package/chunks/chunk-JRECUFB3.js +0 -2630
  204. package/chunks/chunk-KHHJYBR5.js +0 -9
  205. package/chunks/chunk-LJR4RZZ2.js +0 -3
  206. package/chunks/chunk-LUNDTQ3G.js +0 -8
  207. package/chunks/chunk-M53RP3YP.js +0 -31
  208. package/chunks/chunk-MO2HXJG5.js +0 -9
  209. package/chunks/chunk-MTMU7JYZ.js +0 -11
  210. package/chunks/chunk-O44XK65C.js +0 -8
  211. package/chunks/chunk-OA56BXPD.js +0 -3
  212. package/chunks/chunk-PA6532AY.js +0 -6
  213. package/chunks/chunk-PGXQZVLX.js +0 -8
  214. package/chunks/chunk-QKYGQLWC.js +0 -8
  215. package/chunks/chunk-QN6Y6NPA.js +0 -3
  216. package/chunks/chunk-QVCGLQCI.js +0 -32
  217. package/chunks/chunk-S3CWEVTS.js +0 -15
  218. package/chunks/chunk-SDTWBD62.js +0 -8
  219. package/chunks/chunk-T2T2UEPY.js +0 -4
  220. package/chunks/chunk-TISQNFB5.js +0 -3
  221. package/chunks/chunk-U347OO7S.js +0 -9
  222. package/chunks/chunk-UIRBHC5X.js +0 -3
  223. package/chunks/chunk-VI74YQQO.js +0 -8
  224. package/chunks/chunk-VYZOOSMP.js +0 -30
  225. package/chunks/chunk-WC2VTVCE.js +0 -27
  226. package/chunks/chunk-WVY2P6WH.js +0 -26
  227. package/chunks/chunk-WZ75OGYY.js +0 -14
  228. package/chunks/chunk-XMZIY7XX.js +0 -13
  229. package/chunks/chunk-YJAKOETP.js +0 -22
  230. package/chunks/chunk-YV3PUOBU.js +0 -65
  231. package/chunks/contextCommand-DAB3HOHY.js +0 -3
  232. package/chunks/cron-delete-DE6Q2S2L.js +0 -3
  233. package/chunks/cron-list-IAQEJVV7.js +0 -5
  234. package/chunks/de-AQXFJYZI.js +0 -25
  235. package/chunks/dist-7UYRLSLE.js +0 -3
  236. package/chunks/dist-ME6647DQ.js +0 -195
  237. package/chunks/dist-P6SLWL5V.js +0 -42
  238. package/chunks/dist-VG3ZDJ2A.js +0 -28
  239. package/chunks/dist-YTCHM57U.js +0 -23
  240. package/chunks/enterPlanMode-HP35SPLN.js +0 -18
  241. package/chunks/fileFromPath-7UCWPD4W.js +0 -3
  242. package/chunks/fr-6TDHK7F2.js +0 -25
  243. package/chunks/geminiContentGenerator-RJ73DQAP.js +0 -8
  244. package/chunks/glob-QQ6LGKDX.js +0 -22
  245. package/chunks/keychain-token-storage-KQK6MNOJ.js +0 -3
  246. package/chunks/ls-JYJXFSXN.js +0 -15
  247. package/chunks/matildaAgentContentGenerator-YUYS4336.js +0 -8
  248. package/chunks/matildaContentGenerator-O4Z2QPCP.js +0 -8
  249. package/chunks/matildaOAuth2-7COTQQR2.js +0 -3
  250. package/chunks/mcp-client-RXVQU5VI.js +0 -3
  251. package/chunks/monitor-77KXDXPR.js +0 -32
  252. package/chunks/notebook-edit-TKJD2EQZ.js +0 -17
  253. package/chunks/openaiContentGenerator-2EALAM3U.js +0 -3
  254. package/chunks/pt-D6L2QTDM.js +0 -25
  255. package/chunks/read-file-3KUAH6ND.js +0 -3
  256. package/chunks/ripGrep-U2PLKXMY.js +0 -3
  257. package/chunks/ru-BNJCHDYO.js +0 -25
  258. package/chunks/scheduler-J7VU2V5Y.js +0 -8
  259. package/chunks/send-message-P3SMWNEE.js +0 -8
  260. package/chunks/serve-FXH6EBQ6.js +0 -1015
  261. package/chunks/shell-PXR2AXDD.js +0 -3
  262. package/chunks/src-RFAEPLY7.js +0 -3
  263. package/chunks/src-WZTRMETQ.js +0 -5
  264. package/chunks/symbol-search-EAIZPWN7.js +0 -19
  265. package/chunks/task-create-Z3QRCMX4.js +0 -3
  266. package/chunks/task-list-GXAJW3JP.js +0 -9
  267. package/chunks/team-delete-OMYVUAQU.js +0 -8
  268. package/chunks/todoWrite-5NZ7CHTC.js +0 -3
  269. package/chunks/write-file-XDDLTGSG.js +0 -15
@@ -0,0 +1,13 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{b as c}from"./chunk-FKHUEFMK.js";import{b as r}from"./chunk-GZPNIYVZ.js";r();var S=c,N="text-embedding-v4";r();import{AsyncLocalStorage as P}from"node:async_hooks";import{randomUUID as f}from"node:crypto";r();import{AsyncLocalStorage as A}from"node:async_hooks";var R=new A;var E="x-matilda-reported-operation-id",O="x-matilda-reported-attempt-purpose",y=[E,O],D=new Set(y),_=["answer","tool_followup","continuation","retry","compaction","unknown"],l=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,I=new Set(_),d=new P,m=new WeakSet;function T(){return f()}function s(t,e){let o=Object.freeze({operationId:t,attemptPurpose:e});return m.add(o),o}function G(t){return D.has(t.toLowerCase())}function a(){let t=d.getStore();return t&&m.has(t)?t:void 0}var x=class{activeOperationId;begin(e){return this.activeOperationId=T(),s(this.activeOperationId,e)}continue(e){let o=a()?.operationId??this.activeOperationId??T();return this.activeOperationId=o,s(o,e)}};function p(t,e){return d.run(t,e)}function Y(t){d.enterWith(t)}function H(t,e){let o=a();return o?p(s(o.operationId,t),e):e()}function C(t,e){let o={next:(...n)=>p(t,()=>e.next(...n)),return:n=>p(t,()=>e.return(n)),throw:n=>p(t,()=>e.throw(n)),[Symbol.asyncIterator]:()=>o},i=Symbol.asyncDispose,u=i&&e[i];return i&&typeof u=="function"&&(o[i]=()=>p(t,()=>u.call(e))),o}function W(t,e){let o=a();return o?C(s(o.operationId,t),e):e}function j(){let t=a();if(!t||!l.test(t.operationId))return{};let e=R.getStore()?.attempt,o=e!==void 0&&e>1?"retry":t.attemptPurpose;return I.has(o)?{[E]:t.operationId,[O]:o}:{}}export{R as a,E as b,O as c,y as d,G as e,a as f,x as g,p as h,Y as i,H as j,C as k,W as l,j as m,S as n,N as o};
4
+ /**
5
+ * @license
6
+ * Copyright 2025 Google LLC
7
+ * SPDX-License-Identifier: Apache-2.0
8
+ */
9
+ /**
10
+ * @license
11
+ * Copyright 2026 Matilda Team
12
+ * SPDX-License-Identifier: Apache-2.0
13
+ */
@@ -0,0 +1,8 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{b as e}from"./chunk-GZPNIYVZ.js";e();var t="MATILDA_API_KEY";var o="matilda-code-1.0",a="Matilda",n="https://matilda.maincode.com/api/v1/code";var r={id:"matilda",label:"Matilda",description:"Connect to the Matilda Core code API endpoint",protocol:"openai",baseUrl:n,envKey:t,models:[{id:o,displayName:a,contextWindowSize:1048576,description:"Matilda Code model",generationConfig:{openAIRequestProfile:"matilda-code",timeout:6e5,samplingParams:{max_tokens:65536,chat_template_kwargs:{enable_thinking:!0}},schemaCompliance:"openapi_30",splitToolMedia:!0,customHeaders:{"User-Agent":"MatildaCode/0.1"}}}],modelNamePrefix:"",documentationUrl:"https://matilda.maincode.help/welcome/external-api",uiGroup:"third-party"};export{t as a,o as b,a as c,n as d,r as e};
4
+ /**
5
+ * @license
6
+ * Copyright 2026 Matilda Team
7
+ * SPDX-License-Identifier: Apache-2.0
8
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{w as i}from"./chunk-PGXQZVLX.js";import{b as o}from"./chunk-GZPNIYVZ.js";o();import l from"node:path";function d(t,n){if(t.getApprovalMode()!=="bogan")return null;let r=l.resolve(n),s=t.getProjectRoot?.()??t.getTargetDir();if(i(r,s))return null;let e=t.getWorkspaceContext?.();if(!e||(typeof e.isPathWithinWorkspaceFresh=="function"?e.isPathWithinWorkspaceFresh(r):e.isPathWithinWorkspace(r)))return null;let a=e.getDirectories?.()??[t.getTargetDir()],p=t.getChannel?.()==="desktop"?"Approve the folder from Matilda Desktop, then retry the write.":"Use --include-directories to add extra roots, or a non-BOGAN approval mode for intentional external writes.";return`Refusing out-of-workspace write in BOGAN mode: ${r}. Workspace root(s): ${a.join(", ")}. This blocks path typos (e.g. writing under $HOME when the project is elsewhere). `+p}export{d as a};
3
+ import{l as i}from"./chunk-I3CV4LOD.js";import{b as o}from"./chunk-GZPNIYVZ.js";o();import l from"node:path";function d(t,n){if(t.getApprovalMode()!=="bogan")return null;let r=l.resolve(n),s=t.getProjectRoot?.()??t.getTargetDir();if(i(r,s))return null;let e=t.getWorkspaceContext?.();if(!e||(typeof e.isPathWithinWorkspaceFresh=="function"?e.isPathWithinWorkspaceFresh(r):e.isPathWithinWorkspace(r)))return null;let a=e.getDirectories?.()??[t.getTargetDir()],p=t.getChannel?.()==="desktop"?"Approve the folder from Matilda Desktop, then retry the write.":"Use --include-directories to add extra roots, or a non-BOGAN approval mode for intentional external writes.";return`Refusing out-of-workspace write in BOGAN mode: ${r}. Workspace root(s): ${a.join(", ")}. This blocks path typos (e.g. writing under $HOME when the project is elsewhere). `+p}export{d as a};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Matilda Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{f}from"./chunk-2MOGYHWM.js";import{f as u}from"./chunk-QKYGQLWC.js";import{g as m,i as c,p as l,q as p}from"./chunk-6E766NPX.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();var o=2e3;function T(e){return e.length<=o?e:`${e.slice(0,o)}
3
+ import{d as f}from"./chunk-ZQKABJBB.js";import{d as u}from"./chunk-QXSBPCBA.js";import{f as m,g as c,m as l,n as p}from"./chunk-DB5LMKXU.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();var o=2e3;function T(e){return e.length<=o?e:`${e.slice(0,o)}
4
4
  \u2026 (${e.length-o} more characters)`}var s=class extends m{constructor(t,r){super(r);this.config=t}getDescription(){return`Create task: ${this.params.subject}`}async getDefaultPermission(){return"ask"}getConfirmationDetails(t){let r={type:"info",title:"Confirm TaskCreate",prompt:`Create task: ${this.params.subject}
5
5
 
6
6
  `+T(this.params.description),onConfirm:async()=>{}};return Promise.resolve(r)}async execute(){let t=u(this.config.getTeamContext()?.teamName);if(!t){let a="No active team. Create a team first.";return{llmContent:a,returnDisplay:a,error:{message:a}}}let r=await f(t,{subject:this.params.subject,description:this.params.description,activeForm:this.params.activeForm,metadata:this.params.metadata}),i=`Task #${r.id} created: "${r.subject}"`;return{llmContent:i,returnDisplay:i}}},d=class e extends c{constructor(t){super(e.Name,p.TASK_CREATE,"Create a new task in the team task list. Tasks are automatically assigned to idle teammates.","other",{type:"object",properties:{subject:{type:"string",description:"Short title for the task.",maxLength:200},description:{type:"string",description:"Detailed description of the task.",maxLength:1e4},activeForm:{type:"string",maxLength:200,description:'Present tense label for UI (e.g., "Running tests").'},metadata:{type:"object",description:"Optional arbitrary metadata."}},required:["subject","description"],additionalProperties:!1});this.config=t}static Name=l.TASK_CREATE;createInvocation(t){return new s(this.config,t)}toAutoClassifierInput(t){return{subject:t.subject,description:t.description}}};export{T as a,d as b};
@@ -0,0 +1,120 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{d as Ze,f as oe}from"./chunk-VUJRLLGL.js";import{b as k,e as te}from"./chunk-LVDDFAK4.js";import{a as Dn,d as Ln,n as et}from"./chunk-EYZPVR7N.js";import{a as Fn,b as zt,c as Gn,d as Kn}from"./chunk-FKHUEFMK.js";import{Aa as Kt,Ca as $t,M as le,O as qe,P as He,Q as Je,Y as Ye,Z as ne,c as q,la as Xe,ma as Qe,tb as Bt,ub as jt,wb as Vt,ya as Gt}from"./chunk-6PFK4XTH.js";import{I as ze,S as N,c as Un,d as Nn,e as W,f as ke,j as Ut,p as Ve}from"./chunk-NK2QMGCC.js";import{h as B,i as We,k as Nt,m as Ft}from"./chunk-HEJO7OBH.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();p();p();p();p();var j=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};p();function $n(t){return/^[0-9A-Fa-f]$/.test(t)}function J(t){return t>="0"&&t<="9"}function Bn(t){return t>=" "}function _e(t){return`,:[]/{}()
4
+ +`.includes(t)}function Wt(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function qt(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var Ht=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,Jt=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function Yt(t){return`,[]/{}
5
+ +`.includes(t)}function Xt(t){return we(t)||Ar.test(t)}var Ar=/^[[{\w-]$/;function jn(t){return t===`
6
+ `||t==="\r"||t===" "||t==="\b"||t==="\f"}function H(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function Vn(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function zn(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function we(t){return Qt(t)||tt(t)}function Qt(t){return t==='"'||t==="\u201C"||t==="\u201D"}function Zt(t){return t==='"'}function tt(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function en(t){return t==="'"}function ue(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=t.lastIndexOf(e);return o!==-1?t.substring(0,o)+(n?"":t.substring(o+1)):t}function F(t,e){let n=t.length;if(!H(t,n-1))return t+e;for(;H(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function Wn(t,e,n){return t.substring(0,e)+t.substring(e+n)}function qn(t){return/[,\n][ \t\r]*$/.test(t)}var Er={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Rr={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
7
+ `,r:"\r",t:" "};function nt(t){let e=0,n="";u(["```","[```","{```"]),i()||Z(),u(["```","```]","```}"]);let r=f(",");for(r&&s(),Xt(t[e])&&qn(n)?(r||(n=F(n,",")),T()):r&&(n=ue(n,","));t[e]==="}"||t[e]==="]";)e++,s();if(e>=t.length)return n;Be();function i(){s();let y=m()||C()||S()||w()||v()||G(!1)||Dt();return s(),y}function s(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,A=e,R=a(y);do R=l(),R&&(R=a(y));while(R);return e>A}function a(y){let A=y?H:Vn,R="";for(;;)if(A(t,e))R+=t[e],e++;else if(zn(t,e))R+=" ",e++;else break;return R.length>0?(n+=R,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!br(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
8
+ `;)e++;return!0}return!1}function u(y){if(c(y)){if(Wt(t[e]))for(;e<t.length&&qt(t[e]);)e++;return s(),!0}return!1}function c(y){a(!0);for(let A of y){let R=e+A.length;if(t.slice(e,R)===A)return e=R,!0}return!1}function f(y){return t[e]===y?(n+=t[e],e++,!0):!1}function d(y){return t[e]===y?(e++,!0):!1}function g(){return d("\\")}function h(){return s(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,s(),d(","),!0):!1}function m(){if(t[e]==="{"){n+="{",e++,s(),d(",")&&s();let y=!0;for(;e<t.length&&t[e]!=="}";){let A;if(y?(A=!0,y=!1):(A=f(","),A||(n=F(n,",")),s()),h(),!(S()||G(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?n=ue(n,","):L();break}s();let je=f(":"),ee=e>=t.length;je||(Xt(t[e])||ee?n=F(n,":"):ve()),i()||(je||ee?n+="null":ve())}return t[e]==="}"?(n+="}",e++):n=F(n,"}"),!0}return!1}function C(){if(t[e]==="["){n+="[",e++,s(),d(",")&&s();let y=!0;for(;e<t.length&&t[e]!=="]";)if(y?y=!1:f(",")||(n=F(n,",")),h(),!i()){n=ue(n,",");break}return t[e]==="]"?(n+="]",e++):n=F(n,"]"),!0}return!1}function T(){let y=!0,A=!0;for(;A;)y?y=!1:f(",")||(n=F(n,",")),A=i();A||(n=ue(n,",")),n=`[
9
+ ${n}
10
+ ]`}function S(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,R=t[e]==="\\";if(R&&(e++,R=!0),we(t[e])){let je=Zt(t[e])?Zt:en(t[e])?en:tt(t[e])?tt:Qt,ee=e,Me=n.length,M='"';for(e++;;){if(e>=t.length){let O=P(e-1);return!y&&_e(t.charAt(O))?(e=ee,n=n.substring(0,Me),S(!0)):(M=F(M,'"'),n+=M,!0)}if(e===A)return M=F(M,'"'),n+=M,!0;if(je(t[e])){let O=e,Lt=M.length;if(M+='"',e++,n+=M,s(!1),y||e>=t.length||_e(t[e])||we(t[e])||J(t[e]))return E(),!0;let z=P(O-1),Pn=t.charAt(z);if(Pn===",")return e=ee,n=n.substring(0,Me),S(!1,z);if(_e(Pn))return e=ee,n=n.substring(0,Me),S(!0);n=n.substring(0,Me),e=O+1,M=`${M.substring(0,Lt)}\\${M.substring(Lt)}`}else if(y&&Yt(t[e])){if(t[e-1]===":"&&Ht.test(t.substring(ee+1,e+2)))for(;e<t.length&&Jt.test(t[e]);)M+=t[e],e++;return M=F(M,'"'),n+=M,E(),!0}else if(t[e]==="\\"){let O=t.charAt(e+1);if(Rr[O]!==void 0)M+=t.slice(e,e+2),e+=2;else if(O==="u"){let z=2;for(;z<6&&$n(t[e+z]);)z++;z===6?(M+=t.slice(e,e+6),e+=6):e+z>=t.length?e=t.length:Sr()}else M+=O,e+=2}else{let O=t.charAt(e);O==='"'&&t[e-1]!=="\\"?(M+=`\\${O}`,e++):jn(O)?(M+=Er[O],e++):(Bn(O)||Q(O),M+=O,e++)}R&&g()}}return!1}function E(){let y=!1;for(s();t[e]==="+";){y=!0,e++,s(),n=ue(n,'"',!0);let A=n.length;S()?n=Wn(n,A,1):n=F(n,'"')}return y}function w(){let y=e;if(t[e]==="-"){if(e++,ae())return I(y),!0;if(!J(t[e]))return e=y,!1}for(;J(t[e]);)e++;if(t[e]==="."){if(e++,ae())return I(y),!0;if(!J(t[e]))return e=y,!1;for(;J(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,ae())return I(y),!0;if(!J(t[e]))return e=y,!1;for(;J(t[e]);)e++}if(!ae())return e=y,!1;if(e>y){let A=t.slice(y,e),R=/^0\d/.test(A);return n+=R?`"${A}"`:A,!0}return!1}function v(){return _("true","true")||_("false","false")||_("null","null")||_("True","true")||_("False","false")||_("None","null")}function _(y,A){return t.slice(e,e+y.length)===y?(n+=A,e+=y.length,!0):!1}function G(y){let A=e;if(Wt(t[e])){for(;e<t.length&&qt(t[e]);)e++;let R=e;for(;H(t,R);)R++;if(t[R]==="(")return e=R+1,i(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!Yt(t[e])&&!we(t[e])&&(!y||t[e]!==":");)e++;if(t[e-1]===":"&&Ht.test(t.substring(A,e+2)))for(;e<t.length&&Jt.test(t[e]);)e++;if(e>A){for(;H(t,e-1)&&e>0;)e--;let R=t.slice(A,e);return n+=R==="undefined"?"null":JSON.stringify(R),t[e]==='"'&&e++,!0}}function Dt(){if(t[e]==="/"){let y=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=`"${t.substring(y,e)}"`,!0}}function P(y){let A=y;for(;A>0&&H(t,A);)A--;return A}function ae(){return e>=t.length||_e(t[e])||H(t,e)}function I(y){n+=`${t.slice(y,e)}0`}function Q(y){throw new j(`Invalid character ${JSON.stringify(y)}`,e)}function Be(){throw new j(`Unexpected character ${JSON.stringify(t[e])}`,e)}function Z(){throw new j("Unexpected end of json string",t.length)}function L(){throw new j("Object key expected",e)}function ve(){throw new j("Colon expected",e)}function Sr(){let y=t.slice(e,e+6);throw new j(`Invalid unicode character "${y}"`,e)}}function br(t,e){return t[e]==="*"&&t[e+1]==="/"}var vr=N("JSON_PARSE");function Mr(t,e={}){if(!t||typeof t!="string")return e;try{return JSON.parse(t)}catch(n){let o=kr(t);if(o!==void 0)return o;try{let r=nt(t);return JSON.parse(r)}catch(r){let i=Yn(t);if(i&&i!==t)try{return JSON.parse(nt(i))}catch{}return vr.error("Failed to parse JSON even with jsonrepair:",{originalError:n,repairError:r,jsonString:t}),e}}}var Hn=Symbol("tool-args-parse-failed");function Jn(t){if(t==null)return{};let e=typeof t=="string"?t.trim():"";if(!e)return{};let n=Mr(e,Hn);return n===Hn?null:n&&typeof n=="object"&&!Array.isArray(n)?n:null}function kr(t){let e=Yn(t);if(e&&e!==t.trim())try{return JSON.parse(e)}catch{return}}function Yn(t){let e=t.trimStart();if(!e)return null;let n=e[0];if(n!=="{"&&n!=="[")return null;let o=0,r=!1,i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(r){i?i=!1:a==="\\"?i=!0:a==='"'&&(r=!1);continue}if(a==='"'){r=!0;continue}if(a==="{"||a==="[")o++;else if(a==="}"||a==="]"){if(o--,o===0)return e.slice(0,s+1);if(o<0)return null}}return null}p();var _r=/[A-Za-z\u00C0-\u024F]/g;function wr(t){return t>=1024&&t<=1279||t>=1280&&t<=1327||t>=11744&&t<=11775||t>=42560&&t<=42655||t>=12352&&t<=12543||t>=13312&&t<=19903||t>=19968&&t<=40959||t>=63744&&t<=64255||t>=44032&&t<=55215}function tn(t){let e=t.codePointAt(0);return e!==void 0&&wr(e)}function xr(t){let e=t.match(_r)?.length??0;if(e<24)return!1;let n=0;for(let o of t)tn(o)&&n++;return n===0||e>=n*8}function ot(t){if(!t||!xr(t))return t;let e="",n=0,o=[...t];for(;n<o.length;){if(!tn(o[n])){e+=o[n],n++;continue}let r=n;for(;r>0&&o[r-1]===" ";)r--;let i=n+1;for(;i<o.length&&tn(o[i]);)i++;for(;i<o.length&&o[i]===" ";)i++;let s=r>0?o[r-1]:"",a=i<o.length?o[i]:"";(/[A-Za-z0-9]/.test(s)&&/[A-Za-z0-9]/.test(a)||o[r]===" "||o[i-1]===" ")&&(e+=" "),n=i,r<n&&o[r]===" "&&e.endsWith(" ")&&(e=e.slice(0,-1))}return e.replace(/ {2,}/g," ")}p();var ce=N("TAGGED_THINKING_PARSER"),Ie=["<think>","<thinking>"],Oe=["</think>","</thinking>"],Ir=Math.max(...Ie.map(t=>t.length),...Oe.map(t=>t.length));function xe(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function rt(t,e,n){let o=t.length-e;return o<=0||o>Ir?!1:n.some(r=>r.startsWith(t.slice(e,e+o)))}function it(t,e,n){return n.find(o=>t.startsWith(o,e))}function on(t){if(!t)return t;let e=t;return e=e.replace(/<\/?think(?:ing)?>/gi,""),e=e.replace(/[A-Za-z]*long[_-]?message[_-]?THINKING/gi,""),e=e.replace(/\bM?long[_-]?message\b/gi,""),e=e.replace(/(^|[\s>])THINKING(?=[\sA-Z<]|$)/g,"$1"),e!==t&&(e=e.replace(/[ \t]{2,}/g," ")),e}function Xn(t){let e=[];for(let n of t){if(n.thought===!0||typeof n.text!="string"){e.push(n);continue}let o=ot(on(n.text));(o.length>0||/^\s+$/.test(n.text))&&e.push({text:o.length>0?o:n.text})}return e}var nn=class{mode="text";buffer="";parse(e,n=!1){this.buffer+=e;let o=this.buffer.toLowerCase(),r=[],i="",s=0;for(;s<this.buffer.length;){if(this.mode==="text"){let a=it(o,s,Ie);if(a){ce.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),xe(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=it(o,s,Oe);if(l){ce.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),xe(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(rt(o,s,Ie)||rt(o,s,Oe)))break}else{let a=it(o,s,Oe);if(a){ce.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),xe(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=it(o,s,Ie);if(l){s+=l.length;continue}if(!n&&(rt(o,s,Oe)||rt(o,s,Ie)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(xe(r,i,this.mode),this.buffer=this.buffer.slice(s),ce.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),Xn(r)):(this.buffer="",this.mode==="thought"&&i&&ce.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),xe(r,i,this.mode),ce.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),Xn(r))}};function Qn(t){return new nn().parse(t,!0)}p();function Zn(t,e="auto"){return e==="openapi_30"?Or(t):t}function Or(t){let e=n=>{if(typeof n!="object"||n===null)return n;if(Array.isArray(n))return n.map(e);let o=n,r={};if(Array.isArray(o.type)){let i=o.type;i.length===2&&i.includes("null")?(r.type=i.find(s=>s!=="null"),r.nullable=!0):r.type=i[0]}else o.type!==void 0&&(r.type=o.type);o.const!==void 0&&(r.enum=[o.const],delete r.const),typeof o.exclusiveMinimum=="number"&&(r.minimum=o.exclusiveMinimum,r.exclusiveMinimum=!0),typeof o.exclusiveMaximum=="number"&&(r.maximum=o.exclusiveMaximum,r.exclusiveMaximum=!0),Array.isArray(o.items)?delete r.items:typeof o.items=="object"&&o.items!==null&&(r.items=e(o.items)),Array.isArray(o.enum)&&(r.enum=o.enum.map(String));for(let[i,s]of Object.entries(o))i==="type"||i==="const"||i==="exclusiveMinimum"||i==="exclusiveMaximum"||i==="items"||i==="enum"||i==="$schema"||i==="$id"||i==="default"||i==="dependencies"||i==="patternProperties"||(r[i]=e(s));return r};return e(t)}p();function de(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function st(t){let e=t.candidates||0,n=t.thoughts||0;return n>e?e+n:Math.max(e,n)}function Pr(t){return t.total&&t.total>0?Math.max(t.total,(t.prompt||0)+st(t)):(t.prompt||0)+st(t)}function Dr(t){let e=Math.max(0,t.thoughtsTokens||0),n=st({candidates:t.outputTokens||0,thoughts:e}),o=Math.max(t.totalTokens||0,(t.inputTokens||0)+n);return{...t,outputTokens:n,thoughtsTokens:e,totalTokens:o}}var V=N("CONVERTER"),so="(attached media from previous tool call)";function ao(t,e={}){let n=t.prompt_tokens||0,o=t.completion_tokens||0,r=t.total_tokens||0,i=t.prompt_tokens_details,s=i?.cached_tokens??i?.cachedTokens??t.cached_tokens??t.prompt_cache_hit_tokens??t.cache_read_input_tokens??0,a=t.completion_tokens_details,l=a?.reasoning_tokens??a?.reasoningTokens??t.reasoning_tokens??0,u=Math.max(0,e.estimatedReasoningTokens??0),c=Math.max(0,e.estimatedContentTokens??0),f=l>0?l:u,d=o;f>0&&(o>=f?d=o:d=o+f),(c>0||u>0)&&(d=Math.max(d,c+(l>0?0:u),c+f)),r>n&&(n>0||o>0||f>0)&&(d=Math.max(d,r-n)),f===0&&u>0&&(f=u),f>d&&(f=d);let g=t.usage_is_incomplete===!0||o>0&&n===0||r>0&&n===0&&o===0,h=n,m=r;return(m===0&&(h>0||d>0)||m>0&&h>0&&m<h+d)&&(m=h+d),{promptTokenCount:h,candidatesTokenCount:d,totalTokenCount:m,cachedContentTokenCount:s,thoughtsTokenCount:f,...g?{usageIsIncomplete:!0}:{}}}var Lr=64,eo=1024;function to(t,e){if(t.length===0)return"";if(e.emittedText.length===0)return e.emittedText=t,e.emittedLength=t.length,t;if(e.cumulativeMode){if(t.startsWith(e.emittedText)){let n=t.slice(e.emittedText.length);return e.emittedText=t,e.emittedLength=t.length,n}return e.emittedText.startsWith(t)?(V.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(V.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),e.cumulativeMode=!1,e.emittedText=t,e.emittedLength+=t.length,t)}if(t.length>e.emittedText.length&&t.startsWith(e.emittedText)){let n=e.emittedText.length,r=n>=eo&&e.emittedLength>n?e.emittedLength:n;if(t.length>r){let i=t.slice(r);return e.emittedText=t,e.emittedLength=t.length,e.cumulativeMode=!0,V.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${t.length}b)`),i}}return t===e.emittedText?t.length>=Lr?(e.cumulativeMode=!0,V.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<eo&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function lo(t){if(!t||typeof t!="object")return t;let e=JSON.parse(JSON.stringify(t)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let r={};for(let[i,s]of Object.entries(o))if(i==="type"&&typeof s=="string"){let a=s.toLowerCase();a==="integer"?r[i]="integer":a==="number"?r[i]="number":r[i]=a}else i==="minimum"||i==="maximum"||i==="multipleOf"?typeof s=="string"&&!isNaN(Number(s))?r[i]=Number(s):r[i]=s:i==="minLength"||i==="maxLength"||i==="minItems"||i==="maxItems"?typeof s=="string"&&!isNaN(Number(s))?r[i]=parseInt(s,10):r[i]=s:typeof s=="object"?r[i]=n(s):r[i]=s;return r};return n(e)}async function Ur(t,e="auto"){let n=[];for(let o of t){let r;if("tool"in o?r=await o.tool():r=o,r.functionDeclarations){for(let i of r.functionDeclarations)if(i.name&&i.description){let s;i.parametersJsonSchema?s={...i.parametersJsonSchema}:i.parameters&&(s=lo(i.parameters)),s&&(s=Zn(s,e)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function Nr(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return Gr(t,o),Kr(t.contents,o,e),o=io(o),n.cleanOrphanToolCalls&&(o=Yr(o),o=io(o)),o}function Fr(t,e){let n=t.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 l={role:"assistant",content:i.join("")||null,refusal:null},u=r.join("");u&&(l.reasoning_content=u),s.length>0&&(l.tool_calls=s);let c=Jr(n?.finishReason),f=t.usageMetadata,d={prompt_tokens:f?.promptTokenCount||0,completion_tokens:f?.candidatesTokenCount||0,total_tokens:f?.totalTokenCount||0};f?.cachedContentTokenCount!==void 0&&(d.prompt_tokens_details={cached_tokens:f.cachedContentTokenCount});let g=t.createTime?Number(t.createTime):Date.now(),h=Number.isFinite(g)?Math.floor(g/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:h,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:c,logprobs:null}],usage:d}}function Gr(t,e){if(!t.config?.systemInstruction)return;let n=co(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function Kr(t,e,n){if(Array.isArray(t))for(let o of t)no(o,e,n);else t&&no(t,e,n)}function no(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!Vr(t))return;let o=t.parts||[],r=t.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,u=new Set,c=new Set,f=[];for(let d of o){if(typeof d=="string"){i.push({type:"text",text:d});continue}"text"in d&&"thought"in d&&d.thought&&r==="assistant"&&d.text&&s.push(d.text),"text"in d&&d.text&&!("thought"in d&&d.thought)&&i.push({type:"text",text:d.text});let g=uo(d,n);if(g&&r==="user"&&i.push(g),"functionCall"in d&&d.functionCall&&r==="assistant"){let h=d.functionCall.id;if(h){if(u.has(h)){V.debug(`Dropping duplicate functionCall id=${h} while converting content`);continue}u.add(h)}a.push({id:h||`call_${l}`,type:"function",function:{name:d.functionCall.name||"",arguments:JSON.stringify(d.functionCall.args||{})}}),l+=1}if(d.functionResponse&&r==="user"){let h=d.functionResponse.id;if(h){if(c.has(h))continue;c.add(h)}let m=Br(d.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(E=>E.text).join(`
11
+ `);m.content=S||"[media attached in following user message]",f.push(...C)}}e.push(m)}}}if(f.length>0&&e.push({role:"user",content:[{type:"text",text:so},...f]}),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),e.push(g);return}i.length>0&&e.push({role:"user",content:i})}function $r(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="object"){let e=t,n=e.output;if(typeof n=="string")return n;let o=e.error;if(typeof o=="string")return o}try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function Br(t,e){let n=$r(t.response),o=[];n&&o.push({type:"text",text:n});for(let r of t.parts||[]){if("text"in r&&typeof r.text=="string"){r.text.length>0&&o.push({type:"text",text:r.text});continue}let i=uo(r,e);i&&o.push(i)}return o.length===0?{role:"tool",tool_call_id:t.id||"",content:""}:{role:"tool",tool_call_id:t.id||"",content:o}}function uo(t,e){let{modalities:n}=e;if(t.inlineData?.mimeType&&t.inlineData?.data){let o=t.inlineData.mimeType,r=oo(o),i=t.inlineData.displayName||o;if(r==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${t.inlineData.data}`}}:re("image",i,e);if(o==="application/pdf")return n.pdf?{type:"file",file:{filename:t.inlineData.displayName||"document.pdf",file_data:`data:${o};base64,${t.inlineData.data}`}}:re("pdf",i,e);if(r==="audio"){if(!n.audio)return re("audio",i,e);let s=jr(o);if(s)return{type:"input_audio",input_audio:{data:`data:${o};base64,${t.inlineData.data}`,format:s}}}return r==="video"?n.video?{type:"video_url",video_url:{url:`data:${o};base64,${t.inlineData.data}`}}:re("video",i,e):{type:"text",text:`Unsupported inline media type: ${o} (${i}).`}}if(t.fileData?.mimeType&&t.fileData?.fileUri){let o=t.fileData.displayName||"file",r=t.fileData.fileUri,i=t.fileData.mimeType,s=oo(i);if(s==="image")return n.image?{type:"image_url",image_url:{url:r}}:re("image",o,e);if(i==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:r}}:re("pdf",o,e);if(s==="video")return n.video?{type:"video_url",video_url:{url:r}}:re("video",o,e);let a=t.fileData.displayName?` (${t.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${i}${a}.`}}return null}function re(t,e,n){V.warn(`Model '${n.model}' does not support ${t} input. Replacing with text placeholder: ${e}`);let o;return t==="pdf"?o=`This model does not support PDF input directly. The read_file tool cannot extract PDF content either. To extract text from the PDF file, try using skills if applicable, or guide user to install pdf skill by running this slash command:
12
+ /extensions install https://github.com/anthropics/skills:document-skills`:o=`This model does not support ${t} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`,{type:"text",text:`[Unsupported ${t} file: "${e}". ${o}]`}}function oo(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function jr(t){return t.includes("wav")?"wav":t.includes("mp3")||t.includes("mpeg")?"mp3":null}function Vr(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&Array.isArray(t.parts)}function co(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>co(e)).filter(Boolean).join(`
13
+ `):typeof t=="object"&&t!==null&&"parts"in t&&t.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
14
+ `)||""}function at(t,e,n=!0){if(e.taggedThinkingParser)return e.taggedThinkingParser.parse(t,n);if(e.responseParsingOptions?.taggedThinkingTags)return Qn(t);if(!t)return[];let o=ot(on(t));return o?[{text:o}]:[]}function zr(t,e){let n=t.choices?.[0],o=new te;if(n){let r=[];if(!e.responseParsingOptions?.taggedThinkingTags){let i=n.message.reasoning_content??n.message.reasoning;i&&r.push({text:i,thought:!0})}if(n.message.content&&r.push(...at(n.message.content,e)),n.message.tool_calls){for(let i of n.message.tool_calls)if(i.function){let s=Jn(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:po(n.finish_reason),index:0,safetyRatings:[]}]}else o.candidates=[];if(o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage){let r=t.choices?.[0]?.message,i=r?.reasoning_content??r?.reasoning??"",s=typeof r?.content=="string"?r.content:"";o.usageMetadata=ao(t.usage,{estimatedReasoningTokens:de(i.length),estimatedContentTokens:de(s.length)})}return o}function Wr(t,e){let n=t.choices?.[0],o=new te,r=e.toolCallParser;if(!r)throw new Error("convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start.");if(n){let i=[];if(!e.responseParsingOptions?.taggedThinkingTags){let u=n.delta?.reasoning_content??n.delta?.reasoning;if(u){let c=to(u,e.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});c&&i.push({text:c,thought:!0})}}if(typeof n.delta?.content=="string"){let u=to(n.delta.content,e.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(u||n.finish_reason)&&i.push(...at(u,e,!!n.finish_reason))}else n.finish_reason&&i.push(...at("",e,!0));if(n.delta?.tool_calls)for(let u of n.delta.tool_calls){let c=u.index??0;u.function?.arguments?r.addChunk(c,u.function.arguments,u.id,u.function.name):r.addChunk(c,"",u.id,u.function?.name)}let s=!1;if(n.finish_reason){s=r.hasIncompleteToolCalls();let u=r.getCompletedToolCalls();for(let c of u)c.name&&i.push({functionCall:{id:c.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:c.name,args:c.args}})}let a=s&&n.finish_reason!=="length"?"length":n.finish_reason,l={content:{parts:i,role:"model"},index:0,safetyRatings:[]};a&&(l.finishReason=po(a)),o.candidates=[l]}else o.candidates=[];return o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage&&(o.usageMetadata=ao(t.usage,Hr(e))),o}function qr(t){let e=t.toolCallParser;if(!e)return null;let n=[],o=e.getStrictCompletedToolCalls(),r=e.hasIncompleteToolCalls();for(let s of o)s.name&&n.push({functionCall:{id:s.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:s.name,args:s.args}});if(n.push(...at("",t,!0)),n.length===0&&!r)return null;let i=new te;return i.candidates=[{content:{parts:n,role:"model"},index:0,safetyRatings:[],finishReason:r?k.MAX_TOKENS:k.STOP}],i.responseId=`stream-flush-${Date.now()}`,i.createTime=new Date().getTime().toString(),i.modelVersion=t.model,i.promptFeedback={safetyRatings:[]},i}function Hr(t){return{estimatedReasoningTokens:de(t.reasoningDeltaState?.emittedLength??0),estimatedContentTokens:de(t.textDeltaState?.emittedLength??0)}}function po(t){return t?{stop:k.STOP,length:k.MAX_TOKENS,content_filter:k.SAFETY,function_call:k.STOP,tool_calls:k.STOP}[t]||k.FINISH_REASON_UNSPECIFIED:k.FINISH_REASON_UNSPECIFIED}function Jr(t){if(!t)return"stop";switch(t){case k.STOP:return"stop";case k.MAX_TOKENS:return"length";case k.SAFETY:case k.RECITATION:case k.BLOCKLIST:case k.PROHIBITED_CONTENT:case k.SPII:case k.IMAGE_SAFETY:case k.IMAGE_RECITATION:case k.IMAGE_PROHIBITED_CONTENT:case k.IMAGE_OTHER:return"content_filter";case k.NO_IMAGE:return"stop";default:return"stop"}}function rn(t){return t.role==="assistant"&&"tool_calls"in t&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0}function ro(t){if(t.role!=="user"||!("content"in t)||!Array.isArray(t.content))return!1;let e=t.content[0];return e?.type==="text"&&e.text===so}function Yr(t){let e=[],n=new Map,o=new Map,r=new Map,i=new Set,s=new Set;for(let a=0;a<t.length;a+=1){let l=t[a];if(rn(l)){let u=[],c=new Set;for(let C of l.tool_calls){let T=C.id;!T||s.has(T)||c.has(T)||(c.add(T),u.push(C))}let f=new Set,d=[],g=[],h=!1;for(let C=a+1;C<t.length;C+=1){let T=t[C];if(T.role==="tool"&&"tool_call_id"in T){if(!T.tool_call_id){h=!1;continue}c.has(T.tool_call_id)&&!f.has(T.tool_call_id)?(f.add(T.tool_call_id),d.push(C),h=!0):h=!1;continue}if(ro(T)){h&&g.push(C);continue}if(!(T.role==="assistant"&&!rn(T)))break}let m=u.filter(C=>f.has(C.id));for(let C of m)s.add(C.id);n.set(a,m),o.set(a,d),r.set(a,g)}}for(let a=0;a<t.length;a+=1){if(i.has(a))continue;let l=t[a];if(rn(l)){let u=l.reasoning_content,c=n.get(a)??[];if(c.length>0){let f={...l};f.tool_calls=c,e.push(f);for(let d of o.get(a)??[]){let g=t[d];g&&(e.push(g),i.add(d))}for(let d of r.get(a)??[]){let g=t[d];g&&(e.push(g),i.add(d))}}else if(typeof l.content=="string"&&l.content.trim()||u){let f={...l};delete f.tool_calls,e.push(f)}else V.debug(`cleanOrphanedToolCalls: dropping assistant with ${l.tool_calls.length} orphaned tool call(s) and no text/reasoning content`)}else l.role==="tool"&&"tool_call_id"in l?V.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):ro(l)?V.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):e.push(l)}return e}function io(t){let e=[];for(let n of t){if(n.role==="assistant"&&e.length>0){let o=e[e.length-1];if(o.role==="assistant"){let r="tool_calls"in o?o.tool_calls||[]:[],i="tool_calls"in n?n.tool_calls||[]:[],s=o.content,a=n.content,l=Array.isArray(s)||Array.isArray(a),u;if(l){let f=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[],d=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[];u=[...f,...d]}else u=[typeof s=="string"?s:"",typeof a=="string"?a:""].filter(Boolean).join("")||null;let c=[...r,...i];o.content=u||null,c.length>0&&(o.tool_calls=c);continue}}e.push(n)}return e}var lt={convertGeminiToolParametersToOpenAI:lo,convertGeminiToolsToOpenAI:Ur,convertGeminiRequestToOpenAI:Nr,convertGeminiResponseToOpenAI:Fr,convertOpenAIResponseToGemini:zr,convertOpenAIChunkToGemini:Wr,flushOpenAIStreamToGemini:qr};p();p();p();Ft();var Xr=new Set(["service.version","service.instance.id","session.id"]);function ie(t,e){We.warn(t),e?.push(t)}function fo(t,e){if(!t)return{};let n={};for(let o of t.split(",")){let r=o.trim();if(!r)continue;let i=r.indexOf("=");if(i<0){ie(`Skipping malformed OTEL_RESOURCE_ATTRIBUTES entry: "${r}" (hint: percent-encode literal commas as %2C)`,e);continue}let s=r.slice(0,i).trim();if(!s)continue;let a=r.slice(i+1).trim(),l;try{l=decodeURIComponent(s)}catch{ie(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,e),l=s}let u;try{u=decodeURIComponent(a)}catch{ie(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${l}", using raw value`,e),u=a}n[l]=u}return n}function sn(t,e,n){for(let o of Xr)o in t&&(ie(`${e} cannot override reserved key "${o}"; ignoring`,n),delete t[o]);return t}function go(t,e){if(t==null)return{};if(typeof t!="object"||Array.isArray(t))return ie("settings.telemetry.resourceAttributes must be an object; ignoring",e),{};let n={};for(let[o,r]of Object.entries(t)){let i=o.trim();if(!i){ie("settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",e);continue}typeof r=="string"?n[i]=r:ie(`settings.telemetry.resourceAttributes value for "${i}" must be a string (got ${typeof r}); ignoring`,e)}return n}function Pe(t){if(t!==void 0)return t==="true"||t==="1"}function mo(t){if(t!==void 0){if(t==="local"||t==="local")return"local";if(t==="gcp"||t==="gcp")return"gcp"}}async function Qr(t){let e=t.argv??{},n=t.env??{},o=t.settings??{},r=e.telemetry??Pe(n.MATILDA_TELEMETRY_ENABLED)??o.enabled,i=e.telemetryTarget??n.MATILDA_TELEMETRY_TARGET??o.target,s=mo(i);if(i!==void 0&&s===void 0)throw new Ut(`Invalid telemetry target: ${String(i)}. Valid values are: local, gcp`);let a=e.telemetryOtlpEndpoint??n.MATILDA_TELEMETRY_OTLP_ENDPOINT??n.OTEL_EXPORTER_OTLP_ENDPOINT??o.otlpEndpoint,l=e.telemetryOtlpProtocol??n.MATILDA_TELEMETRY_OTLP_PROTOCOL??o.otlpProtocol,u=["grpc","http"].find(G=>G===l);if(l!==void 0&&u===void 0)throw new Ut(`Invalid telemetry OTLP protocol: ${String(l)}. Valid values are: grpc, http`);let c=e.telemetryLogPrompts??Pe(n.MATILDA_TELEMETRY_LOG_PROMPTS)??o.logPrompts,f=Pe(n.MATILDA_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES)??o.includeSensitiveSpanAttributes??!1,d=e.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=sn(fo(n.OTEL_RESOURCE_ATTRIBUTES,C),"OTEL_RESOURCE_ATTRIBUTES",C),S=sn(go(o.resourceAttributes,C),"settings.telemetry.resourceAttributes",C),E={...T,...S},w=n.OTEL_SERVICE_NAME?.trim();w&&(E["service.name"]=w);let v=Object.keys(E).length?E:void 0,_=Pe(n.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??o.metrics?.includeSessionId??!1;return{enabled:r,target:s,otlpEndpoint:a,otlpProtocol:u,otlpTracesEndpoint:g,otlpLogsEndpoint:h,otlpMetricsEndpoint:m,logPrompts:c,includeSensitiveSpanAttributes:f,outfile:d,resourceAttributes:v,metrics:{includeSessionId:_},resourceAttributeWarnings:C.length?C:void 0}}p();Ft();import*as X from"node:fs";import*as Pt from"node:path";p();p();p();p();Ft();p();import{AsyncLocalStorage as Zr}from"node:async_hooks";var ho=new Zr;p();import*as K from"node:path";import{promises as dt}from"node:fs";p();p();import ei from"crypto";var ct=new Uint8Array(256),ut=ct.length;function an(){return ut>ct.length-16&&(ei.randomFillSync(ct),ut=0),ct.slice(ut,ut+=16)}p();var x=[];for(let t=0;t<256;++t)x.push((t+256).toString(16).slice(1));function Co(t,e=0){return x[t[e+0]]+x[t[e+1]]+x[t[e+2]]+x[t[e+3]]+"-"+x[t[e+4]]+x[t[e+5]]+"-"+x[t[e+6]]+x[t[e+7]]+"-"+x[t[e+8]]+x[t[e+9]]+"-"+x[t[e+10]]+x[t[e+11]]+x[t[e+12]]+x[t[e+13]]+x[t[e+14]]+x[t[e+15]]}p();p();import ti from"crypto";var ln={randomUUID:ti.randomUUID};function ni(t,e,n){if(ln.randomUUID&&!e&&!t)return ln.randomUUID();t=t||{};let o=t.random||(t.rng||an)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){n=n||0;for(let r=0;r<16;++r)e[n+r]=o[r];return e}return Co(o)}var un=ni;import*as Y from"os";var pt=N("OPENAI_LOGGER"),oi="########",ri=/^[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 ii(t,e){let n=e||process.cwd();if(!t)return K.join(n,"logs","openai");let o=t;return t==="~"||t.startsWith("~/")?o=K.join(Y.homedir(),t.slice(1)):K.isAbsolute(t)||(o=K.resolve(n,t)),K.normalize(o)}function yo(t){return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function si(t){let e=t.split("#");if(e.length!==3)return;let[,n,o]=e;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function ai(t){if(t)return le(t)?yo(t):yo(si(t))}function li(t){if(!t)return;let e=t.indexOf(oi);if(e>0)return t.slice(0,e);if(ri.test(t))return t;let n=t.split("#");if(n.length>=3&&n[0])return n[0]}function ui(t){let e=t?.trim(),n=li(e);return!e&&!n?null:{...e?{promptId:e}:{},...n?{sessionId:n}:{}}}var De=class{logDir;initialized=!1;constructor(e,n){this.logDir=ii(e,n)}async initialize(){if(!this.initialized)try{await dt.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(e){throw pt.error("Failed to initialize OpenAI logger:",e),new Error(`Failed to initialize OpenAI logger: ${e}`)}}async logInteraction(e,n,o,r){this.initialized||await this.initialize();let i=new Date().toISOString().replace(/:/g,"-"),s=un().slice(0,8),a=ai(r),l=a?`openai-${i}-${s}-${a}.json`:`openai-${i}-${s}.json`,u=K.join(this.logDir,l),c={timestamp:new Date().toISOString(),request:e,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:ui(r),system:{hostname:Y.hostname(),platform:Y.platform(),release:Y.release(),nodeVersion:process.version}};try{return await dt.writeFile(u,JSON.stringify(c,null,2),"utf-8"),u}catch(f){throw pt.error("Failed to write OpenAI log file:",f),new Error(`Failed to write OpenAI log file: ${f}`)}}async getLogFiles(e){this.initialized||await this.initialize();try{let o=(await dt.readdir(this.logDir)).filter(r=>r.startsWith("openai-")&&r.endsWith(".json")).map(r=>K.join(this.logDir,r)).sort().reverse();return e?o.slice(0,e):o}catch(n){return n.code==="ENOENT"?[]:(pt.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(e){try{let n=await dt.readFile(e,"utf-8");return JSON.parse(n)}catch(n){throw pt.error(`Failed to read log file ${e}:`,n),new Error(`Failed to read log file: ${n}`)}}},_l=new De;p();var ci="MATILDA_CODE_PROFILE_RUNTIME";function To(t=process.env){return t[ci]==="1"}var dn=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;requests=[];openaiWireRequests=[];tools=So();constructor(e={}){this.enabled=e.enabled??To(),this.now=e.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(e={}){this.enabled=e.enabled??To(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.tools=So()}isEnabled(){return this.enabled}recordGenerateContentRequest(e,n){this.enabled&&(this.requestIndex+=1,this.requests.push({index:this.requestIndex,timestamp:this.now(),source:n.source,model:e.model,stream:n.stream,serializedBytes:D(hi(e)),contents:Ao(e.contents),systemInstructionBytes:fi(e.config?.systemInstruction),generationConfigBytes:D(Eo(e.config)),tools:mi(e.config?.tools)}))}recordOpenAIWireRequest(e){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...di(e)}))}recordToolUse(e,n){if(!this.enabled)return;let o=D(n),r=this.getToolNameDiagnostics(e);r.uses+=1,r.argBytes+=o,r.maxArgBytes=Math.max(r.maxArgBytes,o),this.tools.toolUseCount+=1,this.tools.totalToolUseArgBytes+=o,this.tools.maxToolUseArgBytes=Math.max(this.tools.maxToolUseArgBytes,o)}recordToolResult(e){if(!this.enabled)return;let n=this.getToolNameDiagnostics(e.name);n.results+=1,n.resultBytes+=e.resultBytes,n.maxResultBytes=Math.max(n.maxResultBytes,e.resultBytes),e.isError&&(n.errors+=1,this.tools.toolResultErrorCount+=1),this.tools.toolResultCount+=1,this.tools.totalToolResultBytes+=e.resultBytes,this.tools.maxToolResultBytes=Math.max(this.tools.maxToolResultBytes,e.resultBytes)}snapshot(){return{enabled:this.enabled,startedAt:this.startedAt,requests:this.requests.map(e=>({...e,contents:{...e.contents,roleCounts:{...e.contents.roleCounts}},tools:{...e.tools}})),openaiWireRequests:this.openaiWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),tools:{...this.tools,byName:Object.fromEntries(Object.entries(this.tools.byName).map(([e,n])=>[e,{...n}]))}}}getToolNameDiagnostics(e){let n=this.tools.byName[e];if(n)return n;let o=pi();return this.tools.byName[e]=o,o}},pn=new dn;function di(t){let e=pe(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let i of n){let s=pe(i),a=typeof s.role=="string"?s.role:"unknown";r[a]=(r[a]??0)+D(s.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:D(t),messageCount:n.length,messageBytesByRole:r,toolsCount:o.length,toolSchemaBytes:D(o),topLevelKeys:Object.keys(e).sort()}}function So(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function pi(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function Ao(t){let e={count:0,roleCounts:{},partCount:0,textBytes:0,functionCallCount:0,functionCallArgBytes:0,functionResponseCount:0,functionResponseBytes:0,inlineDataCount:0,inlineDataBytes:0,fileDataCount:0},n=Array.isArray(t)?t:t==null?[]:[t];for(let o of n){if(e.count+=1,typeof o=="string"){e.roleCounts.user=(e.roleCounts.user??0)+1,e.partCount+=1,e.textBytes+=D(o);continue}let r=pe(o),i=typeof r.role=="string"?r.role:"unknown";e.roleCounts[i]=(e.roleCounts[i]??0)+1;let s=Array.isArray(r.parts)?r.parts:[];gi(s,e)}return e}function fi(t){return Ao(t).textBytes}function gi(t,e){for(let n of t){if(e.partCount+=1,typeof n=="string"){e.textBytes+=D(n);continue}let o=pe(n);typeof o.text=="string"&&(e.textBytes+=D(o.text));let r=cn(o.functionCall);r&&(e.functionCallCount+=1,e.functionCallArgBytes+=D(r.args));let i=cn(o.functionResponse);i&&(e.functionResponseCount+=1,e.functionResponseBytes+=D(i.response)+D(i.parts));let s=cn(o.inlineData);s&&(e.inlineDataCount+=1,e.inlineDataBytes+=D(s.data)),o.fileData&&(e.fileDataCount+=1)}}function mi(t){let e=Array.isArray(t)?t:[],n=0;for(let o of e){let r=pe(o),i=Array.isArray(r.functionDeclarations)?r.functionDeclarations:[];n+=i.length}return{count:e.length,functionDeclarationCount:n,schemaBytes:D(e)}}function hi(t){return{model:t.model,contents:t.contents,config:Eo(t.config)}}function Eo(t){if(!t)return;let e=pe(t),n={};for(let[o,r]of Object.entries(e))o!=="abortSignal"&&(n[o]=r);return n}function D(t){return t==null?0:typeof t=="string"?Buffer.byteLength(t,"utf8"):Buffer.byteLength(Ci(t),"utf8")}function Ci(t){try{return JSON.stringify(t)??""}catch{return"[unserializable]"}}function pe(t){return typeof t=="object"&&t!==null?t:{}}function cn(t){return typeof t=="object"&&t!==null?t:null}p();function Ro(t){let e=t.candidates?.[0]?.content?.parts;return!e||e.length===0?!1:e.some(yi)}function yi(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.text=="string"&&e.text.length>0||e.functionCall!==void 0||e.inlineData!==void 0||e.executableCode!==void 0||e.thought===!0}function bo(){let t=Dn.getStore();return{attempt:t?.attempt??1,requestSetupMs:t?.requestSetupMs,retryTotalDelayMs:t?.retryTotalDelayMs}}var se=N("LOGGING_CONTENT_GENERATOR"),Ti=4096,vo="...[truncated]",Si=Ti-vo.length,Le=class{constructor(e,n,o){this.wrapped=e;this.config=n;this.modalities=o.modalities,this.splitToolMedia=o.splitToolMedia,this.generatorAuthType=o.authType,o.enableOpenAILogging&&(this.openaiLogger=new De(o.openAILoggingDir,n.getWorkingDir()),this.schemaCompliance=o.schemaCompliance)}openaiLogger;schemaCompliance;modalities;splitToolMedia;generatorAuthType;getWrapped(){return this.wrapped}logApiRequest(e,n,o){let r=JSON.stringify(e);Gt(this.config,new Bt(n,o,r,q.getStore()))}_logApiResponse(e,n,o,r,i,s){$t(this.config,new Vt(e,o,n,r,this.generatorAuthType,i,s,q.getStore()))}_logApiError(e,n,o,r,i){let s=Nn(o),a=ke(o),l=o?.requestID||o?.request_id||e,u=W(o);Kt(this.config,new jt({responseId:l,model:r,durationMs:n,promptId:i,authType:this.generatorAuthType,errorMessage:s,errorType:a,statusCode:u,subagentName:q.getStore()}))}safelyLogApiError(e,n,o,r,i){try{this._logApiError(e,n,o,r,i)}catch(s){se.warn("Failed to log API error:",s)}}safelyLogApiResponse(e,n,o,r,i,s){try{this._logApiResponse(e,n,o,r,i,s)}catch(a){se.warn("Failed to log API response:",a)}}getClientVisibleModelId(e,n){return("isManagedMatildaModel"in this.config&&typeof this.config.isManagedMatildaModel=="function"?this.config.isManagedMatildaModel(e):!1)&&"getPublicModelId"in this.config&&typeof this.config.getPublicModelId=="function"?this.config.getPublicModelId(e):n||e}async generateContent(e,n){let o=bo(),r=Ye(e.model,n);try{r.setAttribute("llm_request.stream",!1)}catch{}let i=Nt.setSpan(B.active(),r),s=Date.now(),a=le(n),l=this.startCaptureSession();try{pn.recordGenerateContentRequest(e,{stream:!1,source:"generateContent"}),a||(qe(this.config,r,e.config?.systemInstruction),He(this.config,r,e.config?.tools));let u=await B.with(i,async()=>{a||this.logApiRequest(this.toContents(e.contents),e.model,n);let c=await l.wrap(()=>this.wrapped.generateContent(e,n)),f=Date.now()-s,d=a?void 0:this.extractResponseText(c);a||Je(this.config,r,d),this.safelyLogApiResponse(c.responseId??"",f,this.getClientVisibleModelId(e.model,c.modelVersion),n,c.usageMetadata,d);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),c,void 0,n)}catch(g){se.warn("Failed to log OpenAI interaction:",g)}return c});return ne(r,{success:!0,inputTokens:u.usageMetadata?.promptTokenCount,outputTokens:u.usageMetadata?.candidatesTokenCount,cachedInputTokens:u.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-s,responseId:u.responseId||void 0,finishReason:u.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:u.usageMetadata?.thoughtsTokenCount,subagentName:q.getStore()||void 0,...o}),u}catch(u){let c=Date.now()-s,f=e.config?.abortSignal?.aborted??!1;throw ne(r,{success:!1,durationMs:c,error:f?Qe:Xe,errorType:ke(u),errorStatusCode:W(u),subagentName:q.getStore()||void 0,...o}),await B.with(i,async()=>{this.safelyLogApiError("",c,u,this.getClientVisibleModelId(e.model),n);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,u,n)}catch(d){se.warn("Failed to log OpenAI interaction:",d)}}),u}}async generateContentStream(e,n){let o=bo(),r=Ye(e.model,n);try{r.setAttribute("llm_request.stream",!0)}catch{}let i=Nt.setSpan(B.active(),r),s=Date.now(),a=le(n),l=this.startCaptureSession(),u;try{pn.recordGenerateContentRequest(e,{stream:!0,source:"generateContentStream"}),a||(qe(this.config,r,e.config?.systemInstruction),He(this.config,r,e.config?.tools)),u=await B.with(i,async()=>(a||this.logApiRequest(this.toContents(e.contents),e.model,n),l.wrap(()=>this.wrapped.generateContentStream(e,n))))}catch(f){let d=Date.now()-s;B.with(i,()=>this.safelyLogApiError("",d,f,e.model,n));let g=e.config?.abortSignal?.aborted??!1;ne(r,{success:!1,durationMs:d,error:g?Qe:Xe,errorType:ke(f),errorStatusCode:W(f),subagentName:q.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,f,n)}catch(h){se.warn("Failed to log OpenAI interaction:",h)}throw f}let c;if(this.openaiLogger)try{c=await l.resolve(e)}catch(f){se.warn("Failed to resolve OpenAI request:",f)}return B.with(i,()=>this.loggingStreamWrapper(u,s,n,e.model,c,r,i,e.config?.abortSignal,o))}startCaptureSession(){let e,n=!this.openaiLogger;return{wrap:o=>n?o():ho.run(r=>{e=r},o),resolve:async o=>this.openaiLogger?e??await this.buildOpenAIRequestForLogging(o):void 0}}async*loggingStreamWrapper(e,n,o,r,i,s,a,l,u){let c=le(o),f=!c||!!this.openaiLogger,d=[],g="",h="",m,C=!1,T,S=!1,E,w=q.getStore(),v,_=!1,G=I=>a?B.with(a,I):I(),Dt=5*6e4,P,ae=s?()=>{_||(P!==void 0&&clearTimeout(P),P=setTimeout(()=>{try{s.setAttribute("stream.timed_out",!0)}catch{}ne(s,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:g||void 0,subagentName:w||void 0,...u}),_=!0},Dt),P.unref())}:void 0;try{for await(let L of e){!g&&L.responseId&&(g=L.responseId),!h&&L.modelVersion&&(h=L.modelVersion),f&&d.push(L),L.usageMetadata&&(m=L.usageMetadata);let ve=L.candidates?.[0];ve?.finishReason&&(T=ve.finishReason),L.functionCalls?.length&&(S=!0),v===void 0&&Ro(L)&&(v=Date.now()-n),ae?.(),yield L,P!==void 0&&(clearTimeout(P),P=void 0)}P!==void 0&&(clearTimeout(P),P=void 0);let I=Date.now()-n,Q=f?this.consolidateGeminiResponsesForLogging(d):void 0,Be=c?void 0:this.extractResponseText(Q),Z=!T&&!S?new Error("Model stream ended without a finish reason"):void 0;Z&&(C=!0,E=Z),_||(Z?(G(()=>this.safelyLogApiError(g,I,Z,this.getClientVisibleModelId(r,h),o)),await G(()=>this.safelyLogOpenAIInteraction(i,Q,Z,o))):(G(()=>this.safelyLogApiResponse(g,I,this.getClientVisibleModelId(r,h),o,m,Be)),!c&&s&&Je(this.config,s,Be),await G(()=>this.safelyLogOpenAIInteraction(i,Q,void 0,o))))}catch(I){if(C=!0,E=I,!_){let Q=Date.now()-n;G(()=>this.safelyLogApiError(g,Q,I,this.getClientVisibleModelId(r,h),o)),await G(()=>this.safelyLogOpenAIInteraction(i,void 0,I,o))}throw I}finally{if(P!==void 0&&clearTimeout(P),s&&!_){let I=l?.aborted??!1;ne(s,{success:!C,inputTokens:m?.promptTokenCount,outputTokens:m?.candidatesTokenCount,cachedInputTokens:m?.cachedContentTokenCount,ttftMs:v,durationMs:Date.now()-n,error:C?I?Qe:Xe:void 0,responseId:g||void 0,finishReason:T,thoughtsTokenCount:m?.thoughtsTokenCount,subagentName:w||void 0,errorType:E?ke(E):void 0,errorStatusCode:E?W(E):void 0,...u})}}}async buildOpenAIRequestForLogging(e){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(e.model),o=lt.convertGeminiRequestToOpenAI(e,n,{cleanOrphanToolCalls:!1}),r={model:e.model,messages:o};return e.config?.tools&&(r.tools=await lt.convertGeminiToolsToOpenAI(e.config.tools,this.schemaCompliance??"auto")),e.config?.temperature!==void 0&&(r.temperature=e.config.temperature),e.config?.topP!==void 0&&(r.top_p=e.config.topP),e.config?.maxOutputTokens!==void 0&&(r.max_tokens=e.config.maxOutputTokens),e.config?.presencePenalty!==void 0&&(r.presence_penalty=e.config.presencePenalty),e.config?.frequencyPenalty!==void 0&&(r.frequency_penalty=e.config.frequencyPenalty),r}createLoggingRequestContext(e){return{model:e,modalities:this.modalities??{},splitToolMedia:this.splitToolMedia??!0,startTime:0}}async logOpenAIInteraction(e,n,o,r){if(!this.openaiLogger||!e)return;let i=n?this.convertGeminiResponseToOpenAIForLogging(n,e):void 0;await this.openaiLogger.logInteraction(e,i,o instanceof Error?o:o?new Error(String(o)):void 0,r)}async safelyLogOpenAIInteraction(e,n,o,r){try{await this.logOpenAIInteraction(e,n,o,r)}catch(i){se.warn("Failed to log OpenAI interaction:",i)}}convertGeminiResponseToOpenAIForLogging(e,n){let o=new te;return Object.assign(o,e),o.modelVersion=this.getClientVisibleModelId(n.model,e.modelVersion),lt.convertGeminiResponseToOpenAI(o,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(e){if(e.length===0)return;let n=new te,o=[],r=new Map,i,s;for(let u of e){u.usageMetadata&&(s=u.usageMetadata);let c=u.candidates?.[0];c?.finishReason&&(i=c.finishReason);let f=c?.content?.parts??[];for(let d of f){if(typeof d=="string"){o.push({text:d});continue}if("text"in d){d.text&&o.push({text:d.text,...d.thought?{thought:!0}:{},...d.thoughtSignature?{thoughtSignature:d.thoughtSignature}:{}});continue}if("functionCall"in d&&d.functionCall){let g=d.functionCall.id||d.functionCall.name||"tool_call",h=r.get(g),m={functionCall:d.functionCall};h!==void 0?o[h]=m:(r.set(g,o.length),o.push(m));continue}if("functionResponse"in d&&d.functionResponse){o.push({functionResponse:d.functionResponse});continue}o.push(d)}}let a=e[e.length-1],l=a.candidates?.[0];return n.responseId=a.responseId,n.createTime=a.createTime,n.modelVersion=a.modelVersion,n.promptFeedback=a.promptFeedback,n.usageMetadata=s,n.candidates=[{content:{role:l?.content?.role||"model",parts:o},...i?{finishReason:i}:{},index:0,safetyRatings:l?.safetyRatings||[]}],n}extractResponseText(e){let n=e?.candidates?.[0]?.content?.parts;if(!n?.length)return;let o="",r=!1,i=!1,s=a=>{if(r=!0,i)return;let l=Si-o.length;if(a.length<=l){o+=a;return}o+=a.slice(0,Math.max(0,l)),i=!0};for(let a of n){if(typeof a=="string"){s(a);continue}"text"in a&&typeof a.text=="string"&&!("thought"in a&&a.thought)&&s(a.text)}if(r)return i?`${o}${vo}`:o}async countTokens(e){return this.wrapped.countTokens(e)}async embedContent(e){return this.wrapped.embedContent(e)}useSummarizedThinking(){return this.wrapped.useSummarizedThinking()}toContents(e){return Array.isArray(e)?e.map(n=>this.toContent(n)):[this.toContent(e)]}toContent(e){return Array.isArray(e)?{role:"user",parts:this.toParts(e)}:typeof e=="string"?{role:"user",parts:[{text:e}]}:"parts"in e?{...e,parts:e.parts?this.toParts(e.parts.filter(n=>n!=null)):[]}:{role:"user",parts:[this.toPart(e)]}}toParts(e){return e.map(n=>this.toPart(n))}toPart(e){if(typeof e=="string")return{text:e};if("thought"in e&&e.thought){let n=`[Thought: ${e.thought}]`,o={...e};if(delete o.thought,"functionCall"in o||"functionResponse"in o||"inlineData"in o||"fileData"in o)return o;let i=o.text,s=i?String(i):"",a=s?`${s}
15
+ ${n}`:n;return{...o,text:a}}return e}};p();var fn="x-matilda-organization-id",Ai=/^[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 ou(t){if(t!==void 0){if(typeof t!="string"||t.length!==36||!Ai.test(t))throw new Error("--organization-id must be a single UUID.");return t.toLowerCase()}}function gn(t){if(t)try{let e=new URL(t);if((e.hostname==="matilda.maincode.com"&&e.protocol==="https:"&&!e.port||e.hostname==="core-api.matilda"&&(e.protocol==="http:"||e.protocol==="https:"))&&!e.username&&!e.password&&!e.search&&!e.hash)return e}catch{}}function mn(t,e,n){if(e===void 0&&n===void 0)return;let o=gn(t.baseUrl);if(!o||o.pathname.replace(/\/$/,"")!=="/api/v1/code"||t.authType!=="openai")throw new Error("Organization selection and credit spending require the first-party Matilda Core Code endpoint.")}function Mo(t){for(let e of Object.keys(t??{})){let n=e.toLowerCase();if(n===fn)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 ru(t,e,n,o,r){mn(n,o,r);let i=gn(n.baseUrl),s=gn(t instanceof Request?t.url:String(t));if(!s||s.origin!==i.origin||s.pathname!=="/api/v1/code/chat/completions")throw new Error("The selected organization cannot be sent to this endpoint.");let a=e.get(fn);if(a!==null&&a!==o)throw new Error("The request organization conflicts with --organization-id.");o!==void 0&&e.set(fn,o)}p();function ko(t){switch(t){case"openai":return"OPENAI_API_KEY";default:return"API_KEY"}}function _o(t){switch(t){case"openai":return"OPENAI_MODEL";default:return"MODEL"}}var fe=class extends Error{constructor(e){super(e),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},ft=class extends fe{code="STRICT_MISSING_CREDENTIALS";constructor(e,n,o){let r=e||"(unknown)",i=n||"(unknown)";super(`Missing credentials for modelProviders model '${i}'. `+(o?`Current configured envKey: '${o}'. Set that environment variable, or update modelProviders.${r}[].envKey.`:`Configure modelProviders.${r}[].envKey and set that environment variable.`))}},gt=class extends fe{code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},mt=class extends fe{code="MISSING_API_KEY";constructor(e){super(`Missing API key for ${e.authType} auth. Current model: '${e.model||"(unknown)"}', baseUrl: '${e.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${e.envKey}'.`)}},ht=class extends fe{code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}};p();import Tn from"node:process";p();function uu(t,e,n,o=2048){let r=e-n-o;return!Number.isFinite(r)||r<=0?0:Math.min(t,r)}var b={"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 Ct(t){let e=(t??"").toLowerCase().trim();return e=e.replace(/^.*\//,""),e=e.split("|").pop()??e,e=e.split(":").pop()??e,e=e.replace(/\s+/g,"-"),e=e.replace(/-preview/g,""),e.match(/^kimi-k2-\d{4}$/)||(e=e.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g,"")),e=e.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g,""),e}var Ei=[[/^gemini-3/,b["1m"]],[/^gemini-/,b["1m"]],[/^gpt-5/,b["272k"]],[/^gpt-/,b["128k"]],[/^o\d/,b["200k"]],[/^claude-/,b["200k"]],[/^glm-5(\.[01])?(-|$)/,202752],[/^glm-(?:[5-9]|\d{2,})/,b["1m"]],[/^glm-/,202752],[/^matilda-code$/,b["1m"]],[/^matilda/,b["256k"]],[/^ornith/,b["64k"]],[/^kimi-/,b["256k"]],[/^seed-oss/,b["512k"]]],wo=[[/^gemini-3/,b["64k"]],[/^gemini-/,b["8k"]],[/^gpt-5/,b["128k"]],[/^gpt-/,b["16k"]],[/^o\d/,b["128k"]],[/^claude-opus-4-6/,b["128k"]],[/^claude-sonnet-4-6/,b["64k"]],[/^claude-/,b["64k"]],[/^glm-5\.2/,b["64k"]],[/^glm-5/,b["64k"]],[/^glm-4\.7/,b["16k"]],[/^matilda-code$/,b["64k"]],[/^matilda$/,b["64k"]],[/^matilda-core$/,b["64k"]],[/^ornith/,b["32k"]],[/^kimi-k2\.5/,b["32k"]]];function Ri(t,e="input"){let n=Ct(t),o=e==="output"?wo:Ei;for(let[r,i]of o)if(r.test(n))return i}function cu(t){let e=Ct(t);return wo.some(([n])=>n.test(e))}function bi(t,e="input"){return Ri(t,e)}function yt(t,e="input"){return bi(t,e)??(e==="output"?32e3:131072)}p();p();var xo={image:!0,pdf:!0,audio:!0,video:!0},vi=[[/^gemini-3/,xo],[/^gemini-/,xo],[/^gpt-5/,{image:!0}],[/^gpt-/,{image:!0}],[/^o\d/,{image:!0}],[/^claude-/,{image:!0,pdf:!0}],[/^glm-4\.5v/,{image:!0}],[/^glm-5(?:-|$)/,{}],[/^glm-/,{}],[/^kimi-k2\.5/,{image:!0,video:!0}],[/^kimi-/,{}],[/^doubao-seed(ance|ream)/,{}],[/^doubao-seed/,{image:!0}],[/^doubao-.*(vision|vl)/,{image:!0}],[/^doubao/,{}]];function Tt(t){let e=Ct(t);for(let[n,o]of vi)if(n.test(e))return{...o};return{}}p();function Io(t,e,n={kind:"default"}){for(let o of t)if(Oo(o.value))return{value:o.value,source:o.source};return{value:e,source:n}}function hn(t){for(let e of t)if(Oo(e.value))return{value:e.value,source:e.source}}function Oo(t){return!(t==null||typeof t=="string"&&t.trim()==="")}function St(t){return{kind:"cli",detail:t}}function Mi(t){return{kind:"env",envKey:t}}function Ue(t){return{kind:"settings",settingsPath:t}}function ge(t,e,n){return{kind:"modelProviders",authType:t,modelId:e,detail:n}}function Po(t){return{kind:"default",detail:t}}function At(t){return{kind:"computed",detail:t}}function Et(t,e,n){let o=t[e];return{value:o!==void 0?n?n(o):o:void 0,source:Mi(e)}}function U(t,e){return{value:t,source:e}}p();var me=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","openAIRequestProfile"],Do=["model","apiKey","apiKeyEnvKey","baseUrl"],Rt=[...Do,...me],Lo={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","MATILDA_MODEL"]}},Uo={openai:et};var he="MATILDA_API_KEY",ki="matilda-code-1.0";function _i(t,e){if(!t)return!0;try{let{hostname:n}=new URL(t);return n==="matilda.maincode.com"||n.endsWith(".matilda.maincode.com")||Ze(t,e)}catch{return!1}}function wi(t,e,n,o){if(o?.timeout!==void 0)return;let r=t.MATILDA_CODE_API_TIMEOUT_MS;if(r===void 0)return;let i=Number(r);Number.isFinite(i)&&i>0&&(e.timeout=Math.floor(i),n.timeout={kind:"env",envKey:"MATILDA_CODE_API_TIMEOUT_MS"})}function Mu(t){let{authType:e,cli:n,settings:o,env:r,modelProvider:i,proxy:s}=t,a=[],l={},u=e?Lo[e]:{model:[],apiKey:[],baseUrl:[]},c=[];e&&i&&c.push(U(i.id,ge(e,i.id,"model.id"))),n?.model&&c.push(U(n.model,St("--model"))),e==="openai"&&r[he]&&!r.OPENAI_MODEL&&!r.MATILDA_MODEL&&c.push(U(ki,{kind:"env",envKey:he}));for(let v of u.model)c.push(Et(r,v));o?.model&&c.push(U(o.model,Ue("model.name")));let f=e?Uo[e]:"",d=Io(c,f,Po(f));l.model=d.source;let g=[];if(e&&i?.envKey){let v=r[i.envKey];v&&g.push(U(v,{kind:"env",envKey:i.envKey,via:ge(e,i.id,"envKey")}))}if(n?.apiKey&&g.push(U(n.apiKey,St("--openaiApiKey"))),!i?.envKey){let v=r[he];e==="openai"&&v&&_i(r.OPENAI_BASE_URL,r)&&g.push(U(v,{kind:"env",envKey:he}));for(let _ of u.apiKey)g.push(Et(r,_))}o?.apiKey&&g.push(U(o.apiKey,Ue("security.auth.apiKey")));let h=hn(g);h&&(l.apiKey=h.source);let m=[];e&&i?.baseUrl&&m.push(U(i.baseUrl,ge(e,i.id,"baseUrl"))),n?.baseUrl&&m.push(U(n.baseUrl,St("--openaiBaseUrl"))),e==="openai"&&r[he]&&!r.OPENAI_BASE_URL&&m.push(U(oe(r),{kind:"env",envKey:he}));for(let v of u.baseUrl)m.push(Et(r,v));o?.baseUrl&&m.push(U(o.baseUrl,Ue("security.auth.baseUrl")));let C=hn(m);C&&(l.baseUrl=C.source);let T;e&&i?.envKey&&(T=i.envKey,l.apiKeyEnvKey={...ge(e,i.id,"envKey"),envKey:i.envKey});let S=bt(o?.generationConfig,i?.generationConfig,e,i?.id??d.value,r),E=S.config;Object.assign(l,S.sources);let w={authType:e,model:d.value||"",apiKey:h?.value,apiKeyEnvKey:T,baseUrl:C?.value,proxy:s,...E};return s&&(l.proxy=At("Config.getProxy()")),l.authType=At("provided by caller"),{config:w,sources:l,warnings:a}}function bt(t,e,n,o,r){let i={},s=xi(t,e,n,o,i);return wi(r,s,i,e),{config:s,sources:i}}function xi(t,e,n,o,r){let i={};for(let s of me)n&&e&&s in e?(i[s]=e[s],r[s]=ge(n,o||"",`generationConfig.${s}`)):t&&s in t&&(i[s]=t[s],r[s]=Ue(`model.generationConfig.${s}`));return i.modalities===void 0&&o&&(i.modalities=Tt(o),r.modalities=At("auto-detected from model")),i}p();var vt="$runtime|";function xu(t){let e=t;for(;e.startsWith(vt);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}p();p();var No="https://api.openai.com/v1";p();var yn=N("MODEL_REGISTRY");function Fo(t){if(Object.values($).includes(t))return t}function Go(t,e){return e?`${t}\0${e}`:t}var Mt=class{modelsByAuthType;getDefaultBaseUrl(e){switch(e){case"openai":return No;default:return""}}constructor(e){if(this.modelsByAuthType=new Map,e)for(let[n,o]of Object.entries(e)){let r=Fo(n);if(!r){yn.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values($).join(", ")}. Skipping.`);continue}this.registerAuthTypeModels(r,o)}}registerAuthTypeModels(e,n){let o=new Map;for(let r of n){let i=Go(r.id,r.baseUrl);if(o.has(i)){yn.warn(`Duplicate model id "${r.id}"${r.baseUrl?` with baseUrl "${r.baseUrl}"`:""} for authType "${e}". Using the first registered config.`);continue}let s=this.resolveModelConfig(r,e);o.set(i,s)}this.modelsByAuthType.set(e,o)}getModelsForAuthType(e){let n=this.modelsByAuthType.get(e);return n?Array.from(n.values()).map(o=>({id:o.id,label:o.name,description:o.description,capabilities:o.capabilities,authType:o.authType,isVision:o.capabilities?.vision??!1,contextWindowSize:o.generationConfig.contextWindowSize??yt(o.id),modalities:o.generationConfig.modalities??Tt(o.id),baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(e,n,o){let r=this.modelsByAuthType.get(e);if(!r)return;if(o)return r.get(Go(n,o));let i=r.get(n);if(i)return i;for(let s of r.values())if(s.id===n)return s}hasModel(e,n,o){return this.getModel(e,n,o)!==void 0}getDefaultModelForAuthType(e){let n=this.modelsByAuthType.get(e);if(!(!n||n.size===0))return Array.from(n.values())[0]}resolveModelConfig(e,n){return this.validateModelConfig(e,n),{...e,authType:n,name:e.name||e.id,baseUrl:e.baseUrl||this.getDefaultBaseUrl(n),generationConfig:{...e.generationConfig??{}},capabilities:e.capabilities||{}}}validateModelConfig(e,n){if(!e.id)throw new Error(`Model config in authType '${n}' missing required field: id`)}reloadModels(e){if(this.modelsByAuthType.clear(),e)for(let[n,o]of Object.entries(e)){let r=Fo(n);if(!r){yn.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values($).join(", ")}. Skipping.`);continue}this.registerAuthTypeModels(r,o)}}};var Ko=class t{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;hasManualCredentials=!1;onModelChange;authTypeWasExplicitlyProvided;settingsGenerationConfig;runtimeModelSnapshots=new Map;activeRuntimeModelSnapshotId;static deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>t.deepClone(o));let n={};for(let o of Object.keys(e))n[o]=t.deepClone(e[o]);return n}constructor(e={}){this.modelRegistry=new Mt(e.modelProvidersConfig),this.onModelChange=e.onModelChange,this._generationConfig={...e.generationConfig||{}},this.generationConfigSources=e.generationConfigSources||{},this.settingsGenerationConfig=t.deepClone(e.settingsGenerationConfig),this.authTypeWasExplicitlyProvided=e.initialAuthType!==void 0,this.currentAuthType=e.initialAuthType}createStateSnapshotForRollback(){return{currentAuthType:this.currentAuthType,generationConfig:t.deepClone(this._generationConfig),generationConfigSources:t.deepClone(this.generationConfigSources),strictModelProviderSelection:this.strictModelProviderSelection,hasManualCredentials:this.hasManualCredentials,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(e){this.currentAuthType=e.currentAuthType,this._generationConfig=e.generationConfig,this.generationConfigSources=e.generationConfigSources,this.strictModelProviderSelection=e.strictModelProviderSelection,this.hasManualCredentials=e.hasManualCredentials,this.activeRuntimeModelSnapshotId=e.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||et}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModelsForAuthType(this.currentAuthType):[]}getAvailableModelsForAuthType(e){return this.modelRegistry.getModelsForAuthType(e)}getAllConfiguredModels(e){let n=e&&e.length>0?e:Object.values($),o=new Set,r=[];for(let a of n)o.has(a)||(o.add(a),r.push(a));let i=this.getRuntimeModelOption(),s=[];for(let a of r)i&&i.authType===a&&s.push(i),s.push(...this.modelRegistry.getModelsForAuthType(a));return s}hasModel(e,n){return this.modelRegistry.hasModel(e,n)}getResolvedModel(e,n){let o=this.modelRegistry.getModel(e,n);if(o)return{...o,generationConfig:this.resolveEntryGenerationConfig(o).config}}resolveEntryGenerationConfig(e){return bt(this.settingsGenerationConfig,e.generationConfig,e.authType,e.id,Tn.env)}isManagedMatildaResolvedModel(e){return e?.id===zt&&e?.envKey===Fn&&e?.baseUrl===Kn&&e?.generationConfig?.openAIRequestProfile==="matilda-code"}isManagedMatildaModel(e){let n=e.trim();return!n||!this.currentAuthType?!1:this.isManagedMatildaResolvedModel(this.modelRegistry.getModel(this.currentAuthType,n))}getPublicModelId(e){return this.isManagedMatildaModel(e)?zt:e}getModelDisplayName(e){return this.isManagedMatildaModel(e)?Gn:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,e)?.name??e:e}async setModel(e,n){if(this.currentAuthType&&this.modelRegistry.hasModel(this.currentAuthType,e)){await this.switchModel(this.currentAuthType,e);return}let o=this.createStateSnapshotForRollback();try{this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.applyRawModelDerivedDefaults(e),this.onModelChange&&this.currentAuthType&&await this.onModelChange(this.currentAuthType)}catch(r){throw this.rollbackToStateSnapshot(o),r}}applyRawModelDerivedDefaults(e){let n=bt(this.settingsGenerationConfig,void 0,this.currentAuthType,e,Tn.env);this.shouldUpdateModelDerivedDefault("modalities")&&this.applyResolvedField("modalities",n),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this.applyResolvedField("contextWindowSize",n),this.fillContextWindowSize(e))}applyResolvedField(e,n){this._generationConfig[e]=t.deepClone(n.config[e]);let o=n.sources[e];o?this.generationConfigSources[e]=o:delete this.generationConfigSources[e]}fillContextWindowSize(e){this._generationConfig.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=yt(e,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"})}shouldUpdateModelDerivedDefault(e){let n=this.generationConfigSources[e];return n===void 0||n.kind==="computed"||n.kind==="default"||n.kind==="modelProviders"||n.kind==="programmatic"||n.kind==="unknown"}async switchModel(e,n,o){let r=this.extractRuntimeModelSnapshotId(n);if(r){await this.switchToRuntimeModel(r);return}let i=this.createStateSnapshotForRollback();try{let s=e!==this.currentAuthType;this.currentAuthType=e;let a=this.modelRegistry.getModel(e,n,o?.baseUrl);if(!a)throw new Error(`Model '${n}' not found for authType '${e}'`);let l=i.generationConfig.model||"",u=!s&&l?this.modelRegistry.getModel(e,l,i.generationConfig.baseUrl)??this.modelRegistry.getModel(e,l):void 0,c=!s&&!!i.generationConfig.apiKey&&!!a.envKey&&u?.envKey===a.envKey&&u.baseUrl===a.baseUrl,f=c?i.generationConfig.apiKey:void 0,d=c?i.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(a),!this._generationConfig.apiKey&&f&&(this._generationConfig.apiKey=f,d&&(this.generationConfigSources.apiKey=t.deepClone(d))),this.activeRuntimeModelSnapshotId=void 0,this.onModelChange&&await this.onModelChange(e)}catch(s){throw this.rollbackToStateSnapshot(i),s}}buildRuntimeModelSnapshotId(e,n){return`${vt}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(vt))return this.runtimeModelSnapshots.has(e)?e:void 0;if(this.runtimeModelSnapshots.has(e))return e}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}mergeSettingsGenerationConfig(e){if(e)for(let n of me)!(n in this._generationConfig)&&n in e&&(this._generationConfig[n]=e[n],this.generationConfigSources[n]={kind:"settings",detail:`model.generationConfig.${n}`})}updateCredentials(e,n){(e.apiKey||e.baseUrl||e.model)&&(this.hasManualCredentials=!0,this.clearProviderSourcedConfig()),e.apiKey&&(this._generationConfig.apiKey=e.apiKey,this.generationConfigSources.apiKey={kind:"programmatic",detail:"updateCredentials"}),e.baseUrl&&(this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"programmatic",detail:"updateCredentials"}),e.model&&(this._generationConfig.model=e.model,this.generationConfigSources.model={kind:"programmatic",detail:"updateCredentials"}),this.strictModelProviderSelection=!1,this._generationConfig.apiKeyEnvKey=void 0,n&&this.mergeSettingsGenerationConfig(n),this.syncRuntimeModelSnapshotWithCredentials()}syncRuntimeModelSnapshotWithCredentials(){let e=this.currentAuthType,{model:n,apiKey:o,baseUrl:r}=this._generationConfig;if(!(!n||!e||!o||!r)&&!this.modelRegistry.hasModel(e,n,r))if(this.activeRuntimeModelSnapshotId&&this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)){let i=this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);i.apiKey=o,i.baseUrl=r,i.modelId=n;let s=this.buildRuntimeModelSnapshotId(i.authType,i.modelId);s!==i.id&&(this.runtimeModelSnapshots.delete(i.id),i.id=s,this.runtimeModelSnapshots.set(s,i),this.activeRuntimeModelSnapshotId=s),i.createdAt=Date.now()}else this.detectAndCaptureRuntimeModel()}clearProviderSourcedConfig(){for(let e of Rt)this.generationConfigSources[e]?.kind==="modelProviders"&&(delete this._generationConfig[e],delete this.generationConfigSources[e])}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=!1}applyResolvedModelDefaults(e){if(this.strictModelProviderSelection=!0,this.hasManualCredentials=!1,this._generationConfig.model=e.id,this.generationConfigSources.model={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"model.id"},this._generationConfig.apiKey=void 0,this._generationConfig.apiKeyEnvKey=void 0,e.envKey!==void 0){let o=Tn.env[e.envKey];o&&(this._generationConfig.apiKey=o,this.generationConfigSources.apiKey={kind:"env",envKey:e.envKey,via:{kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}),this._generationConfig.apiKeyEnvKey=e.envKey,this.generationConfigSources.apiKeyEnvKey={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"baseUrl"};let n=this.resolveEntryGenerationConfig(e);for(let o of me)this.applyResolvedField(o,n);this.fillContextWindowSize(e.id)}syncAfterAuthRefresh(e,n){this.strictModelProviderSelection=!1;let o=this.currentAuthType;this.currentAuthType=e;let r=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,i=n?this.modelRegistry.getModel(e,n,r)??this.modelRegistry.getModel(e,n):void 0;if(i){let g=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==i.envKey||this._generationConfig.baseUrl!==i.baseUrl),h=o===e&&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"),E=S?this._generationConfig.baseUrl:void 0,w=S&&T?{...T}:void 0;this.applyResolvedModelDefaults(i),h&&!this._generationConfig.apiKey&&m&&(this._generationConfig.apiKey=m,C&&(this.generationConfigSources.apiKey=C)),E&&(this._generationConfig.baseUrl=E,w&&(this.generationConfigSources.baseUrl=w)),this.strictModelProviderSelection=!0,this.activeRuntimeModelSnapshotId=void 0;return}let s=this.generationConfigSources.apiKey,a=this.generationConfigSources.baseUrl,l=this._generationConfig.apiKey&&s?.kind!=="modelProviders"||this._generationConfig.baseUrl&&a?.kind!=="modelProviders";if(!(o!==e)&&(n===void 0||!this.modelRegistry.hasModel(e,n))&&(this.hasManualCredentials||l)){n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (preserved credentials)"}));return}let f=this.modelRegistry.getDefaultModelForAuthType(e);if(f){this.applyResolvedModelDefaults(f),this.activeRuntimeModelSnapshotId=void 0;return}n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (no default model)"}))}setOnModelChange(e){this.onModelChange=e}detectAndCaptureRuntimeModel(){let{model:e,apiKey:n,baseUrl:o,apiKeyEnvKey:r,...i}=this._generationConfig,s=this.currentAuthType;if(!e||!s)return;if(this.modelRegistry.hasModel(s,e,o)){this.clearRuntimeModelSnapshotForAuthType(s);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(s,e),u={id:l,authType:s,modelId:e,apiKey:n,baseUrl:o,apiKeyEnvKey:r,generationConfig:i,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(l,u),this.activeRuntimeModelSnapshotId=l,this.cleanupOldRuntimeModelSnapshots(),l}getActiveRuntimeModelSnapshot(){if(this.activeRuntimeModelSnapshotId)return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId)}getActiveRuntimeModelSnapshotId(){return this.activeRuntimeModelSnapshotId}async switchToRuntimeModel(e){let n=this.runtimeModelSnapshots.get(e);if(!n)throw new Error(`Runtime model snapshot '${e}' not found`);let o=this.createStateSnapshotForRollback();try{this.currentAuthType=n.authType,this.activeRuntimeModelSnapshotId=e,this.strictModelProviderSelection=!1,this.hasManualCredentials=!0,this._generationConfig.model=n.modelId,this.generationConfigSources.model={kind:"programmatic",detail:"runtimeModelSwitch"},n.apiKey&&(this._generationConfig.apiKey=n.apiKey,this.generationConfigSources.apiKey=n.sources.apiKey||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.baseUrl&&(this._generationConfig.baseUrl=n.baseUrl,this.generationConfigSources.baseUrl=n.sources.baseUrl||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.apiKeyEnvKey&&(this._generationConfig.apiKeyEnvKey=n.apiKeyEnvKey),n.generationConfig&&Object.assign(this._generationConfig,n.generationConfig),this.onModelChange&&await this.onModelChange(n.authType)}catch(r){throw this.rollbackToStateSnapshot(o),r}}getRuntimeModelOption(){let e=this.getActiveRuntimeModelSnapshot();if(e)return{id:e.modelId,label:e.modelId,authType:e.authType,isVision:!1,contextWindowSize:e.generationConfig?.contextWindowSize,isRuntimeModel:!0,runtimeSnapshotId:e.id}}clearRuntimeModelSnapshotForAuthType(e){for(let[n,o]of this.runtimeModelSnapshots.entries())o.authType===e&&(this.runtimeModelSnapshots.delete(n),this.activeRuntimeModelSnapshotId===n&&(this.activeRuntimeModelSnapshotId=void 0))}cleanupOldRuntimeModelSnapshots(){let e=new Map;for(let n of this.runtimeModelSnapshots.values()){let o=e.get(n.authType);(!o||n.createdAt>o.createdAt)&&e.set(n.authType,n)}this.runtimeModelSnapshots.clear();for(let n of e.values())this.runtimeModelSnapshots.set(n.id,n);this.activeRuntimeModelSnapshotId&&!this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)&&(this.activeRuntimeModelSnapshotId=void 0)}reloadModelProvidersConfig(e){this.modelRegistry.reloadModels(e)}};p();import{mkdirSync as ns,readFileSync as os}from"node:fs";import{dirname as rs,join as is}from"node:path";p();p();import{randomBytes as Ii,createHash as Oi}from"node:crypto";import{setTimeout as Pi}from"node:timers/promises";var Di="urn:ietf:params:oauth:grant-type:device_code";function $o(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function An(){let t=Ii(32).toString("base64url"),e=Oi("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function Ce(t,e){let n=typeof t=="object"&&t!==null?t:{};if(typeof n.access_token!="string"||n.access_token==="")throw new Error("The token response has no access token");return{accessToken:n.access_token,refreshToken:n.refresh_token??e?.refreshToken,expiresAt:Date.now()+(n.expires_in??3600)*1e3,idToken:n.id_token??e?.idToken}}var Li=15e3;async function En(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!$o(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(Li)});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 Ui=15e3,Sn="Device code expired: restart the sign-in";async function Rn(t,e,n={}){let o;try{o=await fetch(t,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,scope:e.scope??"openid offline_access"}),signal:Vo(AbortSignal.timeout(Ui),n.signal)})}catch(i){throw zo(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 Bo(t,e,n={}){let o=await fetch(t,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:Di,client_id:e.clientId,device_code:e.deviceCode}),signal:n.signal});if(o.ok)return{kind:"authorized",tokens:Ce(await o.json())};let r=await o.json().catch(()=>({})),i=typeof r.error=="string"?r.error:"unknown";switch(i){case"authorization_pending":return{kind:"pending"};case"slow_down":return{kind:"slow_down"};default:return{kind:"error",error:i}}}async function jo(t,e,n={}){let o=e.interval*1e3;try{for(;Date.now()<e.expiresAt;){await Pi(Math.min(o,e.expiresAt-Date.now()),void 0,{signal:n.signal});let r=e.expiresAt-Date.now();if(r<=0)break;let i=await Bo(t,e,{signal:Vo(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(Sn);case"access_denied":throw new Error("User denied the authorization request");default:throw new Error(`Device flow error: ${i.error}`)}}}}catch(r){throw zo(r,n.signal)?new Error(Sn):r}throw new Error(Sn)}function Vo(t,e){return e?AbortSignal.any([t,e]):t}function zo(t,e){return!e?.aborted&&t instanceof Error&&t.name==="TimeoutError"}p();import{randomBytes as Ni}from"node:crypto";import{promises as ye,openSync as Fi,closeSync as Gi,unlinkSync as qo,statSync as Ki}from"node:fs";import{dirname as $i}from"node:path";var Wo=new Map,Bi=2e4,ji=3e4,Vi=50;function bn(t,e={}){let n=async()=>{try{let s=await ye.readFile(t,"utf8"),a=JSON.parse(s);return a&&typeof a=="object"?a:{}}catch(s){if(s.code==="ENOENT")return{};throw s}},o=async(s,a)=>{await ye.mkdir($i(t),{recursive:!0});let l=`${t}.${process.pid}.${Ni(4).toString("hex")}.tmp`;try{await ye.writeFile(l,JSON.stringify(s,null,2),{mode:384}),a?.throwIfAborted(),await ye.rename(l,t)}catch(u){throw await ye.rm(l,{force:!0}).catch(()=>{}),u}await ye.chmod(t,384).catch(()=>{})},r=(s,a={})=>{let u=(Wo.get(t)??Promise.resolve()).then(async()=>{a.signal?.throwIfAborted();let c=await n(),f=!1;for(let[d,g]of Object.entries(s)){if(g===null){if(!(d in c))continue;delete c[d]}else{if(c[d]===g)continue;c[d]=g}f=!0}f&&await o(c,a.signal),a.onCommit?.()});return Wo.set(t,u.catch(()=>{})),u};return{store:{async get(s){return(await n())[s]??null},set:(s,a,l)=>r({[s]:a},l),remove:(s,a)=>r({[s]:null},a)},lock:zi(`${t}.lock`,e.lockTimeoutMs??Bi),update:r}}function zi(t,e){let n=Promise.resolve();return o=>{let r=n.then(async()=>{await Wi(t,e);try{return await o()}finally{qi(t)}});return n=r.then(()=>{},()=>{}),r}}async function Wi(t,e){let n=Date.now()+e;for(;;)try{Gi(Fi(t,"wx"));return}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-Ki(t).mtimeMs>ji){qo(t);continue}}catch{continue}if(Date.now()>n)throw Object.assign(new Error(`Timed out acquiring credential lock at ${t}`),{code:"ETIMEDOUT"});await Hi(Vi)}}function qi(t){try{qo(t)}catch{}}function Hi(t){return new Promise(e=>setTimeout(e,t))}p();var Te=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function vn(t){let e=t.storageKey??"default",n=t.fetchImpl??fetch,o=t.expirySkewMs??6e4,r=t.refreshTimeoutMs??15e3,i=null,s=async()=>{let u=await t.store.get(e);if(!u)return null;try{let c=JSON.parse(u);return c.accessToken?c:null}catch{return null}},a=u=>u.expiresAt-Date.now()>o,l=u=>t.lock(async()=>{let c=await s()??u;if(c.accessToken!==u.accessToken&&a(c))return c.accessToken;if(!c.refreshToken)throw new Te("No refresh token available \u2014 sign in again.");let f;try{let g=await n(t.tokenEndpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:c.refreshToken}),signal:AbortSignal.timeout(r)});if(!g.ok){let h=await g.text().catch(()=>"");throw g.status>=400&&g.status<500&&Ji(h)==="invalid_grant"?(await t.store.remove(e),new Te):Object.assign(new Error(`Token refresh failed (${g.status})`),{status:g.status})}f=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 d=Ce(f,c);return await t.store.set(e,JSON.stringify(d)),d.accessToken});return{async getAccessToken(u){let c=await s();if(!c)throw new Te("Not signed in.");return!u?.forceRefresh&&a(c)?c.accessToken:(i||(i=l(c).finally(()=>{i=null})),i)}}}function Ji(t){try{return JSON.parse(t).error}catch{return}}p();import{createServer as Yi}from"node:http";import{randomBytes as Xi}from"node:crypto";async function kt(t){if(t.transport.kind==="device")return Qi(t);if(t.transport.kind!=="loopback")throw new Error(`Unsupported login transport: ${t.transport.kind}`);if(t.signal?.aborted)throw new Error("Login aborted");let e=m=>t.onEvent?.(m),{codeVerifier:n,codeChallenge:o}=An(),r=Xi(16).toString("hex"),i=t.timeoutMs??5*60*1e3,s=t.transport.successRedirect,a=t.transport.port;e({type:"state",status:"idle"});let l,u,c=new Promise((m,C)=>{l=m,u=C});c.catch(()=>{});let f=Yi((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"),E=T.searchParams.get("state"),w=T.searchParams.get("code");if(S){let v=T.searchParams.get("error_description"),_=v?`OAuth error: ${S} (${v})`:`OAuth error: ${S}`;C.writeHead(400,{"content-type":"text/plain; charset=utf-8"}).end(`Sign-in failed: ${S}
16
+ `,()=>u(new Error(_)));return}if(E!==r){C.writeHead(400).end("State mismatch"),u(new Error("OAuth state mismatch"));return}if(!w){C.writeHead(400).end("Missing authorization code");return}Zi(C,s,()=>l(w))}),d=await new Promise((m,C)=>{f.once("error",C),f.listen(a??0,"127.0.0.1",()=>{m(f.address().port)})}),g=setTimeout(()=>u(new Error("Login timed out \u2014 the browser never reached the local callback. The hosted success page is not a completed sign-in.")),i),h=()=>u(new Error("Login aborted"));t.signal?.addEventListener("abort",h,{once:!0}),t.signal?.aborted&&h();try{t.signal?.throwIfAborted();let m=`http://127.0.0.1:${d}/callback`,C=new URL(t.metadata.authorization_endpoint);C.searchParams.set("client_id",t.clientId),C.searchParams.set("response_type","code"),C.searchParams.set("redirect_uri",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",t.scope??"openid offline_access");let T=C.toString();e({type:"authorize_url",url:T}),e({type:"state",status:"awaiting_user"}),t.openBrowser&&await t.openBrowser(T);let S=await c;await Ho(f),e({type:"state",status:"exchanging"});let E=await fetch(t.metadata.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,code:S,code_verifier:n,redirect_uri:m}),signal:t.signal});if(!E.ok){let v=await E.text().catch(()=>"");throw new Error(`Token exchange failed (${E.status}): ${v}`)}let w=Ce(await E.json());return e({type:"state",status:"authenticated"}),w}catch(m){throw e({type:"state",status:"error"}),t.signal?.aborted?new Error("Login aborted"):m}finally{clearTimeout(g),t.signal?.removeEventListener("abort",h),await Ho(f)}}async function Qi(t){let e=t.metadata.device_authorization_endpoint;if(!e)throw new Error("The authorization server does not offer device sign-in");if(t.signal?.aborted)throw new Error("Login aborted");let n=o=>t.onEvent?.(o);n({type:"state",status:"idle"});try{let o=await Rn(e,{clientId:t.clientId,scope:t.scope},{signal:t.signal});n({type:"user_code",userCode:o.userCode,verificationUri:o.verificationUri,verificationUriComplete:o.verificationUriComplete}),n({type:"state",status:"awaiting_user"});let r=await jo(t.metadata.token_endpoint,{clientId:t.clientId,deviceCode:o.deviceCode,interval:o.interval,expiresAt:o.expiresAt},{signal:t.signal});return n({type:"state",status:"authenticated"}),r}catch(o){throw n({type:"state",status:"error"}),t.signal?.aborted?new Error("Login aborted"):o}}function Ho(t){return t.listening?new Promise(e=>{t.close(()=>e()),t.closeAllConnections()}):Promise.resolve()}function Zi(t,e,n){t.writeHead(302,{location:e}).end(n)}p();var es=["www-browser"];function ts(t){let e=t.replace(/\\/g,"/").split("/").pop();return!!e&&es.includes(e)}function Jo(t={}){let n=process.env.BROWSER?.trim()?.match(/^\S+/)?.[0];if(!t.ignoreBrowserBlocklist&&process.platform!=="win32"&&n&&ts(n)||process.env.CI||process.env.DEBIAN_FRONTEND==="noninteractive")return!1;let o=!!process.env.SSH_CONNECTION;return!(process.platform==="linux"&&!["DISPLAY","WAYLAND_DISPLAY","MIR_SOCKET"].some(s=>!!process.env[s])||o&&process.platform!=="linux")}var Ae="matilda-code",Xo="matilda-desktop",Qo="openid profile email offline_access",Ne="MATILDA_API_KEY",ss="matilda";function Ee(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function Zo(){return is(ze.getGlobalMatildaDir(),"matilda-auth.json")}function wt(){let t=Zo();return ns(rs(t),{recursive:!0}),bn(t)}function as(t){return t==="desktop"}function Ge(t){return t?.clientId?t.clientId:as(t?.channel)?Xo:Ae}function Fe(t){return`matilda:${t}`}function xt(t){return`${Fe(t)}:refresh-rejected`}function Ke(t){return t===Ae?[Fe(t),ss]:[Fe(t)]}function ls(){try{let t=os(Zo(),"utf8");return JSON.parse(t)}catch{return{}}}function _t(t){if(!t)return null;try{let e=JSON.parse(t);return typeof e?.accessToken=="string"&&typeof e?.baseUrl=="string"?e:null}catch{return null}}function us(t,e){return Ee(t)===Ee(e)}function cs(t){if(!t)return{};try{let e=t.split(".")[1],n=Buffer.from(e.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(n);return{sub:o.sub,email:o.email,name:o.name}}catch{return{}}}function er(t,e){let n=cs(t.idToken);return{accessToken:t.accessToken,accessTokenExpiresAt:t.expiresAt,refreshToken:t.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:e}}var Yo=new Map;async function kn(t){let e=Yo.get(t);if(e)return e;try{let n=await En(t);return Yo.set(t,n),n}catch{return{issuer:t,authorization_endpoint:`${t}/api/auth/oauth/authorize`,token_endpoint:`${t}/api/auth/oauth/token`,device_authorization_endpoint:`${t}/api/auth/oauth/device/code`}}}function Re(t){try{let e=ls(),n=Ge(t);for(let o of Ke(n)){let r=_t(e[o]);if(r)return r}return null}catch{return null}}function tr(t){let e=Re(t);return!e||t?.baseUrl&&!us(e.baseUrl,t.baseUrl)?null:e}function _n(t){return tr(t)!==null}async function nr(t,e){for(let n of e){let o=await t.get(n);if(_t(o))return o}return null}async function ds(t,e){let n=Ge(t),o=Ke(n),{store:r,lock:i}=wt();await i(async()=>{let s=await nr(r,o);if(!(s!==null&&s!==e)){for(let a of o)await r.remove(a);await r.set(xt(n),"1"),delete process.env[Ne]}})}function ps(t){return t instanceof Error?t.code==="invalid_grant"||t.name==="InvalidGrantError"?!0:t.message==="Token refresh failed (401)":!1}function Se(t){Mn({authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:t.occurrenceCount},{baseUrl:t.baseUrl,token:t.token}).catch(()=>{})}async function or(t,e,n={}){let o=Ge(e),r=Fe(o),i={[r]:JSON.stringify(t),[xt(o)]:null};for(let l of Ke(o))l!==r&&(i[l]=null);let{lock:s,update:a}=wt();await s(()=>a(i,{signal:n.signal,onCommit:()=>{process.env[Ne]=t.accessToken}}))}async function fs(t,e){for(let n of Ke(e))await t.remove(n);await t.remove(xt(e)),delete process.env[Ne]}function Nc(t){let e=Re(t);return e?{authenticated:!0,userId:e.userId,email:e.email,displayName:e.displayName,baseUrl:e.baseUrl,accessTokenExpiresAt:e.accessTokenExpiresAt}:{authenticated:!1}}async function Fc(t){let e={channel:t?.channel,clientId:t?.clientId},{store:n,lock:o}=wt(),r=await o(async()=>{let i=Re(e);return await fs(n,Ge(e)),i});if(r?.accessToken){let i=Ee(r.baseUrl);await fetch(`${i}/api/auth/logout`,{method:"POST",headers:{authorization:`Bearer ${r.accessToken}`,"content-type":"application/json"},body:JSON.stringify(r.refreshToken?{refreshToken:r.refreshToken}:{}),signal:t?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}}async function rr(t){let e=Ge(t),n=Fe(e),o=tr({baseUrl:t?.baseUrl,channel:t?.channel,clientId:e});if(!o)return t?.fallbackAccessToken??process.env[Ne]??"";let r=Ee(o.baseUrl),i=await kn(r),{store:s,lock:a}=wt(),{manager:l,startedFrom:u}=gs(s,a,i.token_endpoint,o.baseUrl,e,n,t?.signal),c=e===Ae&&(!!t?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=3e5),f;try{f=await l.getAccessToken({forceRefresh:t?.forceRefresh})}catch(d){throw c&&Se({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"}),!ps(d)||d instanceof Ve?d:(e===Xo&&await ds({channel:t?.channel,clientId:e},u()),new Ve({cause:d}))}return c&&Se({baseUrl:o.baseUrl,token:f,authStage:"refresh",authOutcome:"succeeded"}),process.env[Ne]=f,f}function gs(t,e,n,o,r,i,s){let a=Ke(r),l=(g,h)=>{let m=[h?.signal,s].filter(C=>C instanceof AbortSignal);return fetch(g,{...h,signal:m.length>1?AbortSignal.any(m):m[0]})},u=g=>nr(t,g===i?a:[g]),c=null;return{manager:vn({tokenEndpoint:n,clientId:r,store:{get:async g=>{c=await u(g);let h=_t(c);if(!h?.accessToken)return null;let m={accessToken:h.accessToken,refreshToken:h.refreshToken,expiresAt:h.accessTokenExpiresAt};return JSON.stringify(m)},set:async(g,h)=>{let m=await u(g);if(m===null||m!==c)throw new Ve;let C=JSON.parse(h),T=_t(m)??{},S={...T,accessToken:C.accessToken,accessTokenExpiresAt:C.expiresAt,refreshToken:C.refreshToken??T.refreshToken??"",baseUrl:T.baseUrl??o};await t.set(i,JSON.stringify(S)),await t.remove(xt(r));for(let E of a)E!==i&&await t.remove(E)},remove:async g=>{if(await u(g)!==c)return;let h=g===i?a:[g];for(let m of h)await t.remove(m)}},storageKey:i,lock:e,fetchImpl:l,expirySkewMs:3e5}),startedFrom:()=>c}}function ms(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&Jo()}async function Gc(t){let e=Ee(t.baseUrl),n=await kn(e),o="",r=0,i=0,s={},a=f=>{s[f]=(s[f]??0)+1},u=await(f=>(r+=1,kt({metadata:n,clientId:Ae,scope:f,transport:{kind:"loopback",successRedirect:`${e}/api/auth/oauth/success?client_id=${encodeURIComponent(Ae)}`},signal:t.signal,onEvent:d=>{d.type==="authorize_url"&&(o=d.url,t.onAuthorizeUrl?.(d.url)),d.type==="state"&&d.status==="exchanging"&&(i+=1)},openBrowser:async d=>{if(t.openBrowser===!1||!ms()){a("skipped");return}try{let{default:g}=await import("./open-QQ7FWG4A.js");(await g(d)).once("error",()=>{}),a("succeeded")}catch{a("failed")}}})))(Qo),c=er(u,t.baseUrl);await or(c),Se({baseUrl:t.baseUrl,token:c.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:r});for(let[f,d]of Object.entries(s))Se({baseUrl:t.baseUrl,token:c.accessToken,authStage:"browser_opened",authOutcome:f,occurrenceCount:d});return i>0&&Se({baseUrl:t.baseUrl,token:c.accessToken,authStage:"callback_received",authOutcome:"succeeded",occurrenceCount:i}),Se({baseUrl:t.baseUrl,token:c.accessToken,authStage:"token_persisted",authOutcome:"succeeded"}),{...c,authorizeUrl:o}}async function Kc(t){let e=Ee(t.baseUrl),n=await kn(e),o=await kt({metadata:n,clientId:Ae,scope:Qo,transport:{kind:"device"},signal:t.signal,onEvent:i=>{i.type==="user_code"&&t.onDeviceCode({userCode:i.userCode,verificationUri:i.verificationUri,verificationUriComplete:i.verificationUriComplete})}}),r=er(o,t.baseUrl);return await or(r),r}p();p();p();function It(t){return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="object"&&"message"in t.error}function ir(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}p();function sr(t){let e=Math.max(1,t.attempt),n=Math.min(t.maxDelayMs,2147483647),o=Math.min(e-1,31),r=Math.min(t.initialDelayMs*Math.pow(2,o),n),s=(t.retryAfterMode??"ignore")==="ignore"?null:hs(t.error);if(s!==null&&s>0){let c=Math.min(t.retryAfterMaxDelayMs??t.maxDelayMs,2147483647),f=Math.min(s,c);return Math.max(r,f)}let a=t.jitterRatio??0;if(a<=0)return r;let l=t.random??Math.random,u=r*a*(l()*2-1);return Math.min(Math.max(0,r+u),n)}function hs(t){let e=ar(t,"retry-after")??Cs(t,"retry-after");if(e===null)return null;let n=e.trim();if(/^\d+(\.\d+)?$/.test(n)){let i=Number(n);if(Number.isFinite(i)&&i>=0)return Math.min(i*1e3,2147483647)}let o=Date.parse(n);if(!Number.isFinite(o))return null;let r=o-Date.now();return r>0?Math.min(r,2147483647):0}function ar(t,e){if(!ys(t))return null;let{headers:n}=t;if(typeof n.get=="function"){let r=n.get(e);return typeof r=="string"?r:null}if(typeof n!="object"||n===null)return null;let o=e.toLowerCase();for(let[r,i]of Object.entries(n))if(r.toLowerCase()===o)return typeof i=="string"?i:null;return null}function Cs(t,e){return Ts(t)?ar(t.response,e):null}function ys(t){return typeof t=="object"&&t!==null&&"headers"in t&&t.headers!=null}function Ts(t){return typeof t=="object"&&t!==null&&"response"in t&&typeof t.response=="object"&&t.response!==null&&"headers"in t.response&&t.response.headers!=null}var Ss=new Set([429,503,1302,1305]);function wn(t,e){if(xn(t))return!1;let n=Es(t);return n===null?!1:!!(Ss.has(n)||e&&e.includes(n))}function xn(t){return As(t)==="insufficient_quota"}function As(t){let e=ur(t)?.code;if(e!==void 0)return e;let n=typeof t=="object"&&t!==null&&"code"in t?t.code:void 0;return typeof n=="string"||typeof n=="number"?n:void 0}function lr(t){let e=W(t),n=ur(t),o=cr(t),r=o?.includes("event:error")||o?.includes("HTTP_STATUS/")?"sse":e!==void 0?"http":"unknown";return{...e!==void 0?{statusCode:e}:{},...n?.code!==void 0?{providerCode:String(n.code)}:{},...n?.message!==void 0?{providerMessage:n.message}:{},...n?.requestId!==void 0?{requestId:n.requestId}:{},transport:r}}function Yc(t,e){return sr({attempt:t,initialDelayMs:e.initialDelayMs,maxDelayMs:e.maxDelayMs,retryAfterMode:"minimum",retryAfterMaxDelayMs:e.maxDelayMs,error:e.error})}function Es(t){if(It(t)){let n=Number(t.error.code);if(Number.isFinite(n)&&n>0)return n}let e=t instanceof Error?t.message:typeof t=="string"?t:null;if(e){let n=e.indexOf("{");if(n!==-1)try{let o=JSON.parse(e.substring(n));if(It(o)){let r=Number(o.error.code);if(Number.isFinite(r)&&r>0)return r}}catch{}}if(ir(t)&&typeof t.status=="number")return t.status;if(t instanceof Error&&"status"in t){let n=t.status;if(typeof n=="number")return n}return W(t)??null}function ur(t){for(let e of Rs(t)){if(typeof e!="object"||e===null)continue;let n=e,o=e.error,i=(typeof o=="object"&&o!==null?o:void 0)??n,s=typeof i.code=="string"||typeof i.code=="number"?i.code:void 0,a=typeof i.message=="string"?i.message:void 0,l=typeof i.request_id=="string"?i.request_id:typeof i.requestId=="string"?i.requestId:typeof n.request_id=="string"?n.request_id:typeof n.requestId=="string"?n.requestId:void 0;if(s!==void 0||a!==void 0||l!==void 0)return{code:s,message:a,requestId:l}}return It(t)?{code:t.error.code,message:t.error.message}:null}function Rs(t){let e=cr(t);if(!e)return[];let n=[];for(let i of e.split(/\r?\n/)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(!s||s==="[DONE]"))try{n.push(JSON.parse(s))}catch{}}if(n.length>0)return n;let o=e.indexOf("{"),r=e.lastIndexOf("}");if(o!==-1&&r>o)try{n.push(JSON.parse(e.slice(o,r+1)))}catch{}return n}function cr(t){return t instanceof Error?t.message:typeof t=="string"?t:null}function bs(t,e={}){if(vs(t))return{kind:"abort",diagnosis:"fail-fast",reason:"aborted"};let n=lr(t),o=n.statusCode,r=Is(t),i=n.providerCode??r.providerCode,s=n.providerMessage??r.providerMessage,a=n.requestId??r.requestId,l={...o!==void 0?{statusCode:o}:{},...i!==void 0?{providerCode:i}:{},...s!==void 0?{providerMessage:s}:{},...a!==void 0?{requestId:a}:{}};if(xs(i))return{kind:"provider-business",diagnosis:"fail-fast",reason:"allocated-quota-exceeded",...l};if(xn(t))return{kind:"provider-business",diagnosis:"fail-fast",reason:"insufficient-quota",...l};if(wn(t,e.extraRetryErrorCodes))return{kind:n.transport==="sse"?"sse-provider":o!==void 0?"http":"provider",diagnosis:"retryable",reason:"rate-limit",...l};let u=ks(t);if(u!==void 0&&(o===void 0||o>=500))return{kind:"transport",diagnosis:"retryable",reason:"transport-error",transportCode:u,...o!==void 0?{statusCode:o}:{}};if(o!==void 0){let c=n.transport==="sse"?"sse-provider":"http";return o===529?{kind:c,diagnosis:"retryable",reason:"capacity-overload",...l}:o===401||o===403?{kind:c,diagnosis:"fail-fast",reason:"auth-error",...l}:o>=400&&o<500?{kind:c,diagnosis:"fail-fast",reason:"client-error",...l}:o>=500&&o<600?{kind:c,diagnosis:"retryable",reason:"server-error",...l}:{kind:c,diagnosis:"unknown",reason:"http-status",...l}}return i==="upstream_unavailable"||i==="upstream_timeout"||i==="incomplete_stream"?{kind:"sse-provider",diagnosis:"retryable",reason:"server-error",...l}:{kind:"unknown",diagnosis:"unknown",reason:"unclassified",...l}}function td(t){let e=t.statusCode??Number(t.providerCode);return t.kind!=="transport"&&t.diagnosis!=="fail-fast"&&(e>=500&&e<600||t.kind==="sse-provider"&&t.reason==="server-error"&&t.diagnosis==="retryable")}function dr(t,e){return wn(t,e)||bs(t,{extraRetryErrorCodes:e}).diagnosis==="retryable"}function vs(t){return Un(t)?!0:t instanceof Error&&t.name==="CanceledError"}var Ms=5;function ks(t){let e=t;for(let n=0;n<=Ms;n++){if(typeof e!="object"||e===null)return;let o=e.code;if(typeof o=="string"&&_s(o))return o;e=e instanceof Error?e.cause:void 0}}function _s(t){return ws.has(t)}var ws=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 xs(t){return t==="Throttling.AllocationQuota"}function Is(t){if(typeof t!="object"||t===null)return{};let e=t,n=typeof e.code=="string"||typeof e.code=="number"?String(e.code):void 0,o=typeof e.code=="number"&&e.code>=100&&e.code<600,r=t instanceof Error&&n?.startsWith("ERR_")||o?void 0:n,i=typeof e.request_id=="string"?e.request_id:typeof e.requestId=="string"?e.requestId:void 0,s=typeof e.message=="string"&&(!(t instanceof Error)||r!==void 0||i!==void 0)?e.message:void 0;return{...r!==void 0?{providerCode:r}:{},...s!==void 0?{providerMessage:s}:{},...i!==void 0?{requestId:i}:{}}}var $=(e=>(e.USE_OPENAI="openai",e))($||{}),Ot="MATILDA_API_KEY";function Os(t,e){if(t.apiKey||t.apiKeyEnvKey!==Ot)return;let n=t.baseUrl||oe();if(!_n({baseUrl:n,channel:e}))return;let o=Re({channel:e});o?.accessToken&&(t.apiKey=o.accessToken,process.env[Ot]=o.accessToken)}async function Ps(t,e){if(t.apiKeyEnvKey!==Ot)return;let n=t.baseUrl||oe();if(!_n({baseUrl:n,channel:e}))return;let o=Re({channel:e});if(!o?.accessToken)return;let r;try{r=await rr({baseUrl:n,fallbackAccessToken:o.accessToken,channel:e})}catch(i){if(!dr(i))throw i;r=o.accessToken}r&&(t.apiKey=r,process.env[Ot]=r)}function In(t,e,n){t[e]=n}function Ds(t,e){return t?.[e]}function dd(t,e,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:e,proxy:t?.getProxy()};In(i,"authType",{kind:"computed",detail:"provided by caller"}),t?.getProxy()&&In(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=c=>Ds(o,c)??{kind:"unknown"};for(let c of Rt)n&&c in n&&!i[c]&&In(i,c,l(c));Os(a,t.getChannel());let u=Cn(a,s);if(!u.valid)throw new Error(u.errors.map(c=>c.message).join(`
17
+ `));return{config:a,sources:i}}function Cn(t,e=!1){let n=[];if(!t.apiKey)if(e)n.push(new ft(t.authType,t.model,t.apiKeyEnvKey));else{let o=t.apiKeyEnvKey||ko(t.authType);n.push(new mt({authType:t.authType,model:t.model,baseUrl:t.baseUrl,envKey:o}))}if(!t.model)if(e)n.push(new gt(t.authType));else{let o=_o(t.authType);n.push(new ht({authType:t.authType,envKey:o}))}return{valid:n.length===0,errors:n}}function Ls(t){let e=t;for(;e instanceof Error;){if("code"in e&&e.code==="ERR_MODULE_NOT_FOUND")return e;e=e.cause}}async function pd(t,e,n){mn(t,e.getOrganizationId?.(),e.getCodeCreditLimitMinor?.()),Mo(t.customHeaders),await Ps(t,e.getChannel());let o=Cn(t,!1);if(!o.valid)throw new Error(o.errors.map(s=>s.message).join(`
18
+ `));let r=t.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai"){let{applyDeclaredInputModalities:s,createOpenAIContentGenerator:a}=await import("./openaiContentGenerator-BG3OM453.js");await s(t,e,n),i=a(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=Ls(s);throw a?new Error(`Matilda was updated in the background and needs to be restarted.
19
+ Please exit and restart Matilda to use the '${r}' provider.`,{cause:a}):s}return new Le(i,e,t)}var Us=["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"],Ns=new Set([...Us,...Ln]),Fs=new Set(["VSCode","ACP","SDK","CI"]),be="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",Gs="[A-Za-z][0-9A-Za-z-]{0,23}",pr="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",Ks=new RegExp(`^${be}(?:-${Gs}(?:\\.${pr})+)?$`),$s=63,Bs=new RegExp(`^${be}$`),js=new RegExp(`^${be}-preview\\.(?:0|[1-9]\\d{0,11})$`),Vs=new RegExp(`^${be}-canary\\.(?:0|[1-9]\\d{0,11})$`),zs=new RegExp(`^${be}-nightly\\.(?:0|[1-9]\\d{0,11})\\.[0-9A-Fa-f]{7,12}$`),Ws=new RegExp(`^${be}-(preview|canary|nightly|development|internal)(?:\\.${pr})+$`);function qs(t){return t==="desktop"?"desktop":t===void 0||Fs.has(t)?"code_cli":"unknown"}function Hs(t){if(t==="android")return"android";if(t==="darwin")return"macos";if(t==="win32")return"windows";if(t==="linux")return"linux"}function Js(t){if(t==="x64")return"x64";if(t==="arm64")return"arm64"}function Ys(t){if(t===void 0)return"npm";if(t==="desktop")return"direct-download";if(t==="VSCode")return"vscode-marketplace"}function Xs(t,e){if(e==="desktop")return"matilda-desktop";if(t==="VSCode")return"matilda-vscode";if(e==="code_cli")return"matilda-code"}function Qs(t){if(typeof t=="string"&&!(t.length>$s||!Ks.test(t)))return t}function Zs(t){if(t!==void 0)return Bs.test(t)?"stable":js.test(t)?"preview":Vs.test(t)?"canary":zs.test(t)?"nightly":Ws.exec(t)?.[1]}function fr(t,e=process.platform,n=process.arch){let o=t.getChannel?.(),r=qs(o),i=Qs(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:t.getCliVersion?.()),s=Zs(i),a=Hs(e),l=Js(n),u=Ys(o),c=Xs(o,r);return{...c?{"x-matilda-client-name":c}:{},...i?{"x-matilda-client-version":i}:{},...a?{"x-matilda-client-operating-system":a}:{},...l?{"x-matilda-client-architecture":l}:{},...u?{"x-matilda-client-distribution-channel":u}:{},...s?{"x-matilda-client-release-channel":s}:{}}}function yd(t){let e=t.toLowerCase();return Ns.has(e)||e.startsWith("x-matilda-reported-")}function ea(t){let e=t??oe();try{let n=new URL(e);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let o=n.hostname.toLowerCase();return o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="core-api.matilda"||Ze(e)}catch{return!1}}function Td(t,e=t.apiKey){return t.authType==="openai"&&!!e&&ea(t.baseUrl)}var ta=3e3,$e=1,na=24*60*60*1e3,gr=20,mr=999,oa=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"]),ra=new Set(["ENOTFOUND","EAI_AGAIN"]),ia=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),sa=new Set(["ABORT_ERR","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT"]),aa=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]);function la(t){return`${new URL(t).origin}/api/client-events`}function ua(t){let e={eventType:t.eventType,platform:"cli"};return t.eventType==="network_error"&&(e.transportReason=t.transportReason,e.transportStage=t.transportStage,e.responseReceived=t.responseReceived,e.occurrenceCount=t.occurrenceCount),t.eventType==="auth_funnel"&&(e.authStage=t.authStage,e.authOutcome=t.authOutcome,e.occurrenceCount=t.occurrenceCount),t.eventType==="network_error"&&(e.reportedSurface=t.reportedSurface,e.reportedOs=t.reportedOs,e.reportedArchitecture=t.reportedArchitecture,e.reportedProcess=t.reportedProcess,e.reportedReleaseChannel=t.reportedReleaseChannel,t.reportedVersion&&(e.reportedVersion=t.reportedVersion)),e}async function On(t,e){let{baseUrl:n,token:o}=e;if(!n||!o)return!1;let r=e.fetchImpl??fetch,i=new AbortController,s=setTimeout(()=>i.abort(),e.timeoutMs??ta);try{let a=await r(la(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(ua(t)),signal:i.signal});return a.ok?!0:(We.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`),!1)}catch{return!1}finally{clearTimeout(s)}}async function Mn(t,e){let n=typeof t.occurrenceCount=="number"&&Number.isFinite(t.occurrenceCount)?Math.max(1,Math.min(Math.floor(t.occurrenceCount),mr)):1;return On({eventType:"auth_funnel",authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:n},e)}function hr(){try{let t=X.readFileSync(Tr(),"utf8"),e=JSON.parse(t);return e.schemaVersion!==$e||!Array.isArray(e.failures)?void 0:{schemaVersion:$e,failures:e.failures.filter(ca)}}catch{return}}function ca(t){if(!t||typeof t!="object")return!1;let e=t;return e.eventType==="network_error"&&typeof e.transportReason=="string"&&typeof e.transportStage=="string"&&typeof e.responseReceived=="boolean"&&typeof e.occurrenceCount=="number"&&typeof e.reportedSurface=="string"&&typeof e.reportedOs=="string"&&typeof e.reportedArchitecture=="string"&&typeof e.reportedProcess=="string"&&typeof e.reportedReleaseChannel=="string"&&typeof e.firstObservedAtMs=="number"&&typeof e.lastObservedAtMs=="number"}function Cr(t){let e=Tr();if(t.failures.length===0){try{X.rmSync(e,{force:!0})}catch{}return}try{X.mkdirSync(Pt.dirname(e),{recursive:!0}),X.writeFileSync(e,`${JSON.stringify(t)}
20
+ `,"utf8")}catch{}}function yr(t,e){return t.filter(n=>e-n.lastObservedAtMs<=na).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-gr)}function da(t){let e=fr(t);return{reportedSurface:e["x-matilda-client-name"]==="matilda-desktop"?"desktop":e["x-matilda-client-name"]==="matilda-code"||e["x-matilda-client-name"]==="matilda-vscode"?"code_cli":"unknown",reportedOs:e["x-matilda-client-operating-system"]??"unknown",reportedArchitecture:e["x-matilda-client-architecture"]??"unknown",reportedProcess:e["x-matilda-client-name"]??"unknown",reportedVersion:e["x-matilda-client-version"],reportedReleaseChannel:e["x-matilda-client-release-channel"]??"unknown"}}function pa(t){if(!t||typeof t!="object")return;let e=t.code;if(typeof e=="string")return e;if(!(t instanceof Error)||!t.cause||typeof t.cause!="object")return;let n=t.cause.code;return typeof n=="string"?n:void 0}function fa(t){if(!(!t||typeof t!="object"))for(let e of["status","statusCode"]){let n=t[e];if(typeof n=="number")return n}}function ga(t,e){let n=pa(t);if(n&&oa.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&ra.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&ia.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&sa.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&aa.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=fa(t),r=t instanceof Error?t.message.toLowerCase():String(t).toLowerCase();if(r.includes("self signed")||r.includes("certificate")||r.includes("tls"))return{reason:"tls",stage:"tls",responseReceived:!1};if(o===407||n==="proxy_auth_required")return{reason:"proxy",stage:"connect",responseReceived:!0};if(e&&r.includes("proxy")&&(r.includes("407")||r.includes("connect")||r.includes("fetch failed")))return{reason:"proxy",stage:"connect",responseReceived:!1};if(r.includes("timed out")||r.includes("timeout")||r.includes("deadline exceeded"))return{reason:"timeout",stage:"request",responseReceived:!1};if(r.includes("fetch failed"))return{reason:"unknown",stage:"unknown",responseReceived:!1}}function ma(t,e){return t.findIndex(n=>n.transportReason===e.transportReason&&n.transportStage===e.transportStage&&n.responseReceived===e.responseReceived&&n.reportedSurface===e.reportedSurface&&n.reportedOs===e.reportedOs&&n.reportedArchitecture===e.reportedArchitecture&&n.reportedProcess===e.reportedProcess&&n.reportedVersion===e.reportedVersion&&n.reportedReleaseChannel===e.reportedReleaseChannel)}function vd(t,e){let n=da(e.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=ga(t,e.proxyConfigured);if(!o)return!1;let r=Date.now(),i={eventType:"network_error",transportReason:o.reason,transportStage:o.stage,responseReceived:o.responseReceived,occurrenceCount:1,...n,firstObservedAtMs:r,lastObservedAtMs:r},s=hr()??{schemaVersion:$e,failures:[]},a=yr(s.failures,r),l=ma(a,i);if(l>=0){let u=a[l];a[l]={...u,occurrenceCount:Math.min(u.occurrenceCount+1,mr),lastObservedAtMs:r}}else a.push(i);return Cr({schemaVersion:$e,failures:a.slice(-gr)}),!0}async function Md(t){let e=hr();if(!e)return;let n=yr(e.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await On({eventType:i.eventType,transportReason:i.transportReason,transportStage:i.transportStage,responseReceived:i.responseReceived,occurrenceCount:i.occurrenceCount,reportedSurface:i.reportedSurface,reportedOs:i.reportedOs,reportedArchitecture:i.reportedArchitecture,reportedProcess:i.reportedProcess,reportedVersion:i.reportedVersion,reportedReleaseChannel:i.reportedReleaseChannel},t)){o.push(...n.slice(r));break}}Cr({schemaVersion:$e,failures:o})}function Tr(){return Pt.join(ze.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var Df="local",Lf="http://localhost:4317";export{ts as a,Jo as b,Mr as c,nn as d,st as e,Pr as f,Dr as g,lt as h,ho as i,ii as j,pn as k,Qr as l,fr as m,yd as n,Td as o,Mn as p,vd as q,Md as r,Df as s,Lf as t,ou as u,mn as v,Mo as w,ru as x,uu as y,cu as z,yt as A,me as B,Lo as C,Mu as D,xu as E,Ko as F,Re as G,_n as H,Nc as I,Fc as J,rr as K,ms as L,Gc as M,Kc as N,It as O,ir as P,sr as Q,hs as R,wn as S,xn as T,As as U,lr as V,Yc as W,bs as X,td as Y,dr as Z,$ as _,dd as $,pd as aa};
21
+ /**
22
+ * @license
23
+ * Copyright 2025 Matilda
24
+ * SPDX-License-Identifier: Apache-2.0
25
+ */
26
+ /**
27
+ * @license
28
+ * Copyright 2025 Google LLC
29
+ * SPDX-License-Identifier: Apache-2.0
30
+ */
31
+ /**
32
+ * @license
33
+ * Copyright 2026 Matilda Team
34
+ * SPDX-License-Identifier: Apache-2.0
35
+ */
36
+ /**
37
+ * @license
38
+ * Copyright 2026 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
+ */
@@ -0,0 +1,3 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{b as f}from"./chunk-GZPNIYVZ.js";f();var q=new Error("timeout while waiting for mutex to become available"),k=new Error("mutex already locked"),v=new Error("request for lock canceled"),m=function(u,e,t,i){function o(n){return n instanceof t?n:new t(function(s){s(n)})}return new(t||(t=Promise))(function(n,s){function l(r){try{a(i.next(r))}catch(c){s(c)}}function h(r){try{a(i.throw(r))}catch(c){s(c)}}function a(r){r.done?n(r.value):o(r.value).then(l,h)}a((i=i.apply(u,e||[])).next())})},d=class{constructor(e,t=v){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((i,o)=>{let n={resolve:i,reject:o,weight:e,priority:t},s=w(this._queue,l=>t<=l.priority);s===-1&&e<=this._value?this._dispatchItem(n):this._queue.splice(s+1,0,n)})}runExclusive(e){return m(this,arguments,void 0,function*(t,i=1,o=0){let[n,s]=yield this.acquire(i,o);try{return yield t(n)}finally{s()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(i=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),p(this._weightedWaiters[e-1],{resolve:i,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(i=>i.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let i=this._weightedWaiters[t-1];if(!i)continue;let o=i.findIndex(n=>n.priority<=e);(o===-1?i:i.splice(0,o)).forEach(n=>n.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function p(u,e){let t=w(u,i=>e.priority<=i.priority);u.splice(t+1,0,e)}function w(u,e){for(let t=u.length-1;t>=0;t--)if(e(u[t]))return t;return-1}var E=function(u,e,t,i){function o(n){return n instanceof t?n:new t(function(s){s(n)})}return new(t||(t=Promise))(function(n,s){function l(r){try{a(i.next(r))}catch(c){s(c)}}function h(r){try{a(i.throw(r))}catch(c){s(c)}}function a(r){r.done?n(r.value):o(r.value).then(l,h)}a((i=i.apply(u,e||[])).next())})},_=class{constructor(e){this._semaphore=new d(1,e)}acquire(){return E(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};export{_ as a};
@@ -0,0 +1,3 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{b as i}from"./chunk-GZPNIYVZ.js";import{c as p,e as Vr}from"./chunk-OWGSC52X.js";function b(t){return Symbol.for(t)}var Br,V,O=p(()=>{i();Br=function(){function t(r){var e=this;e._currentContext=r?new Map(r):new Map,e.getValue=function(n){return e._currentContext.get(n)},e.setValue=function(n,a){var o=new t(e._currentContext);return o._currentContext.set(n,a),o},e.deleteValue=function(n){var a=new t(e._currentContext);return a._currentContext.delete(n),a}}return t}(),V=new Br});var Lr,Ur,Ct,St=p(()=>{i();O();Lr=function(t,r){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),a,o=[],u;try{for(;(r===void 0||r-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(c){u={error:c}}finally{try{a&&!a.done&&(e=n.return)&&e.call(n)}finally{if(u)throw u.error}}return o},Ur=function(t,r,e){if(e||arguments.length===2)for(var n=0,a=r.length,o;n<a;n++)(o||!(n in r))&&(o||(o=Array.prototype.slice.call(r,0,n)),o[n]=r[n]);return t.concat(o||Array.prototype.slice.call(r))},Ct=function(){function t(){}return t.prototype.active=function(){return V},t.prototype.with=function(r,e,n){for(var a=[],o=3;o<arguments.length;o++)a[o-3]=arguments[o];return e.call.apply(e,Ur([n],Lr(a),!1))},t.prototype.bind=function(r,e){return e},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}()});var Rt,Mt=p(()=>{i();Rt=globalThis});var wt=p(()=>{i();Mt()});var Dt=p(()=>{i();wt()});var d,Z=p(()=>{i();d="1.9.0"});function jr(t){var r=new Set([t]),e=new Set,n=t.match(Gt);if(!n)return function(){return!1};var a={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(a.prerelease!=null)return function(f){return f===t};function o(c){return e.add(c),!1}function u(c){return r.add(c),!0}return function(f){if(r.has(f))return!0;if(e.has(f))return!1;var g=f.match(Gt);if(!g)return o(f);var m={major:+g[1],minor:+g[2],patch:+g[3],prerelease:g[4]};return m.prerelease!=null||a.major!==m.major?o(f):a.major===0?a.minor===m.minor&&a.patch<=m.patch?u(f):o(f):a.minor<=m.minor?u(f):o(f)}}var Gt,Vt,Bt=p(()=>{i();Z();Gt=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;Vt=jr(d)});function _(t,r,e,n){var a;n===void 0&&(n=!1);var o=C[P]=(a=C[P])!==null&&a!==void 0?a:{version:d};if(!n&&o[t]){var u=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return e.error(u.stack||u.message),!1}if(o.version!==d){var u=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+t+" does not match previously registered API v"+d);return e.error(u.stack||u.message),!1}return o[t]=r,e.debug("@opentelemetry/api: Registered a global for "+t+" v"+d+"."),!0}function v(t){var r,e,n=(r=C[P])===null||r===void 0?void 0:r.version;if(!(!n||!Vt(n)))return(e=C[P])===null||e===void 0?void 0:e[t]}function y(t,r){r.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+d+".");var e=C[P];e&&delete e[t]}var kr,P,C,E=p(()=>{i();Dt();Z();Bt();kr=d.split(".")[0],P=Symbol.for("opentelemetry.js.api."+kr),C=Rt});function S(t,r,e){var n=v("diag");if(n)return e.unshift(r),n[t].apply(n,Kr([],Xr(e),!1))}var Xr,Kr,Lt,Ut=p(()=>{i();E();Xr=function(t,r){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),a,o=[],u;try{for(;(r===void 0||r-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(c){u={error:c}}finally{try{a&&!a.done&&(e=n.return)&&e.call(n)}finally{if(u)throw u.error}}return o},Kr=function(t,r,e){if(e||arguments.length===2)for(var n=0,a=r.length,o;n<a;n++)(o||!(n in r))&&(o||(o=Array.prototype.slice.call(r,0,n)),o[n]=r[n]);return t.concat(o||Array.prototype.slice.call(r))},Lt=function(){function t(r){this._namespace=r.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return S("debug",this._namespace,r)},t.prototype.error=function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return S("error",this._namespace,r)},t.prototype.info=function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return S("info",this._namespace,r)},t.prototype.warn=function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return S("warn",this._namespace,r)},t.prototype.verbose=function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return S("verbose",this._namespace,r)},t}()});var s,B=p(()=>{i();(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(s||(s={}))});function jt(t,r){t<s.NONE?t=s.NONE:t>s.ALL&&(t=s.ALL),r=r||{};function e(n,a){var o=r[n];return typeof o=="function"&&t>=a?o.bind(r):function(){}}return{error:e("error",s.ERROR),warn:e("warn",s.WARN),info:e("info",s.INFO),debug:e("debug",s.DEBUG),verbose:e("verbose",s.VERBOSE)}}var kt=p(()=>{i();B()});var Fr,Yr,zr,l,A=p(()=>{i();Ut();kt();B();E();Fr=function(t,r){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),a,o=[],u;try{for(;(r===void 0||r-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(c){u={error:c}}finally{try{a&&!a.done&&(e=n.return)&&e.call(n)}finally{if(u)throw u.error}}return o},Yr=function(t,r,e){if(e||arguments.length===2)for(var n=0,a=r.length,o;n<a;n++)(o||!(n in r))&&(o||(o=Array.prototype.slice.call(r,0,n)),o[n]=r[n]);return t.concat(o||Array.prototype.slice.call(r))},zr="diag",l=function(){function t(){function r(a){return function(){for(var o=[],u=0;u<arguments.length;u++)o[u]=arguments[u];var c=v("diag");if(c)return c[a].apply(c,Yr([],Fr(o),!1))}}var e=this,n=function(a,o){var u,c,f;if(o===void 0&&(o={logLevel:s.INFO}),a===e){var g=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return e.error((u=g.stack)!==null&&u!==void 0?u:g.message),!1}typeof o=="number"&&(o={logLevel:o});var m=v("diag"),Ot=jt((c=o.logLevel)!==null&&c!==void 0?c:s.INFO,a);if(m&&!o.suppressOverrideMessage){var Pt=(f=new Error().stack)!==null&&f!==void 0?f:"<failed to generate stacktrace>";m.warn("Current logger will be overwritten from "+Pt),Ot.warn("Current logger will overwrite one already registered from "+Pt)}return _("diag",Ot,e,!0)};e.setLogger=n,e.disable=function(){y(zr,e)},e.createComponentLogger=function(a){return new Lt(a)},e.verbose=r("verbose"),e.debug=r("debug"),e.info=r("info"),e.warn=r("warn"),e.error=r("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}()});var Wr,Hr,tt,$r,h,R=p(()=>{i();St();E();A();Wr=function(t,r){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),a,o=[],u;try{for(;(r===void 0||r-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(c){u={error:c}}finally{try{a&&!a.done&&(e=n.return)&&e.call(n)}finally{if(u)throw u.error}}return o},Hr=function(t,r,e){if(e||arguments.length===2)for(var n=0,a=r.length,o;n<a;n++)(o||!(n in r))&&(o||(o=Array.prototype.slice.call(r,0,n)),o[n]=r[n]);return t.concat(o||Array.prototype.slice.call(r))},tt="context",$r=new Ct,h=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(r){return _(tt,r,l.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(r,e,n){for(var a,o=[],u=3;u<arguments.length;u++)o[u-3]=arguments[u];return(a=this._getContextManager()).with.apply(a,Hr([r,e,n],Wr(o),!1))},t.prototype.bind=function(r,e){return this._getContextManager().bind(r,e)},t.prototype._getContextManager=function(){return v(tt)||$r},t.prototype.disable=function(){this._getContextManager().disable(),y(tt,l.instance())},t}()});var rt,Xt=p(()=>{i();R();rt=h.getInstance()});var T,et=p(()=>{i();(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(T||(T={}))});var M,w,L,U=p(()=>{i();et();M="0000000000000000",w="00000000000000000000000000000000",L={traceId:w,spanId:M,traceFlags:T.NONE}});var x,j=p(()=>{i();U();x=function(){function t(r){r===void 0&&(r=L),this._spanContext=r}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(r,e){return this},t.prototype.setAttributes=function(r){return this},t.prototype.addEvent=function(r,e){return this},t.prototype.addLink=function(r){return this},t.prototype.addLinks=function(r){return this},t.prototype.setStatus=function(r){return this},t.prototype.updateName=function(r){return this},t.prototype.end=function(r){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(r,e){},t}()});function k(t){return t.getValue(nt)||void 0}function Kt(){return k(h.getInstance().active())}function D(t,r){return t.setValue(nt,r)}function Ft(t){return t.deleteValue(nt)}function Yt(t,r){return D(t,new x(r))}function X(t){var r;return(r=k(t))===null||r===void 0?void 0:r.spanContext()}var nt,ot=p(()=>{i();O();j();R();nt=b("OpenTelemetry Context Key SPAN")});function at(t){return Qr.test(t)&&t!==w}function it(t){return qr.test(t)&&t!==M}function I(t){return at(t.traceId)&&it(t.spanId)}function zt(t){return new x(t)}var Qr,qr,K=p(()=>{i();U();j();Qr=/^([0-9a-f]{32})$/i,qr=/^[0-9a-f]{16}$/i});function Jr(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var ut,F,pt=p(()=>{i();R();ot();j();K();ut=h.getInstance(),F=function(){function t(){}return t.prototype.startSpan=function(r,e,n){n===void 0&&(n=ut.active());var a=!!e?.root;if(a)return new x;var o=n&&X(n);return Jr(o)&&I(o)?new x(o):new x},t.prototype.startActiveSpan=function(r,e,n,a){var o,u,c;if(!(arguments.length<2)){arguments.length===2?c=e:arguments.length===3?(o=e,c=n):(o=e,u=n,c=a);var f=u??ut.active(),g=this.startSpan(r,o,f),m=D(f,g);return ut.with(m,c,void 0,g)}},t}()});var Zr,Y,ct=p(()=>{i();pt();Zr=new F,Y=function(){function t(r,e,n,a){this._provider=r,this.name=e,this.version=n,this.options=a}return t.prototype.startSpan=function(r,e,n){return this._getTracer().startSpan(r,e,n)},t.prototype.startActiveSpan=function(r,e,n,a){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var r=this._provider.getDelegateTracer(this.name,this.version,this.options);return r?(this._delegate=r,this._delegate):Zr},t}()});var Wt,Ht=p(()=>{i();pt();Wt=function(){function t(){}return t.prototype.getTracer=function(r,e,n){return new F},t}()});var te,G,ft=p(()=>{i();ct();Ht();te=new Wt,G=function(){function t(){}return t.prototype.getTracer=function(r,e,n){var a;return(a=this.getDelegateTracer(r,e,n))!==null&&a!==void 0?a:new Y(this,r,e,n)},t.prototype.getDelegate=function(){var r;return(r=this._delegate)!==null&&r!==void 0?r:te},t.prototype.setDelegate=function(r){this._delegate=r},t.prototype.getDelegateTracer=function(r,e,n){var a;return(a=this._delegate)===null||a===void 0?void 0:a.getTracer(r,e,n)},t}()});var st,$t,Qt=p(()=>{i();E();ft();K();ot();A();st="trace",$t=function(){function t(){this._proxyTracerProvider=new G,this.wrapSpanContext=zt,this.isSpanContextValid=I,this.deleteSpan=Ft,this.getSpan=k,this.getActiveSpan=Kt,this.getSpanContext=X,this.setSpan=D,this.setSpanContext=Yt}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(r){var e=_(st,this._proxyTracerProvider,l.instance());return e&&this._proxyTracerProvider.setDelegate(r),e},t.prototype.getTracerProvider=function(){return v(st)||this._proxyTracerProvider},t.prototype.getTracer=function(r,e){return this.getTracerProvider().getTracer(r,e)},t.prototype.disable=function(){y(st,l.instance()),this._proxyTracerProvider=new G},t}()});var lt,qt=p(()=>{i();Qt();lt=$t.getInstance()});var re,ee,Jt,Zt=p(()=>{i();re=function(t,r){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),a,o=[],u;try{for(;(r===void 0||r-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(c){u={error:c}}finally{try{a&&!a.done&&(e=n.return)&&e.call(n)}finally{if(u)throw u.error}}return o},ee=function(t){var r=typeof Symbol=="function"&&Symbol.iterator,e=r&&t[r],n=0;if(e)return e.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},Jt=function(){function t(r){this._entries=r?new Map(r):new Map}return t.prototype.getEntry=function(r){var e=this._entries.get(r);if(e)return Object.assign({},e)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(r){var e=re(r,2),n=e[0],a=e[1];return[n,a]})},t.prototype.setEntry=function(r,e){var n=new t(this._entries);return n._entries.set(r,e),n},t.prototype.removeEntry=function(r){var e=new t(this._entries);return e._entries.delete(r),e},t.prototype.removeEntries=function(){for(var r,e,n=[],a=0;a<arguments.length;a++)n[a]=arguments[a];var o=new t(this._entries);try{for(var u=ee(n),c=u.next();!c.done;c=u.next()){var f=c.value;o._entries.delete(f)}}catch(g){r={error:g}}finally{try{c&&!c.done&&(e=u.return)&&e.call(u)}finally{if(r)throw r.error}}return o},t.prototype.clear=function(){return new t},t}()});var tr,rr=p(()=>{i();tr=Symbol("BaggageEntryMetadata")});function er(t){return t===void 0&&(t={}),new Jt(new Map(Object.entries(t)))}function nr(t){return typeof t!="string"&&(ne.error("Cannot create baggage metadata from unknown type: "+typeof t),t=""),{__TYPE__:tr,toString:function(){return t}}}var ne,gt=p(()=>{i();A();Zt();rr();ne=l.instance()});var vt,or,ar=p(()=>{i();vt=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],or=function(){function t(){function r(n){return function(){for(var a=[],o=0;o<arguments.length;o++)a[o]=arguments[o];if(console){var u=console[n];if(typeof u!="function"&&(u=console.log),typeof u=="function")return u.apply(console,a)}}}for(var e=0;e<vt.length;e++)this[vt[e].n]=r(vt[e].c)}return t}()});function ir(){return _t}var N,oe,z,ae,ie,ue,pe,mt,ce,fe,se,_t,le,ge,ve,me,_e,ye,de,yt=p(()=>{i();N=function(){var t=function(r,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,a){n.__proto__=a}||function(n,a){for(var o in a)Object.prototype.hasOwnProperty.call(a,o)&&(n[o]=a[o])},t(r,e)};return function(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(r,e);function n(){this.constructor=r}r.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}}(),oe=function(){function t(){}return t.prototype.createGauge=function(r,e){return ge},t.prototype.createHistogram=function(r,e){return ve},t.prototype.createCounter=function(r,e){return le},t.prototype.createUpDownCounter=function(r,e){return me},t.prototype.createObservableGauge=function(r,e){return ye},t.prototype.createObservableCounter=function(r,e){return _e},t.prototype.createObservableUpDownCounter=function(r,e){return de},t.prototype.addBatchObservableCallback=function(r,e){},t.prototype.removeBatchObservableCallback=function(r){},t}(),z=function(){function t(){}return t}(),ae=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.prototype.add=function(e,n){},r}(z),ie=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.prototype.add=function(e,n){},r}(z),ue=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.prototype.record=function(e,n){},r}(z),pe=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.prototype.record=function(e,n){},r}(z),mt=function(){function t(){}return t.prototype.addCallback=function(r){},t.prototype.removeCallback=function(r){},t}(),ce=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r}(mt),fe=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r}(mt),se=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r}(mt),_t=new oe,le=new ae,ge=new ue,ve=new pe,me=new ie,_e=new ce,ye=new fe,de=new se});var W,ur=p(()=>{i();(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(W||(W={}))});var H,$,dt=p(()=>{i();H={get:function(t,r){if(t!=null)return t[r]},keys:function(t){return t==null?[]:Object.keys(t)}},$={set:function(t,r,e){t!=null&&(t[r]=e)}}});var Q,pr=p(()=>{i();(function(t){t[t.NOT_RECORD=0]="NOT_RECORD",t[t.RECORD=1]="RECORD",t[t.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(Q||(Q={}))});var q,cr=p(()=>{i();(function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"})(q||(q={}))});var J,fr=p(()=>{i();(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(J||(J={}))});function sr(t){return Ee.test(t)}function lr(t){return Ae.test(t)&&!Ne.test(t)}var ht,he,xe,Ee,Ae,Ne,gr=p(()=>{i();ht="[_0-9a-z-*/]",he="[a-z]"+ht+"{0,255}",xe="[a-z0-9]"+ht+"{0,240}@[a-z]"+ht+"{0,13}",Ee=new RegExp("^(?:"+he+"|"+xe+")$"),Ae=/^[ -~]{0,255}[!-~]$/,Ne=/,|=/});var vr,be,mr,_r,yr,dr=p(()=>{i();gr();vr=32,be=512,mr=",",_r="=",yr=function(){function t(r){this._internalState=new Map,r&&this._parse(r)}return t.prototype.set=function(r,e){var n=this._clone();return n._internalState.has(r)&&n._internalState.delete(r),n._internalState.set(r,e),n},t.prototype.unset=function(r){var e=this._clone();return e._internalState.delete(r),e},t.prototype.get=function(r){return this._internalState.get(r)},t.prototype.serialize=function(){var r=this;return this._keys().reduce(function(e,n){return e.push(n+_r+r.get(n)),e},[]).join(mr)},t.prototype._parse=function(r){r.length>be||(this._internalState=r.split(mr).reverse().reduce(function(e,n){var a=n.trim(),o=a.indexOf(_r);if(o!==-1){var u=a.slice(0,o),c=a.slice(o+1,n.length);sr(u)&&lr(c)&&e.set(u,c)}return e},new Map),this._internalState.size>vr&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,vr))))},t.prototype._keys=function(){return Array.from(this._internalState.keys()).reverse()},t.prototype._clone=function(){var r=new t;return r._internalState=new Map(this._internalState),r},t}()});function hr(t){return new yr(t)}var xr=p(()=>{i();dr()});var xt,Er=p(()=>{i();A();xt=l.instance()});var Te,Ar,Nr=p(()=>{i();yt();Te=function(){function t(){}return t.prototype.getMeter=function(r,e,n){return _t},t}(),Ar=new Te});var Et,br,Tr=p(()=>{i();Nr();E();A();Et="metrics",br=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(r){return _(Et,r,l.instance())},t.prototype.getMeterProvider=function(){return v(Et)||Ar},t.prototype.getMeter=function(r,e,n){return this.getMeterProvider().getMeter(r,e,n)},t.prototype.disable=function(){y(Et,l.instance())},t}()});var At,Ir=p(()=>{i();Tr();At=br.getInstance()});var Or,Pr=p(()=>{i();Or=function(){function t(){}return t.prototype.inject=function(r,e){},t.prototype.extract=function(r,e){return r},t.prototype.fields=function(){return[]},t}()});function bt(t){return t.getValue(Nt)||void 0}function Cr(){return bt(h.getInstance().active())}function Sr(t,r){return t.setValue(Nt,r)}function Rr(t){return t.deleteValue(Nt)}var Nt,Mr=p(()=>{i();R();O();Nt=b("OpenTelemetry Baggage Key")});var Tt,Ie,wr,Dr=p(()=>{i();E();Pr();dt();Mr();gt();A();Tt="propagation",Ie=new Or,wr=function(){function t(){this.createBaggage=er,this.getBaggage=bt,this.getActiveBaggage=Cr,this.setBaggage=Sr,this.deleteBaggage=Rr}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(r){return _(Tt,r,l.instance())},t.prototype.inject=function(r,e,n){return n===void 0&&(n=$),this._getGlobalPropagator().inject(r,e,n)},t.prototype.extract=function(r,e,n){return n===void 0&&(n=H),this._getGlobalPropagator().extract(r,e,n)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){y(Tt,l.instance())},t.prototype._getGlobalPropagator=function(){return v(Tt)||Ie},t}()});var It,Gr=p(()=>{i();Dr();It=wr.getInstance()});var Pe={};Vr(Pe,{DiagConsoleLogger:()=>or,DiagLogLevel:()=>s,INVALID_SPANID:()=>M,INVALID_SPAN_CONTEXT:()=>L,INVALID_TRACEID:()=>w,ProxyTracer:()=>Y,ProxyTracerProvider:()=>G,ROOT_CONTEXT:()=>V,SamplingDecision:()=>Q,SpanKind:()=>q,SpanStatusCode:()=>J,TraceFlags:()=>T,ValueType:()=>W,baggageEntryMetadataFromString:()=>nr,context:()=>rt,createContextKey:()=>b,createNoopMeter:()=>ir,createTraceState:()=>hr,default:()=>Oe,defaultTextMapGetter:()=>H,defaultTextMapSetter:()=>$,diag:()=>xt,isSpanContextValid:()=>I,isValidSpanId:()=>it,isValidTraceId:()=>at,metrics:()=>At,propagation:()=>It,trace:()=>lt});var Oe,Ce=p(()=>{i();gt();O();ar();B();yt();ur();dt();ct();ft();pr();cr();fr();et();xr();K();U();Xt();Er();Ir();Gr();qt();Oe={context:rt,diag:xt,metrics:At,propagation:It,trace:lt}});export{s as a,V as b,W as c,T as d,I as e,q as f,J as g,rt as h,xt as i,At as j,lt as k,Pe as l,Ce as m};