@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
@@ -1,32 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{M as j,N as L,O as W,g as F,ia as B,na as _}from"./chunk-3IRGBRSP.js";import{b as m,e as w}from"./chunk-4J6DC24J.js";import{k as U,n as D}from"./chunk-SDTWBD62.js";import{q as b,s as x,t as O,u as I}from"./chunk-27Q5KW3A.js";import{b as $}from"./chunk-GZPNIYVZ.js";$();var K="2026-06-23",z="auto",Y="instant",Q=12e4,h=18e4,Z=5e4,R=16e3,E=class extends Error{constructor(t,s){super(t);this.status=s;this.name="MatildaAgentHttpError"}},S=class extends Error{code="EMATILDA_STREAM_INCOMPLETE";constructor(){super("Matilda agent stream ended without an authoritative done signal."),this.name="MatildaAgentStreamProtocolError"}},q=["Treat this as Matilda Code traffic.","Prefer the code specialist path for implementation, debugging, refactoring, tests, repo edits, and code review.","Use the fast instruct path for simple coordination, status, clarification, or non-code conversational replies.","Keep the response concise and action-oriented."].join(" "),ee=["You are powering Matilda Code, an interactive terminal coding agent.","Matilda Code owns the local agent loop: codebase reads, edits, shell commands, approvals, memory, subagents, skills, and MCP tools run through the CLI.","Use the conversation context and tool results as facts. Do not claim to have inspected files, run commands, or edited code unless that action appears in the provided context.",`When the user gives a vague starter such as "let's code" without a concrete development task, ask a concise clarifying question instead of inventing an app or dumping code.`].join(" ");function te(n){let e=(n||"https://matilda.maincode.com/api/v1").trim().replace(/\/+$/,"");return/\/api\/v1$/i.test(e)?e.replace(/\/api\/v1$/i,"/api"):/\/api$/i.test(e)?e:`${e}/api`}function y(n){try{let e=JSON.parse(n);return e&&typeof e=="object"?e:void 0}catch{return}}var ne="Your message was blocked by our content safety system.";function se(n){let e=y(n);if(!e||e.error!=="content_blocked")return;let t=Array.isArray(e.categories)?e.categories.filter(o=>typeof o=="string"):[],s=typeof e.assistant_message=="string"&&e.assistant_message.trim().length>0?e.assistant_message:typeof e.message=="string"?e.message:ne;return{categories:t,severity:typeof e.severity=="string"?e.severity:void 0,assistantMessage:s}}function u(n,e){let s=y(n)?.[e];return typeof s=="string"?s:void 0}function H(n){return P(n)}function P(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e;return typeof t.text=="string"?t.text:t.image_url?"[image omitted: Matilda native chat accepts text only]":t.input_audio?"[audio omitted: Matilda native chat accepts text only]":t.file?"[file omitted: Matilda native chat accepts text only]":""}).filter(Boolean).join(`
4
- `):""}function f(n,e){if(n.length<=e)return n;let t=`
5
- [...omitted to fit Matilda native agent context...]
6
- `,s=e-t.length,o=Math.floor(s*.6),i=s-o;return`${n.slice(0,o)}${t}${n.slice(-i)}`}function oe(n){return(n.candidates?.[0]?.content?.parts??[]).map(t=>typeof t=="string"?t:"thought"in t&&t.thought?"":"text"in t&&t.text||"").join("")}function ae(n){let e=y(n),t=typeof e?.output_tokens=="number"?e.output_tokens:void 0;if(t!==void 0)return{promptTokenCount:0,candidatesTokenCount:t,totalTokenCount:t,usageIsIncomplete:!0}}function C(n){return JSON.stringify(n).length}function ie(n){if(C(n)<=h)return n;let e=`
7
- [...omitted to fit Matilda native request limit...]
8
- `;for(let t=0;t<n.messages.length;t+=1){let s=n.messages[t];!s||s.content.length<=R||(n.messages[t]={...s,content:f(s.content,R)})}if(C(n)<=h)return n;for(;n.messages.length>2&&C(n)>h;){n.messages.splice(1,1);let t=n.messages[0];t&&!t.content.includes(e.trim())&&(n.messages[0]={...t,content:`${t.content}${e}`})}for(;C(n)>h;){let t=n.messages.length>1?n.messages.length-1:0,s=n.messages[t];if(!s||s.content.length<=1e3)break;let o=C(n)-h,i=Math.max(1e3,s.content.length-o-e.length-2e3);n.messages[t]={...s,content:f(s.content,i)}}return C(n)<=h||n.clientTools&&delete n.clientTools,n}function re(n){let e=y(n.data);if(!e)return;let t=typeof e.name=="string"?e.name:void 0;if(!t)return;let s=e.args&&typeof e.args=="object"?e.args:{};return{id:typeof e.id=="string"?e.id:void 0,name:t,args:s}}function le(n){let e=y(n.data);if(n.event==="thinking"){let t=u(n.data,"content");return t?`**Thinking** ${t}`:void 0}if(n.event==="generation_status"){let t=u(n.data,"phase");return t?`**Planning** ${t}`:void 0}if(n.event==="status"){let t=u(n.data,"state");if(!t)return;let s=typeof e?.position=="number"?` position ${e.position}`:"";return`**Status** ${t}${s}`}if(n.event==="tool_start"){let t=u(n.data,"tool");if(!t)return;let s=u(n.data,"input")??(e?.args?JSON.stringify(e.args):void 0);return`**Remote tool** Starting ${t}${s?` with ${s}`:""}`}if(n.event==="tool_progress"){let t=u(n.data,"tool"),s=u(n.data,"message");return t&&s?`**Remote tool** ${t}: ${s}`:void 0}if(n.event==="tool_result"){let t=u(n.data,"tool"),s=u(n.data,"status"),o=u(n.data,"output")??u(n.data,"result");return t?`**Remote tool** ${t} ${s??"completed"}${o?`: ${f(o,600)}`:""}`:void 0}}function T(n,e,t){let s=new w;return s.candidates=[{content:{parts:n?[{text:n}]:[],role:"model"},index:0,safetyRatings:[]}],s.createTime=Date.now().toString(),s.modelVersion=e,t&&(s.usageMetadata=t),s}function ce(n,e){let t=new w;return t.candidates=[{content:{parts:n?[{text:n,thought:!0}]:[],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,t}function de(n,e){let t=new w;return t.candidates=[{content:{parts:[{functionCall:n}],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,Object.defineProperty(t,"functionCalls",{value:[n],writable:!0,configurable:!0,enumerable:!0}),t}function J(n){let e=T("",n);return e.matildaReplace=!0,e}function ue(n){return n.matildaReplace===!0}function V(n,e,t){let s=T("",n,t);return s.candidates=[{content:{parts:[],role:"model"},finishReason:e,index:0,safetyRatings:[]}],s}async function*ge(n,e){let t=n.body?.getReader();if(!t)throw new Error("Matilda agent stream returned no response body");let s=new TextDecoder,o="",i="message",r=[],d=!1,c,a=()=>{e<=0||(c&&clearTimeout(c),c=setTimeout(()=>{d=!0,t.cancel().catch(()=>{})},e))},l=()=>{c&&(clearTimeout(c),c=void 0)},g=()=>{if(r.length===0){i="message";return}let A={event:i,data:r.join(`
9
- `)};return i="message",r=[],a(),A};a();try{for(;;){let{done:v,value:p}=await t.read();if(v||d)break;a(),o+=s.decode(p,{stream:!0});let N=o.split(`
10
- `);o=N.pop()??"";for(let k of N){let M=k.endsWith("\r")?k.slice(0,-1):k;if(M.length===0){let G=g();G&&(yield G)}else M.startsWith("event:")?i=M.slice(6).trim():M.startsWith("data:")&&r.push(M.slice(5).trimStart())}}if(o+=s.decode(),o.length>0)for(let v of o.split(`
11
- `)){let p=v.endsWith("\r")?v.slice(0,-1):v;p.startsWith("event:")?i=p.slice(6).trim():p.startsWith("data:")&&r.push(p.slice(5).trimStart())}let A=g();A&&(yield A)}finally{l()}if(d)throw Object.assign(new Error(`No Matilda agent SSE events for ${e}ms`),{code:"ETIMEDOUT"})}var X=class{constructor(e,t){this.contentGeneratorConfig=e;this.cliConfig=t}async generateContent(e,t){let s=await this.generateContentStream(e,t),o="",i,r=m.STOP,d=!1;for await(let a of s){ue(a)?o="":o+=oe(a),a.usageMetadata&&(i=a.usageMetadata);let l=a.candidates?.[0]?.finishReason;l&&(d=!0,r=l)}if(!d)throw new S;let c=T(o,this.modelFor(e),i);return c.candidates=[{content:{parts:o?[{text:o}]:[],role:"model"},index:0,safetyRatings:[]}],r&&(c.candidates[0].finishReason=r),c}async generateContentStream(e,t){return this.streamNativeChat(e)}async countTokens(e){return{totalTokens:Math.ceil(JSON.stringify(e.contents??"").length/4)}}async embedContent(e){throw new Error("Matilda agent SDK transport does not support embeddings.")}useSummarizedThinking(){return!1}async*streamNativeChat(e){let t=this.modelFor(e),s=await this.fetchNativeChat(e),o=!1,i=!1,r,d,c=!1;for await(let a of ge(s,Q))if(a.data!=="[DONE]"){if(a.event==="token"){let l=u(a.data,"content");l&&(i=!0,yield T(l,t))}else if(a.event==="thinking"||a.event==="generation_status"||a.event==="status"||a.event==="tool_start"||a.event==="tool_progress"||a.event==="tool_result"){let l=le(a);l&&(i=!0,yield ce(l,t))}else if(a.event==="client_tool_call"){let l=re(a);l&&(i=!0,yield de(l,t))}else if(a.event==="usage")d=ae(a.data)??d;else if(a.event==="replace")yield J(t);else if(a.event==="safety_replace"){yield J(t);let l=u(a.data,"message")??u(a.data,"content");l&&(i=!0,yield T(l,t))}else if(a.event==="truncated")c=!0,r=m.MAX_TOKENS;else if(a.event==="done"){if(c=!0,r=u(a.data,"reason")==="max_tokens"?m.MAX_TOKENS:r??m.STOP,!i)throw new Error("Matilda agent returned an empty response.");yield V(t,r,d),o=!0}else if(a.event==="error"){let l=y(a.data),g=typeof l?.error=="string"?l.error:"Unknown Matilda agent stream error";throw new Error(`Matilda agent stream error: ${g}`)}}if(!o){if(e.config?.abortSignal?.aborted)return;if(!i)throw new Error("Matilda agent returned an empty response.");if(c)yield V(t,r??m.STOP,d);else throw new S}}async fetchNativeChat(e){let t=await _({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()}),s=await this.postNativeChat(e,t);if(s.status!==401)return this.assertOkResponse(s);let o;try{o=await _({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:t,forceRefresh:!0,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()})}catch(r){throw B(r)?new b(r instanceof Error?r.message:String(r)):r}if(!o||o===t)throw new b("Matilda session expired. Please sign in again.");let i=await U("retry",()=>this.postNativeChat(e,o));return this.assertOkResponse(i)}async postNativeChat(e,t){return fetch(`${te(this.contentGeneratorConfig.baseUrl)}/chat`,{method:"POST",headers:this.buildHeaders(t),body:JSON.stringify(this.buildNativeRequest(e)),signal:e.config?.abortSignal})}async assertOkResponse(e){if(e.ok)return e;let t=await e.text();if(e.status===403){let o;try{o=JSON.parse(t)}catch{}if(O(o))throw new x}if(e.status===422){let o=se(t);if(o)throw new I(`Matilda agent request blocked (422): ${t}`,o.categories,o.severity,o.assistantMessage)}let s=`Matilda agent request failed (${e.status}): ${t}`;throw e.status===401?new b(s):new E(s,e.status)}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"text/event-stream","X-Matilda-API-Version":K,"X-Matilda-Client":"matilda-code","User-Agent":`MatildaCode/${this.cliConfig.getCliVersion?.()||"unknown"}`};for(let[s,o]of Object.entries(this.contentGeneratorConfig.customHeaders??{}))s.toLowerCase()!=="x-matilda-response-mode"&&!L(s)&&(t[s]=o);return W(this.contentGeneratorConfig,e)&&Object.assign(t,j(this.cliConfig),D()),e&&(t.Authorization=`Bearer ${e}`),t}buildNativeRequest(e){let t=this.inferPurpose(e),s=this.clientToolsFromRequest(e),o={messages:this.buildNativeMessages(e,t),responseMode:this.responseModeForPurpose(t)};return s.length>0&&(o.clientTools=s),ie(o)}buildNativeMessages(e,t){let s=this.openAIMessagesFromRequest(e),i=[{role:"user",content:this.buildSystemContext(e,t)}];for(let d of s){if(d.role==="system")continue;let c=this.nativeMessageFromOpenAIMessage(d);c&&i.push(c)}i.length===1&&i.push({role:"user",content:`${this.purposeLabel(t)}:
12
- (empty prompt)`});let r=i[i.length-1];return r?.role!=="user"?i.push({role:"user",content:`${this.purposeLabel(t)}:
13
- Continue from the previous assistant response.`}):r.content.startsWith(`${this.purposeLabel(t)}:
14
- `)||(i[i.length-1]={...r,content:`${this.purposeLabel(t)}:
15
- ${r.content}`}),i}buildSystemContext(e,t){let s=["Agent: Matilda Code",t==="code"?`Routing intent:
16
- ${q}`:void 0,`Instructions:
17
- ${this.instructionsFromRequest(e)}`].filter(o=>!!o);return f(s.join(`
18
-
19
- `),Z)}nativeMessageFromOpenAIMessage(e){let t=this.describeMessage(e);if(t.trim())return{role:e.role==="assistant"?"assistant":"user",content:t}}inferPurpose(e){if(this.contentGeneratorConfig.matildaAgentPurpose)return this.contentGeneratorConfig.matildaAgentPurpose;if(this.contentGeneratorConfig.matildaAgentResponseMode==="instant")return"general";if(this.contentGeneratorConfig.matildaAgentResponseMode==="deep")return"analysis";let s=(this.userMessagesFromRequest(e).at(-1)?.trim()??"").toLowerCase().replace(/\s+/g," ");return/^(hi|hey|hello|thanks|thank you|ok|okay|cool|nice|what'?s up)[.!?]*$/.test(s)||/^(ok|okay)?\s*(let'?s|lets)\s+(code|build|start|get started)[.!?]*$/.test(s)?"general":"code"}responseModeForPurpose(e){return this.contentGeneratorConfig.matildaAgentResponseMode?this.contentGeneratorConfig.matildaAgentResponseMode:e==="general"?Y:e==="analysis"?"deep":z}purposeLabel(e){return e==="code"?"Code task":e==="analysis"?"Analysis task":"Task"}instructionsFromRequest(e){let t=this.openAIMessagesFromRequest(e).filter(s=>s.role==="system").map(s=>P(s.content)).filter(s=>s.trim().length>0);return[ee,...t,this.localAgentContext()].join(`
20
-
21
- `)}localAgentContext(){let e=["Local agent context:","- CLI: Matilda Code terminal agent."],t=this.cliConfig.getModel?.();t&&e.push(`- Active model: ${t}`);let s=this.cliConfig.getApprovalMode?.();s&&e.push(`- Approval mode: ${s}`);let o=this.cliConfig.getSandbox?.();e.push(o?`- Sandbox: ${o.command} (${o.image}).`:"- Sandbox: disabled.");let i=[["allow",this.cliConfig.getPermissionsAllow?.()??[]],["ask",this.cliConfig.getPermissionsAsk?.()??[]],["deny",this.cliConfig.getPermissionsDeny?.()??[]]];for(let[l,g]of i)g.length>0&&e.push(`- Permission ${l} rules: ${g.join(", ")}`);let r=this.cliConfig.getIdeMode?.()?"IDE/ACP":this.cliConfig.isInteractive?.()?"interactive TUI":"headless";e.push(`- Interface mode: ${r}`);let d=this.cliConfig.getProjectRoot?.();d&&e.push(`- Project root: ${d}`);let c=this.cliConfig.getWorkingDir?.();c&&c!==d&&e.push(`- Working directory: ${c}`);let a=this.cliConfig.getToolRegistry?.()?.getAllToolNames?.().slice(0,30)??[];return a.length>0&&e.push(`- Local tools available through the CLI loop: ${a.join(", ")}`),e.join(`
22
- `)}clientToolsFromRequest(e){let t=[];for(let s of e.config?.tools??[])"functionDeclarations"in s&&t.push(...(s.functionDeclarations??[]).filter(o=>!!o.name));return t.map(s=>({name:s.name,...s.description?{description:s.description}:{},...s.parametersJsonSchema?{parameters:s.parametersJsonSchema}:s.parameters?{parameters:s.parameters}:{}}))}userMessagesFromRequest(e){return this.openAIMessagesFromRequest(e).filter(t=>t.role==="user").map(t=>H(t.content)).filter(t=>t.trim().length>0)}openAIMessagesFromRequest(e){let t={model:this.modelFor(e),modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0};return F.convertGeminiRequestToOpenAI(e,t,{cleanOrphanToolCalls:!1})}describeMessage(e){if(e.role==="user")return`User:
23
- ${f(H(e.content),R)}`;if(e.role==="assistant"){let t=P(e.content),s="tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.map(o=>`Tool request: ${o.function.name}(${o.function.arguments})`).join(`
24
- `):"";return`Assistant:
25
- ${f([t,s].filter(Boolean).join(`
26
- `),R)}`}return e.role==="tool"?`Tool result ${e.tool_call_id}:
27
- ${f(P(e.content),R)}`:""}modelFor(e){return e.model||this.contentGeneratorConfig.model}};export{ue as a,X as b};
28
- /**
29
- * @license
30
- * Copyright 2026 Matilda Team
31
- * SPDX-License-Identifier: Apache-2.0
32
- */
@@ -1,15 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{l as Se,m as Ae,n as Ge,o as qe,p as Ue,q as ne}from"./chunk-QKYGQLWC.js";import{c as je}from"./chunk-LUNDTQ3G.js";import{Q as ve,b as ke}from"./chunk-27Q5KW3A.js";import{b as d}from"./chunk-GZPNIYVZ.js";import{a as U,d as k}from"./chunk-OWGSC52X.js";var ze=k((xr,Ke)=>{d();var $=U("constants"),Ot=process.cwd,oe=null,Ft=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return oe||(oe=Ot.call(process)),oe};try{process.cwd()}catch{}typeof process.chdir=="function"&&(_e=process.chdir,process.chdir=function(e){oe=null,_e.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,_e));var _e;Ke.exports=It;function It(e){$.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||r(e),e.chown=u(e.chown),e.fchown=u(e.fchown),e.lchown=u(e.lchown),e.chmod=n(e.chmod),e.fchmod=n(e.fchmod),e.lchmod=n(e.lchmod),e.chownSync=l(e.chownSync),e.fchownSync=l(e.fchownSync),e.lchownSync=l(e.lchownSync),e.chmodSync=o(e.chmodSync),e.fchmodSync=o(e.fchmodSync),e.lchmodSync=o(e.lchmodSync),e.stat=p(e.stat),e.fstat=p(e.fstat),e.lstat=p(e.lstat),e.statSync=T(e.statSync),e.fstatSync=T(e.fstatSync),e.lstatSync=T(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(i,m,c){c&&process.nextTick(c)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(i,m,c,a){a&&process.nextTick(a)},e.lchownSync=function(){}),Ft==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:function(i){function m(c,a,s){var w=Date.now(),v=0;i(c,a,function E(C){if(C&&(C.code==="EACCES"||C.code==="EPERM"||C.code==="EBUSY")&&Date.now()-w<6e4){setTimeout(function(){e.stat(a,function(R,Z){R&&R.code==="ENOENT"?i(c,a,E):s(C)})},v),v<100&&(v+=10);return}s&&s(C)})}return Object.setPrototypeOf&&Object.setPrototypeOf(m,i),m}(e.rename)),e.read=typeof e.read!="function"?e.read:function(i){function m(c,a,s,w,v,E){var C;if(E&&typeof E=="function"){var R=0;C=function(Z,Re,Ce){if(Z&&Z.code==="EAGAIN"&&R<10)return R++,i.call(e,c,a,s,w,v,C);E.apply(this,arguments)}}return i.call(e,c,a,s,w,v,C)}return Object.setPrototypeOf&&Object.setPrototypeOf(m,i),m}(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:function(i){return function(m,c,a,s,w){for(var v=0;;)try{return i.call(e,m,c,a,s,w)}catch(E){if(E.code==="EAGAIN"&&v<10){v++;continue}throw E}}}(e.readSync);function t(i){i.lchmod=function(m,c,a){i.open(m,$.O_WRONLY|$.O_SYMLINK,c,function(s,w){if(s){a&&a(s);return}i.fchmod(w,c,function(v){i.close(w,function(E){a&&a(v||E)})})})},i.lchmodSync=function(m,c){var a=i.openSync(m,$.O_WRONLY|$.O_SYMLINK,c),s=!0,w;try{w=i.fchmodSync(a,c),s=!1}finally{if(s)try{i.closeSync(a)}catch{}else i.closeSync(a)}return w}}function r(i){$.hasOwnProperty("O_SYMLINK")&&i.futimes?(i.lutimes=function(m,c,a,s){i.open(m,$.O_SYMLINK,function(w,v){if(w){s&&s(w);return}i.futimes(v,c,a,function(E){i.close(v,function(C){s&&s(E||C)})})})},i.lutimesSync=function(m,c,a){var s=i.openSync(m,$.O_SYMLINK),w,v=!0;try{w=i.futimesSync(s,c,a),v=!1}finally{if(v)try{i.closeSync(s)}catch{}else i.closeSync(s)}return w}):i.futimes&&(i.lutimes=function(m,c,a,s){s&&process.nextTick(s)},i.lutimesSync=function(){})}function n(i){return i&&function(m,c,a){return i.call(e,m,c,function(s){I(s)&&(s=null),a&&a.apply(this,arguments)})}}function o(i){return i&&function(m,c){try{return i.call(e,m,c)}catch(a){if(!I(a))throw a}}}function u(i){return i&&function(m,c,a,s){return i.call(e,m,c,a,function(w){I(w)&&(w=null),s&&s.apply(this,arguments)})}}function l(i){return i&&function(m,c,a){try{return i.call(e,m,c,a)}catch(s){if(!I(s))throw s}}}function p(i){return i&&function(m,c,a){typeof c=="function"&&(a=c,c=null);function s(w,v){v&&(v.uid<0&&(v.uid+=4294967296),v.gid<0&&(v.gid+=4294967296)),a&&a.apply(this,arguments)}return c?i.call(e,m,c,s):i.call(e,m,s)}}function T(i){return i&&function(m,c){var a=c?i.call(e,m,c):i.call(e,m);return a&&(a.uid<0&&(a.uid+=4294967296),a.gid<0&&(a.gid+=4294967296)),a}}function I(i){if(!i||i.code==="ENOSYS")return!0;var m=!process.getuid||process.getuid()!==0;return!!(m&&(i.code==="EINVAL"||i.code==="EPERM"))}}});var Qe=k((Fr,Je)=>{d();var Be=U("stream").Stream;Je.exports=bt;function bt(e){return{ReadStream:t,WriteStream:r};function t(n,o){if(!(this instanceof t))return new t(n,o);Be.call(this);var u=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,o=o||{};for(var l=Object.keys(o),p=0,T=l.length;p<T;p++){var I=l[p];this[I]=o[I]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){u._read()});return}e.open(this.path,this.flags,this.mode,function(i,m){if(i){u.emit("error",i),u.readable=!1;return}u.fd=m,u.emit("open",m),u._read()})}function r(n,o){if(!(this instanceof r))return new r(n,o);Be.call(this),this.path=n,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,o=o||{};for(var u=Object.keys(o),l=0,p=u.length;l<p;l++){var T=u[l];this[T]=o[T]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var He=k((br,Xe)=>{"use strict";d();Xe.exports=Dt;var Mt=Object.getPrototypeOf||function(e){return e.__proto__};function Dt(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:Mt(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(e,r))}),t}});var Oe=k((Dr,xe)=>{d();var O=U("fs"),Pt=ze(),Nt=Qe(),Lt=He(),ue=U("util"),L,ce;typeof Symbol=="function"&&typeof Symbol.for=="function"?(L=Symbol.for("graceful-fs.queue"),ce=Symbol.for("graceful-fs.previous")):(L="___graceful-fs.queue",ce="___graceful-fs.previous");function Rt(){}function et(e,t){Object.defineProperty(e,L,{get:function(){return t}})}var Y=Rt;ue.debuglog?Y=ue.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(Y=function(){var e=ue.format.apply(ue,arguments);e="GFS4: "+e.split(/\n/).join(`
4
- GFS4: `),console.error(e)});O[L]||(Ve=globalThis[L]||[],et(O,Ve),O.close=function(e){function t(r,n){return e.call(O,r,function(o){o||Ze(),typeof n=="function"&&n.apply(this,arguments)})}return Object.defineProperty(t,ce,{value:e}),t}(O.close),O.closeSync=function(e){function t(r){e.apply(O,arguments),Ze()}return Object.defineProperty(t,ce,{value:e}),t}(O.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){Y(O[L]),U("assert").equal(O[L].length,0)}));var Ve;globalThis[L]||et(globalThis,O[L]);xe.exports=Te(Lt(O));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!O.__patched&&(xe.exports=Te(O),O.__patched=!0);function Te(e){Pt(e),e.gracefulify=Te,e.createReadStream=Re,e.createWriteStream=Ce;var t=e.readFile;e.readFile=r;function r(f,y,h){return typeof y=="function"&&(h=y,y=null),D(f,y,h);function D(P,b,x,F){return t(P,b,function(S){S&&(S.code==="EMFILE"||S.code==="ENFILE")?J([D,[P,b,x],S,F||Date.now(),Date.now()]):typeof x=="function"&&x.apply(this,arguments)})}}var n=e.writeFile;e.writeFile=o;function o(f,y,h,D){return typeof h=="function"&&(D=h,h=null),P(f,y,h,D);function P(b,x,F,S,N){return n(b,x,F,function(g){g&&(g.code==="EMFILE"||g.code==="ENFILE")?J([P,[b,x,F,S],g,N||Date.now(),Date.now()]):typeof S=="function"&&S.apply(this,arguments)})}}var u=e.appendFile;u&&(e.appendFile=l);function l(f,y,h,D){return typeof h=="function"&&(D=h,h=null),P(f,y,h,D);function P(b,x,F,S,N){return u(b,x,F,function(g){g&&(g.code==="EMFILE"||g.code==="ENFILE")?J([P,[b,x,F,S],g,N||Date.now(),Date.now()]):typeof S=="function"&&S.apply(this,arguments)})}}var p=e.copyFile;p&&(e.copyFile=T);function T(f,y,h,D){return typeof h=="function"&&(D=h,h=0),P(f,y,h,D);function P(b,x,F,S,N){return p(b,x,F,function(g){g&&(g.code==="EMFILE"||g.code==="ENFILE")?J([P,[b,x,F,S],g,N||Date.now(),Date.now()]):typeof S=="function"&&S.apply(this,arguments)})}}var I=e.readdir;e.readdir=m;var i=/^v[0-5]\./;function m(f,y,h){typeof y=="function"&&(h=y,y=null);var D=i.test(process.version)?function(x,F,S,N){return I(x,P(x,F,S,N))}:function(x,F,S,N){return I(x,F,P(x,F,S,N))};return D(f,y,h);function P(b,x,F,S){return function(N,g){N&&(N.code==="EMFILE"||N.code==="ENFILE")?J([D,[b,x,F],N,S||Date.now(),Date.now()]):(g&&g.sort&&g.sort(),typeof F=="function"&&F.call(this,N,g))}}}if(process.version.substr(0,4)==="v0.8"){var c=Nt(e);E=c.ReadStream,R=c.WriteStream}var a=e.ReadStream;a&&(E.prototype=Object.create(a.prototype),E.prototype.open=C);var s=e.WriteStream;s&&(R.prototype=Object.create(s.prototype),R.prototype.open=Z),Object.defineProperty(e,"ReadStream",{get:function(){return E},set:function(f){E=f},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return R},set:function(f){R=f},enumerable:!0,configurable:!0});var w=E;Object.defineProperty(e,"FileReadStream",{get:function(){return w},set:function(f){w=f},enumerable:!0,configurable:!0});var v=R;Object.defineProperty(e,"FileWriteStream",{get:function(){return v},set:function(f){v=f},enumerable:!0,configurable:!0});function E(f,y){return this instanceof E?(a.apply(this,arguments),this):E.apply(Object.create(E.prototype),arguments)}function C(){var f=this;ye(f.path,f.flags,f.mode,function(y,h){y?(f.autoClose&&f.destroy(),f.emit("error",y)):(f.fd=h,f.emit("open",h),f.read())})}function R(f,y){return this instanceof R?(s.apply(this,arguments),this):R.apply(Object.create(R.prototype),arguments)}function Z(){var f=this;ye(f.path,f.flags,f.mode,function(y,h){y?(f.destroy(),f.emit("error",y)):(f.fd=h,f.emit("open",h))})}function Re(f,y){return new e.ReadStream(f,y)}function Ce(f,y){return new e.WriteStream(f,y)}var Tt=e.open;e.open=ye;function ye(f,y,h,D){return typeof h=="function"&&(D=h,h=null),P(f,y,h,D);function P(b,x,F,S,N){return Tt(b,x,F,function(g,tr){g&&(g.code==="EMFILE"||g.code==="ENFILE")?J([P,[b,x,F,S],g,N||Date.now(),Date.now()]):typeof S=="function"&&S.apply(this,arguments)})}}return e}function J(e){Y("ENQUEUE",e[0].name,e[1]),O[L].push(e),Ee()}var ae;function Ze(){for(var e=Date.now(),t=0;t<O[L].length;++t)O[L][t].length>2&&(O[L][t][3]=e,O[L][t][4]=e);Ee()}function Ee(){if(clearTimeout(ae),ae=void 0,O[L].length!==0){var e=O[L].shift(),t=e[0],r=e[1],n=e[2],o=e[3],u=e[4];if(o===void 0)Y("RETRY",t.name,r),t.apply(null,r);else if(Date.now()-o>=6e4){Y("TIMEOUT",t.name,r);var l=r.pop();typeof l=="function"&&l.call(null,n)}else{var p=Date.now()-u,T=Math.max(u-o,1),I=Math.min(T*1.2,100);p>=I?(Y("RETRY",t.name,r),t.apply(null,r.concat([o]))):O[L].push(e)}ae===void 0&&(ae=setTimeout(Ee,0))}}});var rt=k((Nr,tt)=>{d();function A(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}tt.exports=A;A.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};A.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};A.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),r=this._timeouts.shift();else return!1;var n=this,o=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r);return this._options.unref&&o.unref(),!0};A.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};A.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};A.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};A.prototype.start=A.prototype.try;A.prototype.errors=function(){return this._errors};A.prototype.attempts=function(){return this._attempts};A.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var o=this._errors[n],u=o.message,l=(e[u]||0)+1;e[u]=l,l>=r&&(t=o,r=l)}return t}});var nt=k(K=>{d();var Ct=rt();K.operation=function(e){var t=K.timeouts(e);return new Ct(t,{forever:e&&e.forever,unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})};K.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort(function(u,l){return u-l}),n};K.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,n=Math.round(r*t.minTimeout*Math.pow(t.factor,e));return n=Math.min(n,t.maxTimeout),n};K.wrap=function(e,t,r){if(t instanceof Array&&(r=t,t=null),!r){r=[];for(var n in e)typeof e[n]=="function"&&r.push(n)}for(var o=0;o<r.length;o++){var u=r[o],l=e[u];e[u]=function(T){var I=K.operation(t),i=Array.prototype.slice.call(arguments,1),m=i.pop();i.push(function(c){I.retry(c)||(c&&(arguments[0]=I.mainError()),m.apply(this,arguments))}),I.attempt(function(){T.apply(e,i)})}.bind(e,l),e[u].options=t}}});var ot=k((kr,it)=>{d();it.exports=nt()});var ut=k((Ar,fe)=>{d();fe.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&fe.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&fe.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var lt=k((qr,H)=>{d();var _=globalThis.process,z=function(e){return e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function"};z(_)?(at=U("assert"),Q=ut(),ct=/^win/i.test(_.platform),ee=U("events"),typeof ee!="function"&&(ee=ee.EventEmitter),_.__signal_exit_emitter__?M=_.__signal_exit_emitter__:(M=_.__signal_exit_emitter__=new ee,M.count=0,M.emitted={}),M.infinite||(M.setMaxListeners(1/0),M.infinite=!0),H.exports=function(e,t){if(!z(globalThis.process))return function(){};at.equal(typeof e,"function","a callback must be provided for exit handler"),X===!1&&Fe();var r="exit";t&&t.alwaysLast&&(r="afterexit");var n=function(){M.removeListener(r,e),M.listeners("exit").length===0&&M.listeners("afterexit").length===0&&se()};return M.on(r,e),n},se=function(){!X||!z(globalThis.process)||(X=!1,Q.forEach(function(t){try{_.removeListener(t,le[t])}catch{}}),_.emit=me,_.reallyExit=Ie,M.count-=1)},H.exports.unload=se,B=function(t,r,n){M.emitted[t]||(M.emitted[t]=!0,M.emit(t,r,n))},le={},Q.forEach(function(e){le[e]=function(){if(z(globalThis.process)){var r=_.listeners(e);r.length===M.count&&(se(),B("exit",null,e),B("afterexit",null,e),ct&&e==="SIGHUP"&&(e="SIGINT"),_.kill(_.pid,e))}}}),H.exports.signals=function(){return Q},X=!1,Fe=function(){X||!z(globalThis.process)||(X=!0,M.count+=1,Q=Q.filter(function(t){try{return _.on(t,le[t]),!0}catch{return!1}}),_.emit=st,_.reallyExit=ft)},H.exports.load=Fe,Ie=_.reallyExit,ft=function(t){z(globalThis.process)&&(_.exitCode=t||0,B("exit",_.exitCode,null),B("afterexit",_.exitCode,null),Ie.call(_,_.exitCode))},me=_.emit,st=function(t,r){if(t==="exit"&&z(globalThis.process)){r!==void 0&&(_.exitCode=r);var n=me.apply(this,arguments);return B("exit",_.exitCode,null),B("afterexit",_.exitCode,null),n}else return me.apply(this,arguments)}):H.exports=function(){return function(){}};var at,Q,ct,ee,M,se,B,le,X,Fe,Ie,ft,me,st});var pt=k(($r,be)=>{"use strict";d();var mt=Symbol();function kt(e,t,r){let n=t[mt];if(n)return t.stat(e,(u,l)=>{if(u)return r(u);r(null,l.mtime,n)});let o=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,o,o,u=>{if(u)return r(u);t.stat(e,(l,p)=>{if(l)return r(l);let T=p.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(t,mt,{value:T}),r(null,p.mtime,T)})})}function jt(e){let t=Date.now();return e==="s"&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}be.exports.probe=kt;be.exports.getMtime=jt});var St=k((Yr,re)=>{"use strict";d();var At=U("path"),Pe=Oe(),Gt=ot(),qt=lt(),ht=pt(),q={};function te(e,t){return t.lockfilePath||`${e}.lock`}function Ne(e,t,r){if(!t.realpath)return r(null,At.resolve(e));t.fs.realpath(e,r)}function De(e,t,r){let n=te(e,t);t.fs.mkdir(n,o=>{if(!o)return ht.probe(n,t.fs,(u,l,p)=>{if(u)return t.fs.rmdir(n,()=>{}),r(u);r(null,l,p)});if(o.code!=="EEXIST")return r(o);if(t.stale<=0)return r(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:e}));t.fs.stat(n,(u,l)=>{if(u)return u.code==="ENOENT"?De(e,{...t,stale:0},r):r(u);if(!dt(l,t))return r(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:e}));yt(e,t,p=>{if(p)return r(p);De(e,{...t,stale:0},r)})})})}function dt(e,t){return e.mtime.getTime()<Date.now()-t.stale}function yt(e,t,r){t.fs.rmdir(te(e,t),n=>{if(n&&n.code!=="ENOENT")return r(n);r()})}function pe(e,t){let r=q[e];r.updateTimeout||(r.updateDelay=r.updateDelay||t.update,r.updateTimeout=setTimeout(()=>{r.updateTimeout=null,t.fs.stat(r.lockfilePath,(n,o)=>{let u=r.lastUpdate+t.stale<Date.now();if(n)return n.code==="ENOENT"||u?Me(e,r,Object.assign(n,{code:"ECOMPROMISED"})):(r.updateDelay=1e3,pe(e,t));if(!(r.mtime.getTime()===o.mtime.getTime()))return Me(e,r,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let p=ht.getMtime(r.mtimePrecision);t.fs.utimes(r.lockfilePath,p,p,T=>{let I=r.lastUpdate+t.stale<Date.now();if(!r.released){if(T)return T.code==="ENOENT"||I?Me(e,r,Object.assign(T,{code:"ECOMPROMISED"})):(r.updateDelay=1e3,pe(e,t));r.mtime=p,r.lastUpdate=Date.now(),r.updateDelay=null,pe(e,t)}})})},r.updateDelay),r.updateTimeout.unref&&r.updateTimeout.unref())}function Me(e,t,r){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),q[e]===t&&delete q[e],t.options.onCompromised(r)}function Ut(e,t,r){t={stale:1e4,update:null,realpath:!0,retries:0,fs:Pe,onCompromised:n=>{throw n},...t},t.retries=t.retries||0,t.retries=typeof t.retries=="number"?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),Ne(e,t,(n,o)=>{if(n)return r(n);let u=Gt.operation(t.retries);u.attempt(()=>{De(o,t,(l,p,T)=>{if(u.retry(l))return;if(l)return r(u.mainError());let I=q[o]={lockfilePath:te(o,t),mtime:p,mtimePrecision:T,options:t,lastUpdate:Date.now()};pe(o,t),r(null,i=>{if(I.released)return i&&i(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));vt(o,{...t,realpath:!1},i)})})})})}function vt(e,t,r){t={fs:Pe,realpath:!0,...t},Ne(e,t,(n,o)=>{if(n)return r(n);let u=q[o];if(!u)return r(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));u.updateTimeout&&clearTimeout(u.updateTimeout),u.released=!0,delete q[o],yt(o,t,r)})}function $t(e,t,r){t={stale:1e4,realpath:!0,fs:Pe,...t},t.stale=Math.max(t.stale||0,2e3),Ne(e,t,(n,o)=>{if(n)return r(n);t.fs.stat(te(o,t),(u,l)=>u?u.code==="ENOENT"?r(null,!1):r(u):r(null,!dt(l,t)))})}function Wt(){return q}qt(()=>{for(let e in q){let t=q[e].options;try{t.fs.rmdirSync(te(e,t))}catch{}}});re.exports.lock=Ut;re.exports.unlock=vt;re.exports.check=$t;re.exports.getLocks=Wt});var gt=k((zr,wt)=>{"use strict";d();var Yt=Oe();function Kt(e){let t=["mkdir","realpath","stat","rmdir","utimes"],r={...e};return t.forEach(n=>{r[n]=(...o)=>{let u=o.pop(),l;try{l=e[`${n}Sync`](...o)}catch(p){return u(p)}u(null,l)}}),r}function zt(e){return(...t)=>new Promise((r,n)=>{t.push((o,u)=>{o?n(o):r(u)}),e(...t)})}function Bt(e){return(...t)=>{let r,n;if(t.push((o,u)=>{r=o,n=u}),e(...t),r)throw r;return n}}function Jt(e){if(e={...e},e.fs=Kt(e.fs||Yt),typeof e.retries=="number"&&e.retries>0||e.retries&&typeof e.retries.retries=="number"&&e.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return e}wt.exports={toPromise:zt,toSync:Bt,toSyncOptions:Jt}});var er=k((Jr,W)=>{"use strict";d();var V=St(),{toPromise:he,toSync:de,toSyncOptions:Le}=gt();async function _t(e,t){let r=await he(V.lock)(e,t);return he(r)}function Qt(e,t){let r=de(V.lock)(e,Le(t));return de(r)}function Xt(e,t){return he(V.unlock)(e,t)}function Ht(e,t){return de(V.unlock)(e,Le(t))}function Vt(e,t){return he(V.check)(e,t)}function Zt(e,t){return de(V.check)(e,Le(t))}W.exports=_t;W.exports.lock=_t;W.exports.unlock=Xt;W.exports.lockSync=Qt;W.exports.unlockSync=Ht;W.exports.check=Vt;W.exports.checkSync=Zt});d();function $e(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}d();import*as j from"node:fs/promises";import*as G from"node:path";function Ye(){return G.join(ve.getGlobalMatildaDir(),Ae)}function we(e){return G.join(Ye(),e)}function ge(e){return G.join(we(e),qe)}function fr(e){return G.join(we(e),Ue)}function Et(e){return G.join(ve.getGlobalMatildaDir(),Ge,e)}function ie(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function sr(e,t){return`${ie(e)}@${ie(t)}`}function lr(e,t){let r=ie(e);if(!r)throw new Error(`Teammate name "${e}" sanitizes to an empty string. Choose a name with at least one alphanumeric character.`);if(r===Se)throw new Error(`"${Se}" is reserved for the team leader. Choose a different teammate name.`);let n=new Set(t.map(o=>o.name));if(n.has(r)){let o=[...n].join(", ")||"<none>";throw new Error(`A teammate named "${r}" already exists in this team (existing: ${o}). Choose a different name.`)}return r}function mr(e){let t=new Set(e.map(r=>r.color).filter(r=>r!==void 0));for(let r of ne)if(!t.has(r))return r;return ne[e.length%ne.length]}function pr(e){return e.map(t=>{let{color:r,...n}=t;return n})}function hr(e,t,r){return e.map(n=>n.agentId===t?{...n,isActive:r}:n)}function dr(e,t){return e.find(r=>r.agentId===t)}function yr(e,t){let r=ie(t);return e.find(n=>n.name===r)}function vr(e){let t=e.trimStart();if(/^shutdown_approved\b/i.test(t))return"shutdown_approved";if(/^shutdown_rejected\b/i.test(t))return"shutdown_rejected"}async function xt(e){let t=ge(e);try{let r=await j.readFile(t,"utf-8");return JSON.parse(r)}catch(r){if(ke(r)&&r.code==="ENOENT")return;throw r}}async function Sr(e,t){let r=ge(e);await j.mkdir(G.dirname(r),{recursive:!0}),await je(r,t)}async function wr(e,t){let r=ge(e);await j.mkdir(G.dirname(r),{recursive:!0}),await j.writeFile(r,JSON.stringify(t,null,2)+`
5
- `,{encoding:"utf-8",flag:"wx"})}async function gr(e){let t;try{t=await xt(e)}catch{return!1}return t?typeof t.leadPid!="number"||t.leadPid<=0||t.leadPid!==process.pid&&$e(t.leadPid)?!1:(await We(e),!0):(await We(e),!0)}async function We(e){let t=we(e),r=Et(e);await Promise.allSettled([j.rm(t,{recursive:!0,force:!0}),j.rm(r,{recursive:!0,force:!0})])}async function _r(){let e=Ye();try{return(await j.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}export{Oe as a,er as b,$e as c,Ye as d,we as e,ge as f,fr as g,Et as h,ie as i,sr as j,lr as k,mr as l,pr as m,hr as n,dr as o,yr as p,vr as q,xt as r,Sr as s,wr as t,gr as u,We as v,_r as w};
6
- /**
7
- * @license
8
- * Copyright 2026 Matilda
9
- * SPDX-License-Identifier: Apache-2.0
10
- */
11
- /**
12
- * @license
13
- * Copyright 2025 Matilda
14
- * SPDX-License-Identifier: Apache-2.0
15
- */
@@ -1,8 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{b as i}from"./chunk-GZPNIYVZ.js";i();import{AsyncLocalStorage as P}from"node:async_hooks";import{randomUUID as f}from"node:crypto";i();import{AsyncLocalStorage as E}from"node:async_hooks";var c=new E;var x="x-matilda-reported-operation-id",m="x-matilda-reported-attempt-purpose",A=[x,m],y=new Set(A),l=["answer","tool_followup","continuation","retry","compaction","unknown"],_=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,C=new Set(l),u=new P,O=new WeakSet;function R(){return f()}function s(t,e){let o=Object.freeze({operationId:t,attemptPurpose:e});return O.add(o),o}function g(t){return y.has(t.toLowerCase())}function a(){let t=u.getStore();return t&&O.has(t)?t:void 0}var T=class{activeOperationId;begin(e){return this.activeOperationId=R(),s(this.activeOperationId,e)}continue(e){let o=a()?.operationId??this.activeOperationId??R();return this.activeOperationId=o,s(o,e)}};function n(t,e){return u.run(t,e)}function v(t){u.enterWith(t)}function M(t,e){let o=a();return o?n(s(o.operationId,t),e):e()}function I(t,e){let o={next:(...r)=>n(t,()=>e.next(...r)),return:r=>n(t,()=>e.return(r)),throw:r=>n(t,()=>e.throw(r)),[Symbol.asyncIterator]:()=>o},p=Symbol.asyncDispose,d=p&&e[p];return p&&typeof d=="function"&&(o[p]=()=>n(t,()=>d.call(e))),o}function k(t,e){let o=a();return o?I(s(o.operationId,t),e):e}function Y(){let t=a();if(!t||!_.test(t.operationId))return{};let e=c.getStore()?.attempt,o=e!==void 0&&e>1?"retry":t.attemptPurpose;return C.has(o)?{[x]:t.operationId,[m]:o}:{}}export{c as a,x as b,m as c,A as d,l as e,g as f,a as g,T as h,n as i,v as j,M as k,I as l,k as m,Y as n};
4
- /**
5
- * @license
6
- * Copyright 2026 Matilda Team
7
- * SPDX-License-Identifier: Apache-2.0
8
- */
@@ -1,4 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{d as n,e as et,f as E,g as C,h as y,i as he,k as r,l as g,m as i,n as nt,o as h,q as H,r as a,t as l,z as A}from"./chunk-M53RP3YP.js";import{b as R}from"./chunk-GZPNIYVZ.js";R();var u={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",logout:"logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},p={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",mcp_message:"mcp/message",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},ke={cancel_request:"$/cancel_request"},Vt=1;R();R();R();R();var tt=Symbol("skippedItem");function s(o,e){return o.catch(e)}function q(o,e){let t=o.catch(e);return A.unknown().transform((c,d)=>c!==void 0?t.parse(c):(d.addIssue({code:"custom",message:"Required value is missing"}),A.NEVER))}function st(o,e){if(o===null||typeof o!="object"||Array.isArray(o))return;let t=o[e];return typeof t=="string"?t:void 0}function B(o,e,t){return o.superRefine((c,d)=>{let z=st(c,e);z!==void 0&&t.includes(z)&&d.addIssue({code:"custom",path:[e],message:`${e} ${JSON.stringify(z)} is reserved by a known variant, but the value does not match that variant's schema`})})}function W(o,e,t){return A.unknown().transform((c,d)=>{let z=o.safeParse(c);if(!z.success){for(let _ of z.error.issues)d.addIssue({..._,input:c});return A.NEVER}let f=z.data,m=st(c,e);if(m!==void 0&&!t.includes(m)){let _=c;for(let[j,S]of Object.entries(_))j!=="__proto__"&&(Object.hasOwn(f,j)||(f[j]=S))}return f})}function it(o,e){return A.preprocess(t=>{if(t===null||typeof t!="object"||Array.isArray(t))return t;let c=t,d=c[e];if(d==null||typeof d=="string")return t;let z={...c};return delete z[e],z},o)}function T(o){return A.array(o.catch(tt)).transform(e=>e.filter(t=>t!==tt))}var G=h([E(),n()]).nullable(),b=n(),qe=i({sessionId:b,path:n(),content:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Oe=i({sessionId:b,path:n(),line:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),limit:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ie=n(),ot=h([l("read"),l("edit"),l("delete"),l("move"),l("search"),l("execute"),l("think"),l("fetch"),l("switch_mode"),l("other")]),rt=h([l("pending"),l("in_progress"),l("completed"),l("failed")]),Xt=h([l("assistant"),l("user")]),ae=i({audience:s(T(Xt).nullish(),()=>{}),lastModified:s(n().nullish(),()=>{}),priority:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Yt=i({annotations:s(ae.nullish(),()=>{}),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Zt=i({annotations:s(ae.nullish(),()=>{}),data:n(),mimeType:n(),uri:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),es=i({annotations:s(ae.nullish(),()=>{}),data:n(),mimeType:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ns=i({annotations:s(ae.nullish(),()=>{}),description:s(n().nullish(),()=>{}),mimeType:s(n().nullish(),()=>{}),name:n(),size:s(E().nullish(),()=>{}),title:s(n().nullish(),()=>{}),uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ts=i({mimeType:s(n().nullish(),()=>{}),text:n(),uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ss=i({blob:n(),mimeType:s(n().nullish(),()=>{}),uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),is=h([ts,ss]),os=i({annotations:s(ae.nullish(),()=>{}),resource:is,_meta:s(a(n(),r()).nullish(),()=>{})}),$=h([Yt.and(i({type:l("text")})),Zt.and(i({type:l("image")})),es.and(i({type:l("audio")})),ns.and(i({type:l("resource_link")})),os.and(i({type:l("resource")}))]),rs=i({content:$,_meta:s(a(n(),r()).nullish(),()=>{})}),as=i({path:n(),oldText:s(n().nullish(),()=>{}),newText:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),V=n(),cs=i({terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),at=h([rs.and(i({type:l("content")})),as.and(i({type:l("diff")})),cs.and(i({type:l("terminal")}))]),ct=i({path:n(),line:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),lt=i({toolCallId:Ie,kind:s(ot.nullish(),()=>{}),status:s(rt.nullish(),()=>{}),title:s(n().nullish(),()=>{}),name:s(n().nullish(),()=>{}),content:s(T(at).nullish(),()=>{}),locations:s(T(ct).nullish(),()=>{}),rawInput:s(r().optional(),()=>{}),rawOutput:s(r().optional(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),dt=n(),ls=h([l("allow_once"),l("allow_always"),l("reject_once"),l("reject_always")]),ds=i({optionId:dt,name:n(),kind:ls,_meta:s(a(n(),r()).nullish(),()=>{})}),He=i({sessionId:b,toolCall:lt,options:g(ds),_meta:s(a(n(),r()).nullish(),()=>{})}),ut=i({name:n(),value:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ve=i({sessionId:b,command:n(),args:g(n()).optional(),env:g(ut).optional(),cwd:n().nullish(),outputByteLimit:E().nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ae=i({sessionId:b,terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),Ge=i({sessionId:b,terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),Pe=i({sessionId:b,terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),Le=i({sessionId:b,terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),ce=i({sessionId:b,toolCallId:s(Ie.nullish(),()=>{})}),le=i({requestId:G}),us=l("object"),zs=h([l("email"),l("uri"),l("date"),l("date-time")]),zt=i({const:n(),title:n(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ue=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),minLength:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),maxLength:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),pattern:n().nullish(),format:zs.nullish(),default:s(n().nullish(),()=>{}),enum:g(n()).nullish(),oneOf:g(zt).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Fe=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),minimum:E().nullish(),maximum:E().nullish(),default:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Be=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),minimum:E().nullish(),maximum:E().nullish(),default:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),We=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),default:s(y().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),$e=i({enum:g(n()),_meta:s(a(n(),r()).nullish(),()=>{})}),pt=i({anyOf:g(zt),_meta:s(a(n(),r()).nullish(),()=>{})}),ps=W(h([$e.and(i({type:l("string")})),B(i({type:n()}),"type",["string"]),pt]),"type",["string"]),Je=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),minItems:E().nullish(),maxItems:E().nullish(),items:ps,default:s(T(n()).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),hs=W(h([Ue.and(i({type:l("string")})),Fe.and(i({type:l("number")})),Be.and(i({type:l("integer")})),We.and(i({type:l("boolean")})),Je.and(i({type:l("array")})),B(i({type:n()}),"type",["array","boolean","integer","number","string"])]),"type",["array","boolean","integer","number","string"]),fs=i({type:s(us.optional().default("object"),()=>"object"),title:s(n().nullish(),()=>{}),properties:a(n(),hs).optional().default({}),required:g(n()).nullish(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ve=H(h([ce,le]),i({requestedSchema:fs})),ht=n(),Ke=H(h([ce,le]),i({elicitationId:ht,url:et()})),Qe=W(H(h([Ve.and(i({mode:l("form")})),Ke.and(i({mode:l("url")})),B(H(h([ce,le]),i({mode:n()})),"mode",["form","url"])]),i({message:n(),_meta:s(a(n(),r()).nullish(),()=>{})})),"mode",["form","url"]),Xe=n(),ft=n(),ms=i({serverId:Xe,requestId:ft,method:n(),params:a(n(),r()).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),mt=r(),Fr=i({id:G,method:n(),params:h([qe,Oe,He,ve,Ae,Ge,Pe,Le,Qe,ms,mt]).nullish()}),gt=C().gte(0).lte(65535),gs=i({image:s(y().optional().default(!1),()=>!1),audio:s(y().optional().default(!1),()=>!1),embeddedContext:s(y().optional().default(!1),()=>!1),_meta:s(a(n(),r()).nullish(),()=>{})}),_s=i({http:s(y().optional().default(!1),()=>!1),sse:s(y().optional().default(!1),()=>!1),acp:s(y().optional().default(!1),()=>!1),_meta:s(a(n(),r()).nullish(),()=>{})}),bs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Es=i({_meta:s(a(n(),r()).nullish(),()=>{})}),xs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ss=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ts=i({_meta:s(a(n(),r()).nullish(),()=>{})}),ws=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Rs=i({list:s(bs.nullish(),()=>{}),delete:s(Es.nullish(),()=>{}),additionalDirectories:s(xs.nullish(),()=>{}),fork:s(Ss.nullish(),()=>{}),resume:s(Ts.nullish(),()=>{}),close:s(ws.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ns=i({_meta:s(a(n(),r()).nullish(),()=>{})}),js=i({logout:s(Ns.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ys=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Cs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ms=h([l("full"),l("incremental")]),ks=i({syncKind:Ms,_meta:s(a(n(),r()).nullish(),()=>{})}),Ds=i({_meta:s(a(n(),r()).nullish(),()=>{})}),qs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Os=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Is=i({didOpen:s(Cs.nullish(),()=>{}),didChange:s(ks.nullish(),()=>{}),didClose:s(Ds.nullish(),()=>{}),didSave:s(qs.nullish(),()=>{}),didFocus:s(Os.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Hs=i({document:s(Is.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),vs=i({maxCount:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),As=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Gs=i({maxCount:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ps=i({maxCount:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ls=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Us=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Fs=i({recentFiles:s(vs.nullish(),()=>{}),relatedSnippets:s(As.nullish(),()=>{}),editHistory:s(Gs.nullish(),()=>{}),userActions:s(Ps.nullish(),()=>{}),openFiles:s(Ls.nullish(),()=>{}),diagnostics:s(Us.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Bs=i({events:s(Hs.nullish(),()=>{}),context:s(Fs.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),_t=h([l("utf-16"),l("utf-32"),l("utf-8")]),Ws=i({loadSession:s(y().optional().default(!1),()=>!1),promptCapabilities:s(gs.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:s(_s.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:s(Rs.optional().default({}),()=>({})),auth:s(js.optional().default({}),()=>({})),providers:s(ys.nullish(),()=>{}),nes:s(Bs.nullish(),()=>{}),positionEncoding:s(_t.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ye=n(),$s=i({id:Ye,name:n(),description:s(n().nullish(),()=>{}),args:g(n()).optional(),env:a(n(),n()).optional(),_meta:s(a(n(),r()).nullish(),()=>{})}),Js=i({id:Ye,name:n(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Vs=h([$s.and(i({type:l("terminal")})),Js]),bt=i({name:n(),title:s(n().nullish(),()=>{}),version:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ks=i({protocolVersion:gt,agentCapabilities:s(Ws.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:s(T(Vs).optional().default([]),()=>[]),agentInfo:s(bt.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Qs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ze=n(),en=h([l("anthropic"),l("openai"),l("azure"),l("vertex"),l("bedrock"),n()]),Xs=i({apiType:en,baseUrl:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ys=i({providerId:Ze,supported:q(T(en),()=>[]),required:y(),current:Xs.nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Zs=i({providers:g(Ys),_meta:s(a(n(),r()).nullish(),()=>{})}),ei=i({_meta:s(a(n(),r()).nullish(),()=>{})}),ni=i({_meta:s(a(n(),r()).nullish(),()=>{})}),ti=i({_meta:s(a(n(),r()).nullish(),()=>{})}),fe=n(),si=i({id:fe,name:n(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),me=i({currentModeId:fe,availableModes:q(T(si),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),Et=n(),ii=h([l("mode"),l("model"),l("model_config"),l("thought_level"),n()]),nn=n(),xt=i({value:nn,name:n(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),oi=n(),ri=i({group:oi,name:n(),options:q(T(xt),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),ai=h([g(xt),g(ri)]),ci=i({currentValue:nn,options:ai}),li=i({currentValue:y()}),K=H(h([ci.and(i({type:l("select")})),li.and(i({type:l("boolean")}))]),i({id:Et,name:n(),description:s(n().nullish(),()=>{}),category:s(ii.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})})),di=i({sessionId:b,modes:s(me.nullish(),()=>{}),configOptions:s(T(K).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ui=i({modes:s(me.nullish(),()=>{}),configOptions:s(T(K).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),zi=i({sessionId:b,cwd:n(),additionalDirectories:s(T(n()).optional(),()=>[]),title:s(n().nullish(),()=>{}),updatedAt:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),pi=i({sessions:q(T(zi),()=>[]),nextCursor:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),hi=i({_meta:s(a(n(),r()).nullish(),()=>{})}),fi=i({sessionId:b,modes:s(me.nullish(),()=>{}),configOptions:s(T(K).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),mi=i({modes:s(me.nullish(),()=>{}),configOptions:s(T(K).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),gi=i({_meta:s(a(n(),r()).nullish(),()=>{})}),_i=i({_meta:s(a(n(),r()).nullish(),()=>{})}),bi=i({configOptions:q(T(K),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),Ei=h([l("end_turn"),l("max_tokens"),l("max_turn_requests"),l("refusal"),l("cancelled")]),ge=i({totalTokens:E(),inputTokens:E(),outputTokens:E(),thoughtTokens:s(E().nullish(),()=>{}),cachedReadTokens:s(E().nullish(),()=>{}),cachedWriteTokens:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),xi=i({stopReason:Ei,usage:s(ge.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Si=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),Q=n(),P=i({line:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),character:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),_meta:s(a(n(),r()).nullish(),()=>{})}),X=i({start:P,end:P,_meta:s(a(n(),r()).nullish(),()=>{})}),Ti=i({range:X,newText:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),wi=i({id:Q,uri:n(),edits:g(Ti),cursorPosition:s(P.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ri=i({id:Q,uri:n(),position:P,_meta:s(a(n(),r()).nullish(),()=>{})}),Ni=i({id:Q,uri:n(),position:P,newName:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ji=i({id:Q,uri:n(),search:n(),replace:n(),isRegex:y().nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),yi=h([wi.and(i({kind:l("edit")})),Ri.and(i({kind:l("jump")})),Ni.and(i({kind:l("rename")})),ji.and(i({kind:l("searchAndReplace")}))]),Ci=i({suggestions:g(yi),_meta:s(a(n(),r()).nullish(),()=>{})}),Mi=i({_meta:s(a(n(),r()).nullish(),()=>{})}),St=r(),ki=h([l(-32700),l(-32600),l(-32601),l(-32602),l(-32603),l(-32800),l(-32e3),l(-32002),C().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"})]),de=i({code:ki,message:n(),data:s(r().optional(),()=>{})}),Br=h([i({id:G,result:h([Ks,Qs,Zs,ei,ni,ti,di,ui,pi,hi,fi,mi,gi,_i,bi,xi,Si,Ci,Mi,St])}),i({id:G,error:de})]),tn=n(),De=i({content:$,messageId:s(tn.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Di=i({toolCallId:Ie,title:n(),name:s(n().nullish(),()=>{}),kind:s(ot.optional(),()=>{}),status:s(rt.optional(),()=>{}),content:s(T(at).optional(),()=>[]),locations:s(T(ct).optional(),()=>[]),rawInput:s(r().optional(),()=>{}),rawOutput:s(r().optional(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),qi=h([l("high"),l("medium"),l("low")]),Oi=h([l("pending"),l("in_progress"),l("completed")]),Tt=i({content:n(),priority:qi,status:Oi,_meta:s(a(n(),r()).nullish(),()=>{})}),Ii=i({entries:q(T(Tt),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),_e=n(),Hi=i({planId:_e,entries:q(T(Tt),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),vi=i({planId:_e,uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ai=i({planId:_e,content:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Gi=h([Hi.and(i({type:l("items")})),vi.and(i({type:l("file")})),Ai.and(i({type:l("markdown")}))]),Pi=i({plan:Gi,_meta:s(a(n(),r()).nullish(),()=>{})}),Li=i({planId:_e,_meta:s(a(n(),r()).nullish(),()=>{})}),Ui=i({hint:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Fi=Ui,Bi=i({name:n(),description:n(),input:s(Fi.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Wi=i({availableCommands:q(T(Bi),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),$i=i({currentModeId:fe,_meta:s(a(n(),r()).nullish(),()=>{})}),Ji=i({configOptions:q(T(K),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),Vi=i({title:s(n().nullish(),()=>{}),updatedAt:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ki=i({amount:E(),currency:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Qi=i({used:E(),size:E(),cost:s(Ki.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Xi=h([l("info"),l("warning"),l("error"),n()]),Yi=i({severity:Xi,title:n().min(1),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),wt=n(),Zi=h([l("in_progress"),l("completed"),l("failed"),l("cancelled"),n()]),eo=i({compactionId:wt,status:Zi,summary:s(T($).nullish(),()=>{}),error:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),no=i({compactionId:wt,content:$,_meta:s(a(n(),r()).nullish(),()=>{})}),to=i({_meta:s(a(n(),r()).nullish(),()=>{})}),so=i({cancel:s(to.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),sn=i({_meta:s(a(n(),r()).nullish(),()=>{})}),on=i({error:s(de.nullish(),()=>{})}),rn=it(W(H(h([i({stopReason:l("end_turn")}),i({stopReason:l("max_tokens")}),i({stopReason:l("max_turn_requests")}),i({stopReason:l("refusal")}),i({stopReason:l("cancelled")}),on.and(i({stopReason:l("error")})),B(i({stopReason:n()}),"stopReason",["cancelled","end_turn","error","max_tokens","max_turn_requests","refusal"]),i({stopReason:he().optional()})]),i({usage:s(ge.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{}),stopReason:s(n().nullish(),()=>{})})),"stopReason",["cancelled","end_turn","error","max_tokens","max_turn_requests","refusal"]),"stopReason"),an=i({_meta:s(a(n(),r()).nullish(),()=>{})}),cn=i({_meta:s(a(n(),r()).nullish(),()=>{})}),io=W(h([sn.and(i({state:l("running")})),rn.and(i({state:l("idle")})),an.and(i({state:l("requires_action")})),cn.and(i({state:l("unknown")})),B(i({state:n()}),"state",["idle","requires_action","running","unknown"])]),"state",["idle","requires_action","running","unknown"]),oo=i({sessionId:b,title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),capabilities:s(so.nullish(),()=>{}),state:s(io.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ro=i({messageId:tn,senderSessionId:s(b.nullish(),()=>{}),recipientSessionId:s(b.nullish(),()=>{}),content:s(T($).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ao=i({messageId:tn,senderSessionId:s(b.nullish(),()=>{}),recipientSessionId:s(b.nullish(),()=>{}),content:$,_meta:s(a(n(),r()).nullish(),()=>{})}),co=h([De.and(i({sessionUpdate:l("user_message_chunk")})),De.and(i({sessionUpdate:l("agent_message_chunk")})),De.and(i({sessionUpdate:l("agent_thought_chunk")})),Di.and(i({sessionUpdate:l("tool_call")})),lt.and(i({sessionUpdate:l("tool_call_update")})),Ii.and(i({sessionUpdate:l("plan")})),Pi.and(i({sessionUpdate:l("plan_update")})),Li.and(i({sessionUpdate:l("plan_removed")})),Wi.and(i({sessionUpdate:l("available_commands_update")})),$i.and(i({sessionUpdate:l("current_mode_update")})),Ji.and(i({sessionUpdate:l("config_option_update")})),Vi.and(i({sessionUpdate:l("session_info_update")})),Qi.and(i({sessionUpdate:l("usage_update")})),Yi.and(i({sessionUpdate:l("notice")})),eo.and(i({sessionUpdate:l("compaction_update")})),no.and(i({sessionUpdate:l("compaction_summary_chunk")})),oo.and(i({sessionUpdate:l("subagent_update")})),ro.and(i({sessionUpdate:l("session_message")})),ao.and(i({sessionUpdate:l("session_message_chunk")}))]),be=i({sessionId:b,update:co,_meta:s(a(n(),r()).nullish(),()=>{})}),ln=i({elicitationId:ht,_meta:s(a(n(),r()).nullish(),()=>{})}),Rt=r(),Wr=i({method:n(),params:h([be,ln,Rt]).nullish()}),lo=i({readTextFile:s(y().optional().default(!1),()=>!1),writeTextFile:s(y().optional().default(!1),()=>!1),_meta:s(a(n(),r()).nullish(),()=>{})}),uo=a(n(),r()),zo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),po=i({boolean:s(zo.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ho=a(n(),r()),fo=i({compaction:s(uo.nullish(),()=>{}),configOptions:s(po.nullish(),()=>{}),notices:s(ho.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),mo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),go=i({_meta:s(a(n(),r()).nullish(),()=>{})}),_o=i({terminal:s(y().optional().default(!1),()=>!1),_meta:s(a(n(),r()).nullish(),()=>{})}),bo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Eo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),xo=i({form:s(bo.nullish(),()=>{}),url:s(Eo.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),So=i({_meta:s(a(n(),r()).nullish(),()=>{})}),To=i({_meta:s(a(n(),r()).nullish(),()=>{})}),wo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ro=i({jump:s(So.nullish(),()=>{}),rename:s(To.nullish(),()=>{}),searchAndReplace:s(wo.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),No=i({fs:s(lo.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:s(y().optional().default(!1),()=>!1),session:s(fo.nullish(),()=>{}),subagents:s(mo.nullish(),()=>{}),plan:s(go.nullish(),()=>{}),auth:s(_o.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:s(xo.nullish(),()=>{}),nes:s(Ro.nullish(),()=>{}),positionEncodings:s(T(_t).optional(),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),dn=i({protocolVersion:gt,clientCapabilities:s(No.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:s(bt.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),un=i({methodId:Ye,_meta:s(a(n(),r()).nullish(),()=>{})}),zn=i({_meta:s(a(n(),r()).nullish(),()=>{})}),pn=i({providerId:Ze,apiType:en,baseUrl:n(),headers:a(n(),n()).optional(),_meta:s(a(n(),r()).nullish(),()=>{})}),hn=i({providerId:Ze,_meta:s(a(n(),r()).nullish(),()=>{})}),fn=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Nt=i({name:n(),value:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),jo=i({name:n(),url:n(),headers:g(Nt),_meta:s(a(n(),r()).nullish(),()=>{})}),yo=i({name:n(),url:n(),headers:g(Nt),_meta:s(a(n(),r()).nullish(),()=>{})}),Co=i({name:n(),serverId:Xe,_meta:s(a(n(),r()).nullish(),()=>{})}),Mo=i({name:n(),command:n(),args:g(n()),env:g(ut),_meta:s(a(n(),r()).nullish(),()=>{})}),Ee=h([jo.and(i({type:l("http")})),yo.and(i({type:l("sse")})),Co.and(i({type:l("acp")})),Mo]),mn=i({cwd:n(),additionalDirectories:g(n()).optional(),mcpServers:g(Ee),_meta:s(a(n(),r()).nullish(),()=>{})}),gn=i({mcpServers:g(Ee),cwd:n(),additionalDirectories:g(n()).optional(),sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),_n=i({cwd:n().nullish(),cursor:n().nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),bn=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),En=i({sessionId:b,cwd:n(),additionalDirectories:g(n()).optional(),mcpServers:g(Ee).optional(),_meta:s(a(n(),r()).nullish(),()=>{})}),xn=i({sessionId:b,cwd:n(),additionalDirectories:g(n()).optional(),mcpServers:g(Ee).optional(),_meta:s(a(n(),r()).nullish(),()=>{})}),Sn=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),Tn=i({sessionId:b,modeId:fe,_meta:s(a(n(),r()).nullish(),()=>{})}),wn=H(h([i({value:y(),type:l("boolean")}),i({value:nn})]),i({sessionId:b,configId:Et,_meta:s(a(n(),r()).nullish(),()=>{})})),Rn=i({sessionId:b,prompt:g($),_meta:s(a(n(),r()).nullish(),()=>{})}),ko=i({uri:n(),name:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Do=i({name:n(),owner:n(),remoteUrl:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Nn=i({workspaceUri:s(n().nullish(),()=>{}),workspaceFolders:g(ko).nullish(),repository:s(Do.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),qo=h([l("automatic"),l("diagnostic"),l("manual")]),Oo=i({uri:n(),languageId:n(),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Io=i({startLine:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),endLine:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ho=i({uri:n(),excerpts:g(Io),_meta:s(a(n(),r()).nullish(),()=>{})}),vo=i({uri:n(),diff:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ao=i({action:n(),uri:n(),position:P,timestampMs:E(),_meta:s(a(n(),r()).nullish(),()=>{})}),Go=i({uri:n(),languageId:n(),visibleRange:s(X.nullish(),()=>{}),lastFocusedMs:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Po=h([l("error"),l("warning"),l("information"),l("hint")]),Lo=i({uri:n(),range:X,severity:Po,message:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Uo=i({recentFiles:g(Oo).nullish(),relatedSnippets:g(Ho).nullish(),editHistory:g(vo).nullish(),userActions:g(Ao).nullish(),openFiles:g(Go).nullish(),diagnostics:g(Lo).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),jn=i({sessionId:b,uri:n(),version:E(),position:P,selection:X.nullish(),triggerKind:qo,context:Uo.nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),yn=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),$r=i({id:G,method:n(),params:h([dn,un,zn,pn,hn,fn,mn,gn,_n,bn,En,xn,Sn,Tn,wn,Rn,Nn,jn,yn,mt]).nullish()}),Fo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Bo=i({content:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Wo=i({optionId:dt,_meta:s(a(n(),r()).nullish(),()=>{})}),$o=h([i({outcome:l("cancelled")}),Wo.and(i({outcome:l("selected")}))]),Jo=i({outcome:$o,_meta:s(a(n(),r()).nullish(),()=>{})}),Vo=i({terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),Ko=i({exitCode:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Qo=i({output:n(),truncated:y(),exitStatus:s(Ko.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Xo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Yo=i({exitCode:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Zo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),er=h([n(),E(),E(),y(),g(n())]),Cn=i({content:a(n(),er).nullish()}),nr=W(H(h([Cn.and(i({action:l("accept")})),i({action:l("decline")}),i({action:l("cancel")}),B(i({action:n()}),"action",["accept","cancel","decline"])]),i({_meta:s(a(n(),r()).nullish(),()=>{})})),"action",["accept","cancel","decline"]),tr=nt({code:C().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"}),message:n(),data:r().optional()}),sr=h([i({result:r(),_meta:s(a(n(),r()).nullish(),()=>{})}),i({error:tr,_meta:s(a(n(),r()).nullish(),()=>{})})]),Jr=h([i({id:G,result:h([Fo,Bo,Jo,Vo,Qo,Xo,Yo,Zo,nr,sr,St])}),i({id:G,error:de})]),Mn=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),kn=i({sessionId:b,uri:n(),languageId:n(),version:E(),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ir=i({range:X.nullish(),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Dn=i({sessionId:b,uri:n(),version:E(),contentChanges:g(ir),_meta:s(a(n(),r()).nullish(),()=>{})}),qn=i({sessionId:b,uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),On=i({sessionId:b,uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),In=i({sessionId:b,uri:n(),version:E(),position:P,visibleRange:X,_meta:s(a(n(),r()).nullish(),()=>{})}),Hn=i({sessionId:b,id:Q,_meta:s(a(n(),r()).nullish(),()=>{})}),or=h([l("rejected"),l("ignored"),l("replaced"),l("cancelled")]),vn=i({sessionId:b,id:Q,reason:s(or.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),rr=i({serverId:Xe,requestId:ft,method:n(),params:a(n(),r()).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Vr=i({method:n(),params:h([Mn,kn,Dn,qn,On,In,Hn,vn,rr,Rt]).nullish()}),Kr=i({requestId:G,_meta:s(a(n(),r()).nullish(),()=>{})});R();R();var yt="$/cancel_request";function xe(o){return Ln(o)&&"id"in o&&typeof o.method=="string"&&Un(o.id)}function Mt(o){if(!Ln(o)||"method"in o||!("id"in o)||!Un(o.id))return!1;let e=Object.hasOwn(o,"result"),t=Object.hasOwn(o,"error");return e===t?!1:!t||lr(o.error)}function Y(o){return Ln(o)&&!("id"in o)&&typeof o.method=="string"}function L(o){return typeof o=="object"&&o!==null}function Ln(o){return L(o)&&o.jsonrpc==="2.0"}function Un(o){return o===null||typeof o=="string"||typeof o=="number"&&Number.isFinite(o)}function Ct(o){return L(o)&&!("method"in o)&&("id"in o||"result"in o||"error"in o)}function ar(o){let e=!1,t=!1,c=!1,d=!1;for(let z of o)e||=xe(z)||Y(z),t||=Mt(z),L(z)&&(c||="method"in z,d||="result"in z||"error"in z);return e?!1:t?!0:d&&!c}function cr(o){if(!(!L(o)||!Un(o.requestId)))return o.requestId}function lr(o){return L(o)&&typeof o.code=="number"&&Number.isInteger(o.code)&&typeof o.message=="string"}var M={yes(){return{handled:!0}},no(o,e=!1){return{handled:!1,message:o,retry:e}}};function J(o){let e=Promise.reject(o);return e.catch(()=>{}),e}function dr(o){if(o instanceof Error||typeof o=="object"&&o!=null&&"message"in o&&typeof o.message=="string")return o.message}function ur(o){return typeof o=="object"&&o!==null&&"name"in o&&o.name==="ZodError"&&"issues"in o&&Array.isArray(o.issues)&&"format"in o&&typeof o.format=="function"}function kt(o){if(o instanceof N)return o.toResult();if(ur(o))return N.invalidParams(o.format()).toResult();let e=dr(o);try{return N.internalError(e?JSON.parse(e):{}).toResult()}catch{return N.internalError({details:e}).toResult()}}function zr(o){return o instanceof N&&o.code===-32800?o:N.requestCancelled(o)}function pr(o,e){let t=hr(o,e);return t?t.toResult():kt(o)}function hr(o,e){if(!(!e.aborted||!fr(o)))return zr(e.reason)}function fr(o){if(typeof o!="object"||o===null)return!1;let e=o;return e.name==="AbortError"||e.code==="ABORT_ERR"}var An=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,c=new AbortController().signal,d){this.id=e,this.sendResult=t,this.signal=c,this.finishRequest=d}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof N?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?J(new Error("JSON-RPC request already responded")):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},mr=new WeakMap;var ee=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Gn=class{connection;constructor(e){this.connection=e}sendRequest(e,t,c,d){return this.connection.sendRequest(e,t,c,d)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendBatch(e){return this.connection.sendBatch(e)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},ne=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Gn(this);receiveReader;allowBatches=!0;constructor(e,t,c,d){if(typeof e=="function"){let _=e,j=t,S=c;this.initialize(S,[...d?.handlers??[],this.legacyHandler(_,j)],d);return}let z=e,f=t,m=c;this.initialize(z,[...m?.handlers??[],...f],m)}static builder(){return new Pn}runUntil(e){let t=!1,c=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),d=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([c,d]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let t of this.retryQueue.splice(0))this.processIncomingMessage(t).catch(c=>this.close(c));return new ee(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,c,d={}){if(this.abortController.signal.aborted)return J(this.closedReason());let z=this.prepareRequest(e,t,c,d);return this.sendWireMessage(z.message).catch(()=>{}),d.cancellationSignal?.aborted&&z.cancel(),z.response}sendBatch(e){if(this.abortController.signal.aborted)return J(this.closedReason());if(!this.allowBatches)return J(new TypeError("JSON-RPC batches are not supported on this connection"));if(e.length===0)return J(new TypeError("JSON-RPC batch must contain at least one entry"));let t=[],c=[],d=[];for(let _ of e){if(_.kind==="notification"){t.push({jsonrpc:"2.0",method:_.method,params:_.params}),d.push(Promise.resolve(void 0));continue}let j=this.prepareRequest(_.method,_.params,_.mapResponse,_.options);t.push(j.message),d.push(j.response),c.push({signal:_.options?.cancellationSignal,cancel:j.cancel})}let z=t,f=this.sendWireMessage(z);for(let _ of c)_.signal?.aborted&&_.cancel();let m=Promise.all([f,...d]).then(([,..._])=>_);return m.catch(()=>{}),m}sendCancelRequest(e){return this.sendNotification(yt,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?J(this.closedReason()):this.sendWireMessage({jsonrpc:"2.0",method:e,params:t})}prepareRequest(e,t,c,d={}){let z=this.nextRequestId++,f=()=>{},m=new Promise((_,j)=>{let S={resolve:D=>{try{_(c?c(D):D)}catch(k){j(k)}},reject:j};f=()=>{S.cancellationSent||(S.cancellationSent=!0,S.cleanup?.(),this.sendCancelRequest(z).catch(()=>{}))},d.cancellationSignal?.addEventListener("abort",f,{once:!0}),S.cleanup=()=>{d.cancellationSignal?.removeEventListener("abort",f)},this.pendingResponses.set(z,S)});return m.catch(()=>{}),{message:{jsonrpc:"2.0",id:z,method:e,params:t},response:m,cancel:()=>f()}}close(e){if(this.abortController.signal.aborted)return;let t=e??new Error("ACP connection closed");this.abortController.abort(t);for(let c of this.pendingResponses.values())c.cleanup?.(),c.reject(t);this.pendingResponses.clear();for(let c of this.incomingRequests.values())c.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t,c){this.stream=e,this.staticHandlers=t,this.allowBatches=c?.allowBatches??!0,this.closedPromise=new Promise(d=>{this.abortController.signal.addEventListener("abort",()=>d())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(c,d)=>{if(c.kind==="request"){let z=await e(c.method,c.params,d);await c.responder.respond(z)}else await t(c.method,c.params,d);return M.yes()}}}async receive(){let e;try{let t=this.stream.readable.getReader();this.receiveReader=t;try{for(;!this.abortController.signal.aborted;){let{value:c,done:d}=await t.read();if(this.abortController.signal.aborted||d)break;this.receiveWireMessage(c)}}finally{this.receiveReader===t&&(this.receiveReader=void 0),t.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveWireMessage(e){if(Array.isArray(e)){if(!this.allowBatches){this.close(new TypeError("JSON-RPC batches are not supported on this connection"));return}this.receiveBatch(e);return}if(!xe(e)&&!Y(e)&&!Ct(e)){this.sendWireMessage(Z(N.invalidRequest(e))).catch(()=>{});return}this.receiveMessage(e)}receiveBatch(e){if(e.length===0){this.sendWireMessage(Z(N.invalidRequest(e))).catch(()=>{});return}let t=ar(e),d=t?0:e.reduce((S,D)=>S+(Y(D)?0:1),0),z=e.reduce((S,D)=>S+(Y(D)?1:0),0),f=!1,m=[],_=async()=>{f||d!==0||z!==0||m.length===0||(f=!0,await this.sendWireMessage(m))},j=async S=>{m.push(S),d-=1,await _()};for(let S of e){if(t){Ct(S)&&this.receiveMessage(S);continue}if(!xe(S)&&!Y(S)){j(Z(N.invalidRequest(S))).catch(()=>{});continue}let D=this.receiveMessage(S,xe(S)?j:void 0,e.length);Y(S)&&D.finally(()=>{z-=1,_().catch(k=>this.close(k))})}}receiveMessage(e,t,c){return this.abortController.signal.aborted?Promise.resolve():L(e)?"method"in e?("id"in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e,t,c)).catch(d=>this.close(d))):("id"in e?this.handleResponse(e):console.error("Invalid message",{message:e}),Promise.resolve()):(console.error("Invalid message",{message:e}),Promise.resolve())}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,c=!1;try{for(let d of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let z=await d.handleMessage(t,this.context)??{handled:!0};if(z.handled)return;t=z.message??t,c=c||!!z.retry}c?this.retryQueue.push(t):t.kind==="request"&&await t.responder.respondWithError(N.methodNotFound(t.method))}catch(d){if(this.abortController.signal.aborted)return;if(t.kind==="request"&&!t.responder.responded)await t.responder.respondWithResult(pr(d,t.responder.signal));else{let z=kt(d);"error"in z&&console.error("Error handling notification",e.raw,z.error)}}}toIncomingMessage(e,t,c){if("id"in e){let d=new AbortController;this.incomingRequests.set(e.id,d);let z=()=>{this.incomingRequests.get(e.id)===d&&this.incomingRequests.delete(e.id)},f=new An(e.id,m=>{let _={jsonrpc:"2.0",id:e.id,...m};return t?t(_):this.sendWireMessage(_)},d.signal,z);return c!==void 0&&mr.set(f,c),{kind:"request",method:e.method,params:e.params,raw:e,signal:d.signal,responder:f}}return{kind:"notification",method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t)if(this.pendingResponses.delete(e.id),t.cleanup?.(),!Mt(e))t.reject(N.invalidRequest(e));else if("result"in e)t.resolve(e.result);else{let{code:c,message:d,data:z}=e.error;t.reject(new N(c,d,z))}else console.error("Got response to unknown request",e.id)}handleProtocolNotification(e){if(e.method!==yt)return;let t=cr(e.params);if(t===void 0)return;let c=this.incomingRequests.get(t);!c||c.signal.aborted||c.abort(N.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendWireMessage(e){return this.abortController.signal.aborted?J(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(t=>{throw this.close(t),t}),this.writeQueue)}},Pn=class{handlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,c)=>await e(t,c)??M.no(t),describe:()=>this.connectionName??"onReceiveMessage"})}onReceiveRequest(e,t,c){return this.withHandler({handleMessage:async(d,z)=>{if(d.kind!=="request"||d.method!==e)return M.no(d);let f=t(d.params);return await c(f,d.responder,z)??M.yes()},describe:()=>`${this.connectionName??"request"}:${e}`})}onReceiveNotification(e,t,c){return this.withHandler({handleMessage:async(d,z)=>{if(d.kind!=="notification"||d.method!==e)return M.no(d);let f=t(d.params);return await c(f,z)??M.yes()},describe:()=>`${this.connectionName??"notification"}:${e}`})}connect(e,t){return new ne(e,this.handlers,t)}connectWith(e,t,c){return this.connect(e,c).runUntil(t)}},N=class o extends Error{code;data;constructor(e,t,c){super(t),this.code=e,this.name="RequestError",this.data=c}static parseError(e,t){return new o(-32700,`Parse error${t?`: ${t}`:""}`,e)}static invalidRequest(e,t){return new o(-32600,`Invalid request${t?`: ${t}`:""}`,e)}static methodNotFound(e){return new o(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,t){return new o(-32602,`Invalid params${t?`: ${t}`:""}`,e)}static internalError(e,t){return new o(-32603,`Internal error${t?`: ${t}`:""}`,e)}static requestCancelled(e,t){return new o(-32800,`Request cancelled${t?`: ${t}`:""}`,e)}static authRequired(e,t){return new o(-32e3,`Authentication required${t?`: ${t}`:""}`,e)}static resourceNotFound(e){return new o(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};function Z(o){return{jsonrpc:"2.0",id:null,error:o.toErrorResponse()}}R();R();var te=class extends Error{maxMessageBytes;constructor(e){super(`Incoming ACP data exceeds the configured ${e} byte limit`),this.maxMessageBytes=e,this.name="MessageTooLargeError"}};function ue(o){let e=o??33554432;if(!Number.isSafeInteger(e)||e<=0)throw new RangeError("maxMessageBytes must be a positive safe integer");return e}var Se=class{#e=new Uint8Array(0);#n=0;#t;constructor(e){this.#t=ue(e)}get byteLength(){return this.#n}get lastByte(){return this.#e[this.#n-1]}#s(e){if(e>this.#t-this.#n)throw this.clear(),new te(this.#t)}append(e){this.#s(e.byteLength);let t=this.#n+e.byteLength;if(t>this.#e.byteLength){let c=Math.min(this.#t,Math.max(t,this.#e.byteLength*2,1024)),d=new Uint8Array(c);d.set(this.#e.subarray(0,this.#n)),this.#e=d}this.#e.set(e,this.#n),this.#n=t}take(){let e=this.#e.subarray(0,this.#n);return this.clear(),e}clear(){this.#e=new Uint8Array(0),this.#n=0}};var Dt=10,Te=class{#e;#n;constructor(e){this.#n=ue(e),this.#e=new Se(Math.min(Number.MAX_SAFE_INTEGER,this.#n+1))}*push(e){let t=0,c=e.indexOf(Dt,t);for(;c!==-1;)yield this.#t(e.subarray(t,c)),t=c+1,c=e.indexOf(Dt,t);if(t<e.byteLength){let d=e.subarray(t);this.#s(d),this.#e.append(d)}}flush(){if(this.#e.byteLength!==0)return Fn(this.#e.take())}clear(){this.#e.clear()}#t(e){return this.#s(e),this.#e.byteLength===0?Fn(e):(this.#e.append(e),Fn(this.#e.take()))}#s(e){let t=e.byteLength>0?e[e.byteLength-1]:this.#e.lastByte;if(this.#e.byteLength+e.byteLength-(t===13?1:0)>this.#n)throw this.clear(),new te(this.#n)}};function Fn(o){return o[o.byteLength-1]===13?o.subarray(0,-1):o}function qt(o,e,t={}){let c=ue(t.maxMessageBytes),d=new TextEncoder,z=new TextDecoder,f=!1,m,_=Promise.resolve(),j=k=>{let ie=JSON.stringify(k)+`
4
- `,oe=_.then(async()=>{let v=o.getWriter();try{await v.write(d.encode(ie))}finally{v.releaseLock()}});return _=oe.catch(()=>{}),oe},S=new ReadableStream({async start(k){let ie=new Te(c),oe=async U=>{let re=z.decode(U).trim();if(!re)return;let F;try{F=JSON.parse(re)}catch{await j(Z(N.parseError()));return}L(F)||Array.isArray(F)?k.enqueue(F):await j(Z(N.invalidRequest(F)))},v=e.getReader();m=v;try{for(;;){let{value:re,done:F}=await v.read();if(f)return;if(F)break;if(re){for(let Jt of ie.push(re))if(await oe(Jt),f)return}}if(f)return;let U=ie.flush();U&&await oe(U)}catch(U){if(f)return;k.error(U),v.cancel(U).catch(()=>{});return}finally{ie.clear(),m===v&&(m=void 0),v.releaseLock()}f||k.close()},cancel(k){return f=!0,m?.cancel(k)}}),D=new WritableStream({write(k){return j(k)}});return{readable:S,writable:D}}R();var la=Ve.and(i({mode:l("form")})).and(i({message:n()})),da=Ke.and(i({mode:l("url")})).and(i({message:n()})),ua=h([ce,le]).and(i({message:n()})),za=Ue.and(i({type:l("string")})),pa=Fe.and(i({type:l("number")})),ha=Be.and(i({type:l("integer")})),fa=We.and(i({type:l("boolean")})),ma=Je.and(i({type:l("array")})),ga=$e.and(i({type:l("string")}));var _a=sn.and(i({state:l("running")})),ba=rn.and(i({usage:ge.nullish()})).and(i({state:l("idle")})),Ea=an.and(i({state:l("requires_action")})),xa=cn.and(i({state:l("unknown")})),Sa=i({stopReason:l("end_turn")}),Ta=i({stopReason:l("max_tokens")}),wa=i({stopReason:l("max_turn_requests")}),Ra=i({stopReason:l("refusal")}),Na=i({stopReason:l("cancelled")}),ja=on.and(i({error:de.nullish()})).and(i({stopReason:l("error")})),ya=i({stopReason:he().optional()}),Ca=Cn.and(i({action:l("accept")})),Ma=i({action:l("decline")}),ka=i({action:l("cancel")});function Ua(o,e,t){return qt(o,e,t)}function w(o){return o??{}}function At(o){return typeof o=="object"&&o!==null&&"readable"in o&&"writable"in o}function Gt(){let o=new TransformStream,e=new TransformStream;return[{readable:e.readable,writable:o.writable},{readable:o.readable,writable:e.writable}]}var Ba={agent:{initialize:u.initialize,authenticate:u.authenticate,logout:u.logout,providers:{list:u.providers_list,set:u.providers_set,disable:u.providers_disable},session:{new:u.session_new,load:u.session_load,list:u.session_list,delete:u.session_delete,fork:u.session_fork,resume:u.session_resume,close:u.session_close,setMode:u.session_set_mode,setConfigOption:u.session_set_config_option,prompt:u.session_prompt,cancel:u.session_cancel},nes:{start:u.nes_start,suggest:u.nes_suggest,accept:u.nes_accept,reject:u.nes_reject,close:u.nes_close},document:{didOpen:u.document_did_open,didChange:u.document_did_change,didClose:u.document_did_close,didSave:u.document_did_save,didFocus:u.document_did_focus}},client:{session:{requestPermission:p.session_request_permission,update:p.session_update},fs:{writeTextFile:p.fs_write_text_file,readTextFile:p.fs_read_text_file},terminal:{create:p.terminal_create,output:p.terminal_output,release:p.terminal_release,waitForExit:p.terminal_wait_for_exit,kill:p.terminal_kill},elicitation:{create:p.elicitation_create,complete:p.elicitation_complete}},protocol:{cancelRequest:ke.cancel_request}},Pt=Symbol("startActiveSession"),Ne=class{cx;currentRequestId;constructor(e,t){this.cx=e,this.currentRequestId=t}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(e,t,c,d){return this.cx.sendRequest(e,t,c,d)}sendNotification(e,t){return this.cx.sendNotification(e,t)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}},ze=class o extends Ne{constructor(e,t){super(e,t)}static create(e,t){return new o(e,t)}request(e,t,c){let d=Zn[e];return this.sendRequest(e,t,d?.mapResponse,c)}notify(e,t){return this.sendNotification(e,t)}},pe=class o extends Ne{constructor(e,t){super(e,t)}static create(e,t){return new o(e,t)}[Pt](e,t){return this.sendRequest(u.session_new,e,c=>this.attachSession(c),t)}buildSession(e){return typeof e=="string"?ye.create(this,{cwd:e,mcpServers:[]}):ye.create(this,e)}attachSession(e){let t=new $n,c=this.connectionContext.signal,d=()=>{t.fail(c.reason??new Error("ACP connection closed"))};c.aborted?d():c.addEventListener("abort",d);let z=$t(this.connectionContext).attach(e,t),f=new ee(()=>{c.removeEventListener("abort",d)});return Jn.create(this,e,t,[z,f])}request(e,t,c){let d=Yn[e];return this.sendRequest(e,t,d?.mapResponse,c)}notify(e,t){return this.sendNotification(e,t)}},je=class{connection;constructor(e){this.connection=e}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(e){this.connection.close(e)}},Bn=class extends je{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.client=ze.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Me(this,this.connectHandlers))}},Wn=class extends je{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.agent=pe.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Me(this,this.connectHandlers))}};function Lt(o,e=[]){return new Bn(o,e)}function Ut(o,e=[]){return new Wn(o,e)}var $n=class{values=[];waiters=[];failed=!1;failure;enqueue(e){if(this.failed)return;let t=this.waiters.shift();t?t.resolve(e):this.values.push({kind:"value",value:e})}reject(e){if(!this.failed){if(this.waiters.length>0){for(let t of this.waiters.splice(0))t.reject(e);return}this.values.push({kind:"error",error:e})}}clearErrors(){this.values=this.values.filter(e=>e.kind==="value")}fail(e){if(!this.failed){this.failed=!0,this.failure=e;for(let t of this.waiters.splice(0))t.reject(e)}}next(){if(this.values.length>0){let e=this.values.shift();return e.kind==="error"?Promise.reject(e.error):Promise.resolve(e.value)}return this.failed?Promise.reject(this.failure):new Promise((e,t)=>{this.waiters.push({resolve:e,reject:t})})}};function Ot(o){return{...o,additionalDirectories:o.additionalDirectories?[...o.additionalDirectories]:void 0,mcpServers:[...o.mcpServers]}}var ye=class o{cx;request;constructor(e,t){this.cx=e,this.request=Ot(t)}static create(e,t){return new o(e,t)}toRequest(){return Ot(this.request)}withAdditionalDirectories(e){return this.request={...this.request,additionalDirectories:[...e]},this}withMcpServer(e){return this.request={...this.request,mcpServers:[...this.request.mcpServers,e]},this}async start(e){return this.cx[Pt](this.toRequest(),e)}async withSession(e){let t=await this.start();try{return await e(t)}finally{t.dispose()}}},Jn=class o{cx;sessionResponse;updates;registrations;constructor(e,t,c,d){this.cx=e,this.sessionResponse=t,this.updates=c,this.registrations=d}static create(e,t,c,d){return new o(e,t,c,d)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(e,t){this.updates.clearErrors();let c=this.cx.request(u.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(e)},t);return c.then(d=>{this.updates.enqueue({kind:"stop",response:d,stopReason:d.stopReason})},d=>{this.updates.reject(d)}),c}nextUpdate(){return this.updates.next()}async readText(){let e="";for(;;){let t=await this.nextUpdate();if(t.kind==="stop")return e;let{update:c}=t;c.sessionUpdate==="agent_message_chunk"&&c.content.type==="text"&&(e+=c.content.text)}}dispose(){for(let e of this.registrations.splice(0))e.dispose();this.updates.fail(new Error("Active session disposed"))}[Symbol.dispose](){this.dispose()}promptBlocks(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e:[e]}};function Ft(o,e){return o?typeof o=="function"?o(e):o.parse(e):e}function x(o,e,t){return{method:o,params:e,mapResponse:t}}function O(o,e){return{method:o,params:e}}function Bt(o,e,t,c){o.onReceiveRequest(e.method,d=>Ft(e.params,d),async(d,z,f)=>{let m=await c(t(d,f,z.signal,z.id));await z.respond(e.mapResponse?e.mapResponse(m):m)})}function Wt(o,e,t,c){o.onReceiveNotification(e.method,d=>Ft(e.params,d),(d,z)=>c(t(d,z,z.signal)))}function Ce(o){let e={};for(let t of Object.values(o))e[t.method]=t;return e}var gr={initialize:x(u.initialize,dn),newSession:x(u.session_new,mn),loadSession:x(u.session_load,gn,w),unstable_forkSession:x(u.session_fork,En),listSessions:x(u.session_list,_n),deleteSession:x(u.session_delete,bn,w),resumeSession:x(u.session_resume,xn),closeSession:x(u.session_close,Sn,w),setSessionMode:x(u.session_set_mode,Tn,w),setSessionConfigOption:x(u.session_set_config_option,wn),authenticate:x(u.authenticate,un,w),unstable_listProviders:x(u.providers_list,zn),unstable_setProvider:x(u.providers_set,pn,w),unstable_disableProvider:x(u.providers_disable,hn,w),logout:x(u.logout,fn,w),prompt:x(u.session_prompt,Rn),unstable_startNes:x(u.nes_start,Nn),unstable_suggestNes:x(u.nes_suggest,jn),unstable_closeNes:x(u.nes_close,yn,w)},_r={cancel:O(u.session_cancel,Mn),unstable_didOpenDocument:O(u.document_did_open,kn),unstable_didChangeDocument:O(u.document_did_change,Dn),unstable_didCloseDocument:O(u.document_did_close,qn),unstable_didSaveDocument:O(u.document_did_save,On),unstable_didFocusDocument:O(u.document_did_focus,In),unstable_acceptNes:O(u.nes_accept,Hn),unstable_rejectNes:O(u.nes_reject,vn)},br={requestPermission:x(p.session_request_permission,He),writeTextFile:x(p.fs_write_text_file,qe,w),readTextFile:x(p.fs_read_text_file,Oe),createTerminal:x(p.terminal_create,ve),terminalOutput:x(p.terminal_output,Ae),releaseTerminal:x(p.terminal_release,Ge,w),waitForTerminalExit:x(p.terminal_wait_for_exit,Pe),killTerminal:x(p.terminal_kill,Le,w),createElicitation:x(p.elicitation_create,Qe)},Er={sessionUpdate:O(p.session_update,be),completeElicitation:O(p.elicitation_complete,ln)},Yn=Ce(gr),xr=Ce(_r),Zn=Ce(br),Sr=Ce(Er);function Tr(o,e,t,c){return{params:o,requestId:c,signal:t,client:e}}function wr(o,e,t){return{params:o,signal:t,client:e}}function Rr(o,e,t,c){return{params:o,requestId:c,signal:t,agent:e}}function Nr(o,e,t){return{params:o,signal:t,agent:e}}var Vn=class{activeSessions=new Map;handleMessage(e){if(e.kind!=="notification"||e.method!==p.session_update)return M.no(e);let t=be.parse(e.params),c={kind:"session_update",notification:t,update:t.update},d=this.activeSessions.get(t.sessionId);if(d&&d.size>0)for(let z of d)z.enqueue(c);return M.no(e)}attach(e,t){let c=this.activeSessions.get(e.sessionId)??new Set;return c.add(t),this.activeSessions.set(e.sessionId,c),new ee(()=>{c.delete(t),c.size===0&&this.activeSessions.delete(e.sessionId)})}},It=new WeakMap;function $t(o){let e=It.get(o);return e||(e=new Vn,It.set(o,e)),e}function Me(o,e){for(let t of e){let c;try{c=t(o)}catch(d){throw o.close(d),d}Promise.resolve(c).catch(d=>{o.close(d)})}}var I=Symbol("appBuilder"),we=Symbol("runAgentConnectHandlers"),Re=Symbol("runClientConnectHandlers"),se={allowBatches:!1};function jr(o){return new Kn(o)}var Kn=class{builder=ne.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name)}[I](){return this.builder}[we](e){Me(e,this.connectHandlers)}connect(e,t={}){return this.connectConnection(e,t).connection}connectWith(e,t){let{rawConnection:c,connection:d}=this.connectConnection(e);return c.runUntil(()=>t(d.client))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,c){if(c)return this.request({method:e,params:t},c);let d=Yn[e];if(!d)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(d,t)}onNotification(e,t,c){if(c)return this.notification({method:e,params:t},c);let d=xr[e];if(!d)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(d,t)}request(e,t){return Bt(this.builder,e,(c,d,z,f)=>Tr(c,ze.create(d,f),z,f),t),this}notification(e,t){return Wt(this.builder,e,(c,d,z)=>wr(c,ze.create(d),z),t),this}connectConnection(e,t={}){if(At(e)){let _=this.openStreamConnection(e);return t.deferConnectHandlers||this[we](_.connection),_}let[c,d]=Gt(),z=e[I]().connect(d,se),f=Ut(z),m=this.openStreamConnection(c);m.rawConnection.closed.then(()=>f.close()),z.closed.then(()=>m.connection.close());try{e[Re](f),this[we](m.connection)}catch(_){throw f.close(_),m.connection.close(_),_}return m}openStreamConnection(e){let t=this.builder.connect(e,se);return{rawConnection:t,connection:Lt(t,this.connectHandlers)}}};function yr(o){return new Qn(o)}var Qn=class{builder=ne.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name),this.builder.withHandler({handleMessage:(t,c)=>$t(c).handleMessage(t),describe:()=>"client-session-update-router"})}[I](){return this.builder}[Re](e){Me(e,this.connectHandlers)}connect(e){return this.connectConnection(e).connection}connectWith(e,t){let{rawConnection:c,connection:d}=this.connectConnection(e);return c.runUntil(()=>t(d.agent))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,c){if(c)return this.request({method:e,params:t},c);let d=Zn[e];if(!d)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(d,t)}onNotification(e,t,c){if(c)return this.notification({method:e,params:t},c);let d=Sr[e];if(!d)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(d,t)}request(e,t){return Bt(this.builder,e,(c,d,z,f)=>Rr(c,pe.create(d,f),z,f),t),this}notification(e,t){return Wt(this.builder,e,(c,d,z)=>Nr(c,pe.create(d),z),t),this}connectConnection(e){if(At(e)){let m=this.openStreamConnection(e);return this[Re](m.connection),m}let[t,c]=Gt(),d=e[I]().connect(c,se),z=Lt(d),f=this.openStreamConnection(t);f.rawConnection.closed.then(()=>z.close()),d.closed.then(()=>f.connection.close());try{e[we](z),this[Re](f.connection)}catch(m){throw z.close(m),f.connection.close(m),m}return f}openStreamConnection(e){let t=this.builder.connect(e,se);return{rawConnection:t,connection:Ut(t,this.connectHandlers)}}},Cr=new Set([u.initialize,u.authenticate,u.providers_list,u.providers_set,u.providers_disable,u.session_new,u.session_load,u.session_set_mode,u.session_set_config_option,u.session_prompt,u.session_list,u.session_delete,u.session_fork,u.session_resume,u.session_close,u.logout,u.nes_start,u.nes_suggest,u.nes_close]),Mr=new Set([u.session_cancel,u.nes_accept,u.nes_reject,u.document_did_open,u.document_did_change,u.document_did_close,u.document_did_save,u.document_did_focus]),kr=new Set([p.session_request_permission,p.fs_write_text_file,p.fs_read_text_file,p.terminal_create,p.terminal_output,p.terminal_release,p.terminal_wait_for_exit,p.terminal_kill,p.elicitation_create]),Dr=new Set([p.session_update,p.elicitation_complete]);function qr(o){let e=jr().onRequest(u.initialize,t=>o.initialize(t.params)).onRequest(u.session_new,t=>o.newSession(t.params)).onRequest(u.authenticate,async t=>await o.authenticate(t.params)??{}).onRequest(u.session_prompt,t=>o.prompt(t.params)).onNotification(u.session_cancel,t=>o.cancel(t.params));return o.loadSession&&e.onRequest(u.session_load,t=>o.loadSession(t.params)),o.listSessions&&e.onRequest(u.session_list,t=>o.listSessions(t.params)),o.deleteSession&&e.onRequest(u.session_delete,async t=>await o.deleteSession(t.params)??{}),o.unstable_forkSession&&e.onRequest(u.session_fork,t=>o.unstable_forkSession(t.params)),o.resumeSession&&e.onRequest(u.session_resume,t=>o.resumeSession(t.params)),o.closeSession&&e.onRequest(u.session_close,async t=>await o.closeSession(t.params)??{}),o.setSessionMode&&e.onRequest(u.session_set_mode,async t=>await o.setSessionMode(t.params)??{}),o.setSessionConfigOption&&e.onRequest(u.session_set_config_option,t=>o.setSessionConfigOption(t.params)),o.unstable_listProviders&&e.onRequest(u.providers_list,t=>o.unstable_listProviders(t.params)),o.unstable_setProvider&&e.onRequest(u.providers_set,async t=>await o.unstable_setProvider(t.params)??{}),o.unstable_disableProvider&&e.onRequest(u.providers_disable,async t=>await o.unstable_disableProvider(t.params)??{}),o.logout&&e.onRequest(u.logout,async t=>await o.logout(t.params)??{}),o.unstable_startNes&&e.onRequest(u.nes_start,t=>o.unstable_startNes(t.params)),o.unstable_suggestNes&&e.onRequest(u.nes_suggest,t=>o.unstable_suggestNes(t.params)),o.unstable_closeNes&&e.onRequest(u.nes_close,async t=>await o.unstable_closeNes(t.params)??{}),o.unstable_didOpenDocument&&e.onNotification(u.document_did_open,t=>o.unstable_didOpenDocument(t.params)),o.unstable_didChangeDocument&&e.onNotification(u.document_did_change,t=>o.unstable_didChangeDocument(t.params)),o.unstable_didCloseDocument&&e.onNotification(u.document_did_close,t=>o.unstable_didCloseDocument(t.params)),o.unstable_didSaveDocument&&e.onNotification(u.document_did_save,t=>o.unstable_didSaveDocument(t.params)),o.unstable_didFocusDocument&&e.onNotification(u.document_did_focus,t=>o.unstable_didFocusDocument(t.params)),o.unstable_acceptNes&&e.onNotification(u.nes_accept,t=>o.unstable_acceptNes(t.params)),o.unstable_rejectNes&&e.onNotification(u.nes_reject,t=>o.unstable_rejectNes(t.params)),o.extMethod&&e[I]().withHandler({handleMessage:async t=>t.kind!=="request"||Cr.has(t.method)?M.no(t):(await t.responder.respond(await o.extMethod(t.method,t.params)),M.yes()),describe:()=>"legacy-agent-extension-request"}),o.extNotification&&e[I]().withHandler({handleMessage:async t=>t.kind!=="notification"||Mr.has(t.method)?M.no(t):(await o.extNotification(t.method,t.params),M.yes()),describe:()=>"legacy-agent-extension-notification"}),e}function Or(o){let e=yr().onRequest(p.session_request_permission,t=>o.requestPermission(t.params)).onNotification(p.session_update,t=>o.sessionUpdate(t.params)).onRequest(p.fs_write_text_file,async t=>await o.writeTextFile?.(t.params)??{}).onRequest(p.fs_read_text_file,async t=>await o.readTextFile?.(t.params)).onRequest(p.terminal_create,async t=>await o.createTerminal?.(t.params)).onRequest(p.terminal_output,async t=>await o.terminalOutput?.(t.params)).onRequest(p.terminal_release,async t=>await o.releaseTerminal?.(t.params)??{}).onRequest(p.terminal_wait_for_exit,async t=>await o.waitForTerminalExit?.(t.params)).onRequest(p.terminal_kill,async t=>await o.killTerminal?.(t.params)??{});return o.createElicitation&&e.onRequest(p.elicitation_create,t=>o.createElicitation(t.params)),o.completeElicitation&&e.onNotification(p.elicitation_complete,t=>o.completeElicitation(t.params)),o.extMethod&&e[I]().withHandler({handleMessage:async t=>t.kind!=="request"||kr.has(t.method)?M.no(t):(await t.responder.respond(await o.extMethod(t.method,t.params)),M.yes()),describe:()=>"legacy-client-extension-request"}),o.extNotification&&e[I]().withHandler({handleMessage:async t=>t.kind!=="notification"||Dr.has(t.method)?M.no(t):(await o.extNotification(t.method,t.params),M.yes()),describe:()=>"legacy-client-extension-notification"}),e}var Ht=class{connection;constructor(e,t){this.connection=qr(e(this))[I]().connect(t,se)}sessionUpdate(e){return this.connection.sendNotification(p.session_update,e)}requestPermission(e){return this.connection.sendRequest(p.session_request_permission,e)}readTextFile(e){return this.connection.sendRequest(p.fs_read_text_file,e)}writeTextFile(e){return this.connection.sendRequest(p.fs_write_text_file,e,w)}createTerminal(e){return this.connection.sendRequest(p.terminal_create,e,t=>Xn.create(t.terminalId,e.sessionId,this.connection))}createElicitation(e){return this.connection.sendRequest(p.elicitation_create,e)}completeElicitation(e){return this.connection.sendNotification(p.elicitation_complete,e)}request(e,t,c){let d=Zn[e];return this.connection.sendRequest(e,t,d?.mapResponse,c)}notify(e,t){return this.connection.sendNotification(e,t)}extMethod(e,t){return this.request(e,t)}extNotification(e,t){return this.notify(e,t)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},Xn=class o{id;sessionId;connection;constructor(e,t,c){this.id=e,this.sessionId=t,this.connection=c}static create(e,t,c){return new o(e,t,c)}currentOutput(){return this.connection.sendRequest(p.terminal_output,{sessionId:this.sessionId,terminalId:this.id})}waitForExit(){return this.connection.sendRequest(p.terminal_wait_for_exit,{sessionId:this.sessionId,terminalId:this.id})}kill(){return this.connection.sendRequest(p.terminal_kill,{sessionId:this.sessionId,terminalId:this.id},w)}release(){return this.connection.sendRequest(p.terminal_release,{sessionId:this.sessionId,terminalId:this.id},w)}async[Symbol.asyncDispose](){await this.release()}},vt=class{connection;constructor(e,t){this.connection=Or(e(this))[I]().connect(t,se)}initialize(e){return this.connection.sendRequest(u.initialize,e)}newSession(e){return this.connection.sendRequest(u.session_new,e)}loadSession(e){return this.connection.sendRequest(u.session_load,e,w)}unstable_forkSession(e){return this.connection.sendRequest(u.session_fork,e)}listSessions(e){return this.connection.sendRequest(u.session_list,e)}deleteSession(e){return this.connection.sendRequest(u.session_delete,e,w)}resumeSession(e){return this.connection.sendRequest(u.session_resume,e)}closeSession(e){return this.connection.sendRequest(u.session_close,e,w)}setSessionMode(e){return this.connection.sendRequest(u.session_set_mode,e,w)}setSessionConfigOption(e){return this.connection.sendRequest(u.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(u.authenticate,e,w)}unstable_listProviders(e){return this.connection.sendRequest(u.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(u.providers_set,e,w)}unstable_disableProvider(e){return this.connection.sendRequest(u.providers_disable,e,w)}logout(e){return this.connection.sendRequest(u.logout,e,w)}prompt(e){return this.connection.sendRequest(u.session_prompt,e)}cancel(e){return this.connection.sendNotification(u.session_cancel,e)}unstable_startNes(e){return this.connection.sendRequest(u.nes_start,e)}unstable_suggestNes(e){return this.connection.sendRequest(u.nes_suggest,e)}unstable_closeNes(e){return this.connection.sendRequest(u.nes_close,e,w)}unstable_didOpenDocument(e){return this.connection.sendNotification(u.document_did_open,e)}unstable_didChangeDocument(e){return this.connection.sendNotification(u.document_did_change,e)}unstable_didCloseDocument(e){return this.connection.sendNotification(u.document_did_close,e)}unstable_didSaveDocument(e){return this.connection.sendNotification(u.document_did_save,e)}unstable_didFocusDocument(e){return this.connection.sendNotification(u.document_did_focus,e)}unstable_acceptNes(e){return this.connection.sendNotification(u.nes_accept,e)}unstable_rejectNes(e){return this.connection.sendNotification(u.nes_reject,e)}request(e,t,c){let d=Yn[e];return this.connection.sendRequest(e,t,d?.mapResponse,c)}notify(e,t){return this.connection.sendNotification(e,t)}extMethod(e,t){return this.request(e,t)}extNotification(e,t){return this.notify(e,t)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}};export{Vt as a,N as b,Ua as c,Ht as d,vt as e};
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{b as _}from"./chunk-GZPNIYVZ.js";_();var p=new Error("timeout while waiting for mutex to become available"),x=new Error("mutex already locked"),E=new Error("request for lock canceled"),q=function(s,e,t,i){function o(n){return n instanceof t?n:new t(function(u){u(n)})}return new(t||(t=Promise))(function(n,u){function a(r){try{c(i.next(r))}catch(l){u(l)}}function h(r){try{c(i.throw(r))}catch(l){u(l)}}function c(r){r.done?n(r.value):o(r.value).then(a,h)}c((i=i.apply(s,e||[])).next())})},f=class{constructor(e,t=E){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},u=m(this._queue,a=>t<=a.priority);u===-1&&e<=this._value?this._dispatchItem(n):this._queue.splice(u+1,0,n)})}runExclusive(e){return q(this,arguments,void 0,function*(t,i=1,o=0){let[n,u]=yield this.acquire(i,o);try{return yield t(n)}finally{u()}})}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]=[]),k(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 k(s,e){let t=m(s,i=>e.priority<=i.priority);s.splice(t+1,0,e)}function m(s,e){for(let t=s.length-1;t>=0;t--)if(e(s[t]))return t;return-1}var y=function(s,e,t,i){function o(n){return n instanceof t?n:new t(function(u){u(n)})}return new(t||(t=Promise))(function(n,u){function a(r){try{c(i.next(r))}catch(l){u(l)}}function h(r){try{c(i.throw(r))}catch(l){u(l)}}function c(r){r.done?n(r.value):o(r.value).then(a,h)}c((i=i.apply(s,e||[])).next())})},w=class{constructor(e){this._semaphore=new f(1,e)}acquire(){return y(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()}},v=function(s,e,t,i){function o(n){return n instanceof t?n:new t(function(u){u(n)})}return new(t||(t=Promise))(function(n,u){function a(r){try{c(i.next(r))}catch(l){u(l)}}function h(r){try{c(i.throw(r))}catch(l){u(l)}}function c(r){r.done?n(r.value):o(r.value).then(a,h)}c((i=i.apply(s,e||[])).next())})};function L(s,e,t=p){return{acquire:(i,o)=>{let n;if(d(s)?n=i:(n=void 0,o=i),n!==void 0&&n<=0)throw new Error(`invalid weight ${n}: must be positive`);return new Promise((u,a)=>v(this,void 0,void 0,function*(){let h=!1,c=setTimeout(()=>{h=!0,a(t)},e);try{let r=yield d(s)?s.acquire(n,o):s.acquire(o);h?(Array.isArray(r)?r[1]:r)():(clearTimeout(c),u(r))}catch(r){h||(clearTimeout(c),a(r))}}))},runExclusive(i,o,n){return v(this,void 0,void 0,function*(){let u=()=>{};try{let a=yield this.acquire(o,n);return Array.isArray(a)?(u=a[1],yield i(a[0])):(u=a,yield i())}finally{u()}})},release(i){s.release(i)},cancel(){return s.cancel()},waitForUnlock:(i,o)=>{let n;if(d(s)?n=i:(n=void 0,o=i),n!==void 0&&n<=0)throw new Error(`invalid weight ${n}: must be positive`);return new Promise((u,a)=>{let h=setTimeout(()=>a(t),e);(d(s)?s.waitForUnlock(n,o):s.waitForUnlock(o)).then(()=>{clearTimeout(h),u()})})},isLocked:()=>s.isLocked(),getValue:()=>s.getValue(),setValue:i=>s.setValue(i)}}function d(s){return s.getValue!==void 0}export{p as a,w as b,L as c};
@@ -1,9 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{b as d}from"./chunk-GZPNIYVZ.js";import{a as g,d as E}from"./chunk-OWGSC52X.js";var k=E((dr,Ge)=>{"use strict";d();var We=["nodebuffer","arraybuffer","fragments"],qe=typeof Blob<"u";qe&&We.push("blob");Ge.exports={BINARY_TYPES:We,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:qe,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var K=E((mr,re)=>{"use strict";d();var{EMPTY_BUFFER:Vt}=k(),ge=Buffer[Symbol.species];function zt(t,e){if(t.length===0)return Vt;if(t.length===1)return t[0];let s=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let n=t[i];s.set(n,r),r+=n.length}return r<e?new ge(s.buffer,s.byteOffset,r):s}function $e(t,e,s,r,i){for(let n=0;n<i;n++)s[r+n]=t[n]^e[n&3]}function je(t,e){for(let s=0;s<t.length;s++)t[s]^=e[s&3]}function Ht(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ye(t){if(ye.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new ge(t):ArrayBuffer.isView(t)?e=new ge(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ye.readOnly=!1),e}re.exports={concat:zt,mask:$e,toArrayBuffer:Ht,toBuffer:ye,unmask:je};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=g("bufferutil");re.exports.mask=function(e,s,r,i,n){n<48?$e(e,s,r,i,n):t.mask(e,s,r,i,n)},re.exports.unmask=function(e,s){e.length<32?je(e,s):t.unmask(e,s)}}catch{}});var He=E((gr,ze)=>{"use strict";d();var Ve=Symbol("kDone"),xe=Symbol("kRun"),Se=class{constructor(e){this[Ve]=()=>{this.pending--,this[xe]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[xe]()}[xe](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ve])}}};ze.exports=Se});var Z=E((xr,Ze)=>{"use strict";d();var X=g("zlib"),Ye=K(),Yt=He(),{kStatusCode:Ke}=k(),Kt=Buffer[Symbol.species],Xt=Buffer.from([0,0,255,255]),ne=Symbol("permessage-deflate"),C=Symbol("total-length"),W=Symbol("callback"),P=Symbol("buffers"),q=Symbol("error"),ie,Ee=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!ie){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ie=new Yt(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[W];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let s=this._options,r=e.find(i=>!(s.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(s.serverMaxWindowBits===!1||typeof s.serverMaxWindowBits=="number"&&s.serverMaxWindowBits>i.server_max_window_bits)||typeof s.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return s.serverNoContextTakeover&&(r.server_no_context_takeover=!0),s.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof s.serverMaxWindowBits=="number"&&(r.server_max_window_bits=s.serverMaxWindowBits),typeof s.clientMaxWindowBits=="number"?r.client_max_window_bits=s.clientMaxWindowBits:(r.client_max_window_bits===!0||s.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let s=e[0];if(this._options.clientNoContextTakeover===!1&&s.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!s.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(s.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&s.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return s}normalizeParams(e){return e.forEach(s=>{Object.keys(s).forEach(r=>{let i=s[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);s[r]=i})}),e}decompress(e,s,r){ie.add(i=>{this._decompress(e,s,(n,o)=>{i(),r(n,o)})})}compress(e,s,r){ie.add(i=>{this._compress(e,s,(n,o)=>{i(),r(n,o)})})}_decompress(e,s,r){let i=this._isServer?"client":"server";if(!this._inflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?X.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=X.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[ne]=this,this._inflate[C]=0,this._inflate[P]=[],this._inflate.on("error",Qt),this._inflate.on("data",Xe)}this._inflate[W]=r,this._inflate.write(e),s&&this._inflate.write(Xt),this._inflate.flush(()=>{let n=this._inflate[q];if(n){this._inflate.close(),this._inflate=null,r(n);return}let o=Ye.concat(this._inflate[P],this._inflate[C]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[C]=0,this._inflate[P]=[],s&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,s,r){let i=this._isServer?"server":"client";if(!this._deflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?X.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=X.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[C]=0,this._deflate[P]=[],this._deflate.on("data",Zt)}this._deflate[W]=r,this._deflate.write(e),this._deflate.flush(X.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=Ye.concat(this._deflate[P],this._deflate[C]);s&&(n=new Kt(n.buffer,n.byteOffset,n.length-4)),this._deflate[W]=null,this._deflate[C]=0,this._deflate[P]=[],s&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,n)})}};Ze.exports=Ee;function Zt(t){this[P].push(t),this[C]+=t.length}function Xe(t){if(this[C]+=t.length,this[ne]._maxPayload<1||this[C]<=this[ne]._maxPayload){this[P].push(t);return}this[q]=new RangeError("Max payload size exceeded"),this[q].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[q][Ke]=1009,this.removeListener("data",Xe),this.reset()}function Qt(t){if(this[ne]._inflate=null,this[q]){this[W](this[q]);return}t[Ke]=1007,this[W](t)}});var G=E((Er,oe)=>{"use strict";d();var{isUtf8:Qe}=g("buffer"),{hasBlob:Jt}=k(),es=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function ts(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function ve(t){let e=t.length,s=0;for(;s<e;)if((t[s]&128)===0)s++;else if((t[s]&224)===192){if(s+1===e||(t[s+1]&192)!==128||(t[s]&254)===192)return!1;s+=2}else if((t[s]&240)===224){if(s+2>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||t[s]===224&&(t[s+1]&224)===128||t[s]===237&&(t[s+1]&224)===160)return!1;s+=3}else if((t[s]&248)===240){if(s+3>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||(t[s+3]&192)!==128||t[s]===240&&(t[s+1]&240)===128||t[s]===244&&t[s+1]>143||t[s]>244)return!1;s+=4}else return!1;return!0}function ss(t){return Jt&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}oe.exports={isBlob:ss,isValidStatusCode:ts,isValidUTF8:ve,tokenChars:es};if(Qe)oe.exports.isValidUTF8=function(t){return t.length<24?ve(t):Qe(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=g("utf-8-validate");oe.exports.isValidUTF8=function(e){return e.length<32?ve(e):t(e)}}catch{}});var ot=E((br,nt)=>{"use strict";d();var{Writable:rs}=g("stream"),Je=Z(),{BINARY_TYPES:is,EMPTY_BUFFER:et,kStatusCode:ns,kWebSocket:os}=k(),{concat:be,toArrayBuffer:as,unmask:fs}=K(),{isValidStatusCode:ls,isValidUTF8:tt}=G(),ae=Buffer[Symbol.species],b=0,st=1,rt=2,it=3,we=4,Oe=5,fe=6,Te=class extends rs{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||is[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[os]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=b}_write(e,s,r){if(this._opcode===8&&this._state==b)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new ae(r.buffer,r.byteOffset+e,r.length-e),new ae(r.buffer,r.byteOffset,e)}let s=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=s.length-e;e>=r.length?s.set(this._buffers.shift(),i):(s.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new ae(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return s}startLoop(e){this._loop=!0;do switch(this._state){case b:this.getInfo(e);break;case st:this.getPayloadLength16(e);break;case rt:this.getPayloadLength64(e);break;case it:this.getMask();break;case we:this.getData(e);break;case Oe:case fe:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let s=this.consume(2);if((s[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(s[0]&64)===64;if(r&&!this._extensions[Je.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(s[0]&128)===128,this._opcode=s[0]&15,this._payloadLength=s[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(s[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=st:this._payloadLength===127?this._state=rt:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let s=this.consume(8),r=s.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+s.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(s);return}this._masked?this._state=it:this._state=we}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=we}getData(e){let s=et;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}s=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&fs(s,this._mask)}if(this._opcode>7){this.controlMessage(s,e);return}if(this._compressed){this._state=Oe,this.decompress(s,e);return}if(s.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}this._messageLength=this._totalPayloadLength,this._fragments.push(s)}this.dataMessage(e)}decompress(e,s){this._extensions[Je.extensionName].decompress(e,this._fin,(i,n)=>{if(i)return s(i);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");s(o);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");s(o);return}this._fragments.push(n)}this.dataMessage(s),this._state===b&&this.startLoop(s)})}dataMessage(e){if(!this._fin){this._state=b;return}let s=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=be(r,s):this._binaryType==="arraybuffer"?i=as(be(r,s)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=b):(this._state=fe,setImmediate(()=>{this.emit("message",i,!0),this._state=b,this.startLoop(e)}))}else{let i=be(r,s);if(!this._skipUTF8Validation&&!tt(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(n);return}this._state===Oe||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=b):(this._state=fe,setImmediate(()=>{this.emit("message",i,!1),this._state=b,this.startLoop(e)}))}}controlMessage(e,s){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,et),this.end();else{let r=e.readUInt16BE(0);if(!ls(r)){let n=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");s(n);return}let i=new ae(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!tt(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");s(n);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=b;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=b):(this._state=fe,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=b,this.startLoop(s)}))}createError(e,s,r,i,n){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${s}`:s);return Error.captureStackTrace(o,this.createError),o.code=n,o[ns]=i,o}};nt.exports=Te});var ht=E((Tr,lt)=>{"use strict";d();var{Duplex:Or}=g("stream"),{randomFillSync:hs}=g("crypto"),{types:{isUint8Array:cs}}=g("util"),at=Z(),{EMPTY_BUFFER:us,kWebSocket:ds,NOOP:_s}=k(),{isBlob:$,isValidStatusCode:ms}=G(),{mask:ft,toBuffer:R}=K(),w=Symbol("kByteLength"),ps=Buffer.alloc(4),le=8*1024,U,j=le,O=0,gs=1,ys=2,ke=class t{constructor(e,s,r){this._extensions=s||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=O,this.onerror=_s,this[ds]=void 0}static frame(e,s){let r,i=!1,n=2,o=!1;s.mask&&(r=s.maskBuffer||ps,s.generateMask?s.generateMask(r):(j===le&&(U===void 0&&(U=Buffer.alloc(le)),hs(U,0,le),j=0),r[0]=U[j++],r[1]=U[j++],r[2]=U[j++],r[3]=U[j++]),o=(r[0]|r[1]|r[2]|r[3])===0,n=6);let f;typeof e=="string"?(!s.mask||o)&&s[w]!==void 0?f=s[w]:(e=Buffer.from(e),f=e.length):(f=e.length,i=s.mask&&s.readOnly&&!o);let l=f;f>=65536?(n+=8,l=127):f>125&&(n+=2,l=126);let a=Buffer.allocUnsafe(i?f+n:n);return a[0]=s.fin?s.opcode|128:s.opcode,s.rsv1&&(a[0]|=64),a[1]=l,l===126?a.writeUInt16BE(f,2):l===127&&(a[2]=a[3]=0,a.writeUIntBE(f,4,6)),s.mask?(a[1]|=128,a[n-4]=r[0],a[n-3]=r[1],a[n-2]=r[2],a[n-1]=r[3],o?[a,e]:i?(ft(e,r,a,n,f),[a]):(ft(e,r,e,0,f),[a,e])):[a,e]}close(e,s,r,i){let n;if(e===void 0)n=us;else{if(typeof e!="number"||!ms(e))throw new TypeError("First argument must be a valid error code number");if(s===void 0||!s.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0);else{let f=Buffer.byteLength(s);if(f>123)throw new RangeError("The message must not be greater than 123 bytes");if(n=Buffer.allocUnsafe(2+f),n.writeUInt16BE(e,0),typeof s=="string")n.write(s,2);else if(cs(s))n.set(s,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[w]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==O?this.enqueue([this.dispatch,n,!1,o,i]):this.sendFrame(t.frame(n,o),i)}ping(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):$(e)?(i=e.size,n=!1):(e=R(e),i=e.length,n=R.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[w]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};$(e)?this._state!==O?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==O?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):$(e)?(i=e.size,n=!1):(e=R(e),i=e.length,n=R.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[w]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};$(e)?this._state!==O?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==O?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,s,r){let i=this._extensions[at.extensionName],n=s.binary?2:1,o=s.compress,f,l;typeof e=="string"?(f=Buffer.byteLength(e),l=!1):$(e)?(f=e.size,l=!1):(e=R(e),f=e.length,l=R.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=f>=i._threshold),this._compress=o):(o=!1,n=0),s.fin&&(this._firstFragment=!0);let a={[w]:f,fin:s.fin,generateMask:this._generateMask,mask:s.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:l,rsv1:o};$(e)?this._state!==O?this.enqueue([this.getBlobData,e,this._compress,a,r]):this.getBlobData(e,this._compress,a,r):this._state!==O?this.enqueue([this.dispatch,e,this._compress,a,r]):this.dispatch(e,this._compress,a,r)}getBlobData(e,s,r,i){this._bufferedBytes+=r[w],this._state=ys,e.arrayBuffer().then(n=>{if(this._socket.destroyed){let f=new Error("The socket was closed while the blob was being read");process.nextTick(Ce,this,f,i);return}this._bufferedBytes-=r[w];let o=R(n);s?this.dispatch(o,s,r,i):(this._state=O,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(n=>{process.nextTick(xs,this,n,i)})}dispatch(e,s,r,i){if(!s){this.sendFrame(t.frame(e,r),i);return}let n=this._extensions[at.extensionName];this._bufferedBytes+=r[w],this._state=gs,n.compress(e,r.fin,(o,f)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Ce(this,l,i);return}this._bufferedBytes-=r[w],this._state=O,r.readOnly=!1,this.sendFrame(t.frame(f,r),i),this.dequeue()})}dequeue(){for(;this._state===O&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][w],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][w],this._queue.push(e)}sendFrame(e,s){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],s),this._socket.uncork()):this._socket.write(e[0],s)}};lt.exports=ke;function Ce(t,e,s){typeof s=="function"&&s(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],n=i[i.length-1];typeof n=="function"&&n(e)}}function xs(t,e,s){Ce(t,e,s),t.onerror(e)}});var Le=E((Cr,ct)=>{"use strict";d();var{tokenChars:Q}=G();function T(t,e,s){t[e]===void 0?t[e]=[s]:t[e].push(s)}function Ss(t){let e=Object.create(null),s=Object.create(null),r=!1,i=!1,n=!1,o,f,l=-1,a=-1,h=-1,c=0;for(;c<t.length;c++)if(a=t.charCodeAt(c),o===void 0)if(h===-1&&Q[a]===1)l===-1&&(l=c);else if(c!==0&&(a===32||a===9))h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let y=t.slice(l,h);a===44?(T(e,y,s),s=Object.create(null)):o=y,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${c}`);else if(f===void 0)if(h===-1&&Q[a]===1)l===-1&&(l=c);else if(a===32||a===9)h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c),T(s,t.slice(l,h),!0),a===44&&(T(e,o,s),s=Object.create(null),o=void 0),l=h=-1}else if(a===61&&l!==-1&&h===-1)f=t.slice(l,c),l=h=-1;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(i){if(Q[a]!==1)throw new SyntaxError(`Unexpected character at index ${c}`);l===-1?l=c:r||(r=!0),i=!1}else if(n)if(Q[a]===1)l===-1&&(l=c);else if(a===34&&l!==-1)n=!1,h=c;else if(a===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(a===34&&t.charCodeAt(c-1)===61)n=!0;else if(h===-1&&Q[a]===1)l===-1&&(l=c);else if(l!==-1&&(a===32||a===9))h===-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let y=t.slice(l,h);r&&(y=y.replace(/\\/g,""),r=!1),T(s,f,y),a===44&&(T(e,o,s),s=Object.create(null),o=void 0),f=void 0,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${c}`);if(l===-1||n||a===32||a===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=c);let m=t.slice(l,h);return o===void 0?T(e,m,s):(f===void 0?T(s,m,!0):r?T(s,f,m.replace(/\\/g,"")):T(s,f,m),T(e,o,s)),e}function Es(t){return Object.keys(t).map(e=>{let s=t[e];return Array.isArray(s)||(s=[s]),s.map(r=>[e].concat(Object.keys(r).map(i=>{let n=r[i];return Array.isArray(n)||(n=[n]),n.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ct.exports={format:Es,parse:Ss}});var St=E((Nr,xt)=>{"use strict";d();var{kForOnEventAttribute:J,kListener:Ne}=k(),ut=Symbol("kCode"),dt=Symbol("kData"),_t=Symbol("kError"),mt=Symbol("kMessage"),pt=Symbol("kReason"),V=Symbol("kTarget"),gt=Symbol("kType"),yt=Symbol("kWasClean"),L=class{constructor(e){this[V]=null,this[gt]=e}get target(){return this[V]}get type(){return this[gt]}};Object.defineProperty(L.prototype,"target",{enumerable:!0});Object.defineProperty(L.prototype,"type",{enumerable:!0});var I=class extends L{constructor(e,s={}){super(e),this[ut]=s.code===void 0?0:s.code,this[pt]=s.reason===void 0?"":s.reason,this[yt]=s.wasClean===void 0?!1:s.wasClean}get code(){return this[ut]}get reason(){return this[pt]}get wasClean(){return this[yt]}};Object.defineProperty(I.prototype,"code",{enumerable:!0});Object.defineProperty(I.prototype,"reason",{enumerable:!0});Object.defineProperty(I.prototype,"wasClean",{enumerable:!0});var z=class extends L{constructor(e,s={}){super(e),this[_t]=s.error===void 0?null:s.error,this[mt]=s.message===void 0?"":s.message}get error(){return this[_t]}get message(){return this[mt]}};Object.defineProperty(z.prototype,"error",{enumerable:!0});Object.defineProperty(z.prototype,"message",{enumerable:!0});var ee=class extends L{constructor(e,s={}){super(e),this[dt]=s.data===void 0?null:s.data}get data(){return this[dt]}};Object.defineProperty(ee.prototype,"data",{enumerable:!0});var vs={addEventListener(t,e,s={}){for(let i of this.listeners(t))if(!s[J]&&i[Ne]===e&&!i[J])return;let r;if(t==="message")r=function(n,o){let f=new ee("message",{data:o?n:n.toString()});f[V]=this,he(e,this,f)};else if(t==="close")r=function(n,o){let f=new I("close",{code:n,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});f[V]=this,he(e,this,f)};else if(t==="error")r=function(n){let o=new z("error",{error:n,message:n.message});o[V]=this,he(e,this,o)};else if(t==="open")r=function(){let n=new L("open");n[V]=this,he(e,this,n)};else return;r[J]=!!s[J],r[Ne]=e,s.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let s of this.listeners(t))if(s[Ne]===e&&!s[J]){this.removeListener(t,s);break}}};xt.exports={CloseEvent:I,ErrorEvent:z,Event:L,EventTarget:vs,MessageEvent:ee};function he(t,e,s){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,s):t.call(e,s)}});var Ie=E((Ur,Bt)=>{"use strict";d();var bs=g("events"),ws=g("https"),Os=g("http"),bt=g("net"),Ts=g("tls"),{randomBytes:ks,createHash:Cs}=g("crypto"),{Duplex:Br,Readable:Rr}=g("stream"),{URL:Pe}=g("url"),B=Z(),Ls=ot(),Ns=ht(),{isBlob:Ps}=G(),{BINARY_TYPES:Et,CLOSE_TIMEOUT:Bs,EMPTY_BUFFER:ce,GUID:Rs,kForOnEventAttribute:Be,kListener:Us,kStatusCode:Is,kWebSocket:x,NOOP:wt}=k(),{EventTarget:{addEventListener:Ds,removeEventListener:Fs}}=St(),{format:Ms,parse:As}=Le(),{toBuffer:Ws}=K(),Ot=Symbol("kAborted"),Re=[8,13],N=["CONNECTING","OPEN","CLOSING","CLOSED"],qs=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_=class t extends bs{constructor(e,s,r){super(),this._binaryType=Et[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ce,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,s===void 0?s=[]:Array.isArray(s)||(typeof s=="object"&&s!==null?(r=s,s=[]):s=[s]),Tt(this,e,s,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Et.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,s,r){let i=new Ls({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),n=new Ns(e,this._extensions,r.generateMask);this._receiver=i,this._sender=n,this._socket=e,i[x]=this,n[x]=this,e[x]=this,i.on("conclude",js),i.on("drain",Vs),i.on("error",zs),i.on("message",Hs),i.on("ping",Ys),i.on("pong",Ks),n.onerror=Xs,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),s.length>0&&e.unshift(s),e.on("close",Lt),e.on("data",de),e.on("end",Nt),e.on("error",Pt),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[B.extensionName]&&this._extensions[B.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,s){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){v(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,s,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ct(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ue(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.ping(e||ce,s,r)}pong(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ue(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.pong(e||ce,s,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof s=="function"&&(r=s,s={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ue(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...s};this._extensions[B.extensionName]||(i.compress=!1),this._sender.send(e||ce,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){v(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(_,"CONNECTING",{enumerable:!0,value:N.indexOf("CONNECTING")});Object.defineProperty(_.prototype,"CONNECTING",{enumerable:!0,value:N.indexOf("CONNECTING")});Object.defineProperty(_,"OPEN",{enumerable:!0,value:N.indexOf("OPEN")});Object.defineProperty(_.prototype,"OPEN",{enumerable:!0,value:N.indexOf("OPEN")});Object.defineProperty(_,"CLOSING",{enumerable:!0,value:N.indexOf("CLOSING")});Object.defineProperty(_.prototype,"CLOSING",{enumerable:!0,value:N.indexOf("CLOSING")});Object.defineProperty(_,"CLOSED",{enumerable:!0,value:N.indexOf("CLOSED")});Object.defineProperty(_.prototype,"CLOSED",{enumerable:!0,value:N.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(_.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(_.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Be])return e[Us];return null},set(e){for(let s of this.listeners(t))if(s[Be]){this.removeListener(t,s);break}typeof e=="function"&&this.addEventListener(t,e,{[Be]:!0})}})});_.prototype.addEventListener=Ds;_.prototype.removeEventListener=Fs;Bt.exports=_;function Tt(t,e,s,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Bs,protocolVersion:Re[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!Re.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Re.join(", ")})`);let n;if(e instanceof Pe)n=e;else try{n=new Pe(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),t._url=n.href;let o=n.protocol==="wss:",f=n.protocol==="ws+unix:",l;if(n.protocol!=="ws:"&&!o&&!f?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:f&&!n.pathname?l="The URL's pathname is empty":n.hash&&(l="The URL contains a fragment identifier"),l){let u=new SyntaxError(l);if(t._redirects===0)throw u;ue(t,u);return}let a=o?443:80,h=ks(16).toString("base64"),c=o?ws.request:Os.request,m=new Set,y;if(i.createConnection=i.createConnection||(o?$s:Gs),i.defaultPort=i.defaultPort||a,i.port=n.port||a,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(y=new B({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=Ms({[B.extensionName]:y.offer()})),s.length){for(let u of s){if(typeof u!="string"||!qs.test(u)||m.has(u))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(u)}i.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(n.username||n.password)&&(i.auth=`${n.username}:${n.password}`),f){let u=i.path.split(":");i.socketPath=u[0],i.path=u[1]}let p;if(i.followRedirects){if(t._redirects===0){t._originalIpc=f,t._originalSecure=o,t._originalHostOrSocketPath=f?i.socketPath:n.host;let u=r&&r.headers;if(r={...r,headers:{}},u)for(let[S,M]of Object.entries(u))r.headers[S.toLowerCase()]=M}else if(t.listenerCount("redirect")===0){let u=f?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:n.host===t._originalHostOrSocketPath;(!u||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,u||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=t._req=c(i),t._redirects&&t.emit("redirect",t.url,p)}else p=t._req=c(i);i.timeout&&p.on("timeout",()=>{v(t,p,"Opening handshake has timed out")}),p.on("error",u=>{p===null||p[Ot]||(p=t._req=null,ue(t,u))}),p.on("response",u=>{let S=u.headers.location,M=u.statusCode;if(S&&i.followRedirects&&M>=300&&M<400){if(++t._redirects>i.maxRedirects){v(t,p,"Maximum redirects exceeded");return}p.abort();let H;try{H=new Pe(S,e)}catch{let A=new SyntaxError(`Invalid URL: ${S}`);ue(t,A);return}Tt(t,H,s,r)}else t.emit("unexpected-response",p,u)||v(t,p,`Unexpected server response: ${u.statusCode}`)}),p.on("upgrade",(u,S,M)=>{if(t.emit("upgrade",u),t.readyState!==_.CONNECTING)return;p=t._req=null;let H=u.headers.upgrade;if(H===void 0||H.toLowerCase()!=="websocket"){v(t,S,"Invalid Upgrade header");return}let Fe=Cs("sha1").update(h+Rs).digest("base64");if(u.headers["sec-websocket-accept"]!==Fe){v(t,S,"Invalid Sec-WebSocket-Accept header");return}let A=u.headers["sec-websocket-protocol"],Y;if(A!==void 0?m.size?m.has(A)||(Y="Server sent an invalid subprotocol"):Y="Server sent a subprotocol but none was requested":m.size&&(Y="Server sent no subprotocol"),Y){v(t,S,Y);return}A&&(t._protocol=A);let Me=u.headers["sec-websocket-extensions"];if(Me!==void 0){if(!y){v(t,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let me;try{me=As(Me)}catch{v(t,S,"Invalid Sec-WebSocket-Extensions header");return}let Ae=Object.keys(me);if(Ae.length!==1||Ae[0]!==B.extensionName){v(t,S,"Server indicated an extension that was not requested");return}try{y.accept(me[B.extensionName])}catch{v(t,S,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[B.extensionName]=y}t.setSocket(S,M,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(p,t):p.end()}function ue(t,e){t._readyState=_.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Gs(t){return t.path=t.socketPath,bt.connect(t)}function $s(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=bt.isIP(t.host)?"":t.host),Ts.connect(t)}function v(t,e,s){t._readyState=_.CLOSING;let r=new Error(s);Error.captureStackTrace(r,v),e.setHeader?(e[Ot]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ue,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ue(t,e,s){if(e){let r=Ps(e)?e.size:Ws(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(s){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${N[t.readyState]})`);process.nextTick(s,r)}}function js(t,e){let s=this[x];s._closeFrameReceived=!0,s._closeMessage=e,s._closeCode=t,s._socket[x]!==void 0&&(s._socket.removeListener("data",de),process.nextTick(kt,s._socket),t===1005?s.close():s.close(t,e))}function Vs(){let t=this[x];t.isPaused||t._socket.resume()}function zs(t){let e=this[x];e._socket[x]!==void 0&&(e._socket.removeListener("data",de),process.nextTick(kt,e._socket),e.close(t[Is])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function vt(){this[x].emitClose()}function Hs(t,e){this[x].emit("message",t,e)}function Ys(t){let e=this[x];e._autoPong&&e.pong(t,!this._isServer,wt),e.emit("ping",t)}function Ks(t){this[x].emit("pong",t)}function kt(t){t.resume()}function Xs(t){let e=this[x];e.readyState!==_.CLOSED&&(e.readyState===_.OPEN&&(e._readyState=_.CLOSING,Ct(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ct(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Lt(){let t=this[x];if(this.removeListener("close",Lt),this.removeListener("data",de),this.removeListener("end",Nt),t._readyState=_.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[x]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",vt),t._receiver.on("finish",vt))}function de(t){this[x]._receiver.write(t)||this.pause()}function Nt(){let t=this[x];t._readyState=_.CLOSING,t._receiver.end(),this.end()}function Pt(){let t=this[x];this.removeListener("error",Pt),this.on("error",wt),t&&(t._readyState=_.CLOSING,this.destroy())}});var er=E((Fr,It)=>{"use strict";d();var Dr=Ie(),{Duplex:Zs}=g("stream");function Rt(t){t.emit("close")}function Qs(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ut(t){this.removeListener("error",Ut),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Js(t,e){let s=!0,r=new Zs({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(n,o){let f=!o&&r._readableState.objectMode?n.toString():n;r.push(f)||t.pause()}),t.once("error",function(n){r.destroyed||(s=!1,r.destroy(n))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,n){if(t.readyState===t.CLOSED){n(i),process.nextTick(Rt,r);return}let o=!1;t.once("error",function(l){o=!0,n(l)}),t.once("close",function(){o||n(i),process.nextTick(Rt,r)}),s&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,n,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,n,o)});return}t.send(i,o)},r.on("end",Qs),r.on("error",Ut),r}It.exports=Js});var Ft=E((Ar,Dt)=>{"use strict";d();var{tokenChars:tr}=G();function sr(t){let e=new Set,s=-1,r=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(r===-1&&tr[o]===1)s===-1&&(s=i);else if(i!==0&&(o===32||o===9))r===-1&&s!==-1&&(r=i);else if(o===44){if(s===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let f=t.slice(s,r);if(e.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);e.add(f),s=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(s===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let n=t.slice(s,i);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return e.add(n),e}Dt.exports={parse:sr}});var ur=E((Gr,$t)=>{"use strict";d();var rr=g("events"),_e=g("http"),{Duplex:qr}=g("stream"),{createHash:ir}=g("crypto"),Mt=Le(),D=Z(),nr=Ft(),or=Ie(),{CLOSE_TIMEOUT:ar,GUID:fr,kWebSocket:lr}=k(),hr=/^[+/0-9A-Za-z]{22}==$/,At=0,Wt=1,Gt=2,De=class extends rr{constructor(e,s){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ar,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:or,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=_e.createServer((r,i)=>{let n=_e.STATUS_CODES[426];i.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),i.end(n)}),this._server.listen(e.port,e.host,e.backlog,s)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=cr(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,n,o)=>{this.handleUpgrade(i,n,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=At}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Gt){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(te,this);return}if(e&&this.once("close",e),this._state!==Wt)if(this._state=Wt,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(te,this):process.nextTick(te,this);else{let s=this._server;this._removeListeners(),this._removeListeners=this._server=null,s.close(()=>{te(this)})}}shouldHandle(e){if(this.options.path){let s=e.url.indexOf("?");if((s!==-1?e.url.slice(0,s):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,s,r,i){s.on("error",qt);let n=e.headers["sec-websocket-key"],o=e.headers.upgrade,f=+e.headers["sec-websocket-version"];if(e.method!=="GET"){F(this,e,s,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){F(this,e,s,400,"Invalid Upgrade header");return}if(n===void 0||!hr.test(n)){F(this,e,s,400,"Missing or invalid Sec-WebSocket-Key header");return}if(f!==13&&f!==8){F(this,e,s,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){se(s,400);return}let l=e.headers["sec-websocket-protocol"],a=new Set;if(l!==void 0)try{a=nr.parse(l)}catch{F(this,e,s,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],c={};if(this.options.perMessageDeflate&&h!==void 0){let m=new D({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=Mt.parse(h);y[D.extensionName]&&(m.accept(y[D.extensionName]),c[D.extensionName]=m)}catch{F(this,e,s,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${f===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(y,p,u,S)=>{if(!y)return se(s,p||401,u,S);this.completeUpgrade(c,n,a,e,s,r,i)});return}if(!this.options.verifyClient(m))return se(s,401)}this.completeUpgrade(c,n,a,e,s,r,i)}completeUpgrade(e,s,r,i,n,o,f){if(!n.readable||!n.writable)return n.destroy();if(n[lr])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>At)return se(n,503);let a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ir("sha1").update(s+fr).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(r.size){let c=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;c&&(a.push(`Sec-WebSocket-Protocol: ${c}`),h._protocol=c)}if(e[D.extensionName]){let c=e[D.extensionName].params,m=Mt.format({[D.extensionName]:[c]});a.push(`Sec-WebSocket-Extensions: ${m}`),h._extensions=e}this.emit("headers",a,i),n.write(a.concat(`\r
4
- `).join(`\r
5
- `)),n.removeListener("error",qt),h.setSocket(n,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(te,this)})),f(h,i)}};$t.exports=De;function cr(t,e){for(let s of Object.keys(e))t.on(s,e[s]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function te(t){t._state=Gt,t.emit("close")}function qt(){this.destroy()}function se(t,e,s,r){s=s||_e.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${_e.STATUS_CODES[e]}\r
6
- `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
7
- `)+`\r
8
- \r
9
- `+s)}function F(t,e,s,r,i,n){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,F),t.emit("wsClientError",o,s,e)}else se(s,r,i,n)}});export{Z as a,ot as b,ht as c,Le as d,Ie as e,er as f,Ft as g,ur as h};
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{b as p}from"./chunk-GZPNIYVZ.js";import{d as v}from"./chunk-OWGSC52X.js";var f=v((T,y)=>{"use strict";p();var m="Function.prototype.bind called on incompatible ",O=Object.prototype.toString,w=Math.max,x="[object Function]",s=function(e,t){for(var r=[],n=0;n<e.length;n+=1)r[n]=e[n];for(var o=0;o<t.length;o+=1)r[o+e.length]=t[o];return r},F=function(e,t){for(var r=[],n=t||0,o=0;n<e.length;n+=1,o+=1)r[o]=e[n];return r},S=function(a,e){for(var t="",r=0;r<a.length;r+=1)t+=a[r],r+1<a.length&&(t+=e);return t};y.exports=function(e){var t=this;if(typeof t!="function"||O.apply(t)!==x)throw new TypeError(m+t);for(var r=F(arguments,1),n,o=function(){if(this instanceof n){var c=t.apply(this,s(r,arguments));return Object(c)===c?c:this}return t.apply(e,s(r,arguments))},d=w(0,t.length-r.length),l=[],u=0;u<d;u++)l[u]="$"+u;if(n=Function("binder","return function ("+S(l,",")+"){ return binder.apply(this,arguments); }")(o),t.prototype){var i=function(){};i.prototype=t.prototype,n.prototype=new i,i.prototype=null}return n}});var g=v((j,h)=>{"use strict";p();var E=f();h.exports=Function.prototype.bind||E});var M=v((P,b)=>{"use strict";p();var R=Function.prototype.call,q=Object.prototype.hasOwnProperty,A=g();b.exports=A.call(R,q)});export{g as a,M as b};
@@ -1,8 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{b as d}from"./chunk-GZPNIYVZ.js";d();import{setMaxListeners as b}from"node:events";var f=50;function c(r=f){let t=new AbortController;return b(r,t.signal),t}function m(r){if(r)return r instanceof AbortController?r.signal:r}function v(r,t){let e=c(t),n=m(r);if(!n)return e;if(n.aborted)return e.abort(n.reason),e;let a=new WeakRef(n),i=()=>{e.abort(a.deref()?.reason)};return n.addEventListener("abort",i,{once:!0}),e.signal.addEventListener("abort",()=>{a.deref()?.removeEventListener("abort",i)},{once:!0}),e}function g(r,t){let e=c(t?.maxListeners),n=r.find(o=>o?.aborted);if(n)return e.abort(n.reason),{signal:e.signal,cleanup:()=>{}};let a=[];for(let o of r){if(!o)continue;if(o.aborted){e.abort(o.reason);break}let u=()=>e.abort(o.reason);o.addEventListener("abort",u,{once:!0}),a.push(()=>o.removeEventListener("abort",u))}let i=t?.timeoutMs;if(i!==void 0&&i>0&&!e.signal.aborted){let o=setTimeout(()=>{e.abort(new DOMException("Operation timed out","TimeoutError"))},i);a.push(()=>clearTimeout(o))}let s=!1,l=()=>{if(!s){s=!0;for(let o of a)o()}};return e.signal.aborted?l():e.signal.addEventListener("abort",l,{once:!0}),{signal:e.signal,cleanup:l}}async function E(r,t){t?.throwIfAborted();let e=r();if(!t)return e;let n=()=>{},a=new Promise((i,s)=>{n=()=>s(t.reason),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,a])}finally{t.removeEventListener("abort",n),e.catch(()=>{})}}export{c as a,v as b,g as c,E as d};
4
- /**
5
- * @license
6
- * Copyright 2025 Matilda
7
- * SPDX-License-Identifier: Apache-2.0
8
- */